Multiple return values from PHP with jQuery AJAX

Asked
Active3 hr before
Viewed126 times

7 Answers

returnvaluesmultiple
90%

Meta Stack Overflow , Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers , Stack Overflow Public questions & answers ,Stack Overflow em Português

Example:

< ? php echo json_encode(array("a" => "valueA", "b" => "valueB")); ? >

In Javascript:

$.getJSON("myscript.php", function(data) {
   alert("Value for 'a': " + data.a + "\nValue for 'b': " + data.b);
});
load more v
88%

Use json_encode() to convert an associative array from PHP into JSON and use $.getJSON(), which will return a Javascript array.,Then you need to encode your response as a JSON Array:,Why don't you return a JSON object. This way you can easily put many different results inside the ajax response.,Make your response return JSON, you'll need to change your jQuery to this, so the expected dataType is json:

I'm using this jQuery code:

$.ajax({
   type: "POST",
   url: "customerfilter.php",
   data: dataString,
   cache: false,
   success: function(html) {
      $(".custName").html(html);
   }
});

How can i do something like this: $(".projDesc").html(html1); So i can split the returned results into two html elements?

echo "<p>" .$row['cust_name']. "</p>";
load more v
72%

Sometimes we need our server to return more than 1 value to our Jquery. And those 2 values need to be presented in the page.,Thank you swadesh, i was confused to make a make this on alternative idea, its really helpful,We can do this usgin jquery. There are 2 methods., You are commenting using your WordPress.com account. ( Log Out /  Change )

Example:

< ? php echo json_encode(array("a" => "valueA", "b" => "valueB")); ? >
load more v
65%

I have a jQuery post function that returns a response on success after the click of a div. However, I would like to return multiple variables on success. Do I have to use JSON, and if so, is it possible to integrate it into the $.ajax function after success?,Anyhow, I see two important points to consider for multiple return values:,Each number of return values needs a tuple-class of its own. There might be something like that provided in the Functional Java library. For reference, here's an N-Tuple implementation.,As boring as it is, I'd recommend creating a separate class to hold all the response values and declare that as the method return type. That way the meaning of each value can be highlighted.

I have a jQuery post function that returns a response on success after the click of a div. However, I would like to return multiple variables on success. Do I have to use JSON, and if so, is it possible to integrate it into the $.ajax function after success?

$.ajax({
   type: "POST",
   data: "action=favorite&username=" + username + "&topic_id=" + topic_id + "&token=" + token,
   url: "favorite.php",
   success: function(response) {

   }
});
load more v
75%

I have a question as to how to assign values to PHP variables after they are passed from the jQuery Ajax call, particularly through the data: specification. This is what the .ajax() call looks like:,So, I have just learned that the name of the parameter is how the PHP code must fetch the passed value; therefore, if it is set to confirmEmail, then I must call it as $_POST[‘confirmEmail’]; in my PHP file.,It’s still saying undefined variable for the declaration of $origEmail and $confirmEmail, so I guess there may be something wrong with the .ajax() call.,I want to be able to receive those parameters into the PHP script for all the values into the following PHP script (filename: confirmform.php).

I have a question as to how to assign values to PHP variables after they are passed from the jQuery Ajax call, particularly through the data: specification. This is what the .ajax() call looks like:

$("#submissionform form").submit(function(e) {
var origEmail = $('#go').val();
var confirmEmail = $("#confirmemail").val();
var name = $("#name").val();
var age = $("#age").val();
var country = $("#country").val();

$.ajax({
   type: "POST",
   dataType: 'json',
   cache: false,
   url: "Scripts/confirmform.php",
   data: {
      origEmail: origEmail,
      confirmEmail: confirmEmail,
      name: name,
      age: age,
      country: country
   },
   success: function(data) {
      testSecondResults(data);
   }
});
});
});

I want to be able to receive those parameters into the PHP script for all the values into the following PHP script (filename: confirmform.php).

<
? php
$instance = new CheckForm;
$instance - > checkSubmission();

class CheckForm {
   public
   function checkSubmission() {
      $response = array("validation" => " ", "message" => " ");
      if ($_POST['country'] != "Select Country") {
         if (isset($_POST['confirmemail']) && isset($_POST['name'])) {
            $origEmail = $_GET['go'];
            $confirmEmail = $_POST['confirmemail'];
            if ($origEmail == $confirmEmail) {
               $name = htmlspecialchars($_POST['name']);
               $ageRange = $_POST['age'];
               $country = $_POST['country'];

               require_once('databasewriter.php');
               $dbWriter = new DatabaseWriter;
               $dbWriter - > writeUserToDatabase($confirmEmail, $name, $ageRange, $country, $category);
               $response = array("validation" => "pass", "message" => 'Thanks for joining the e-mail list, '.$name.
                  ', under the e-mail address, '.$confirmEmail.
                  '.');
            } else {
               $response = array("validation" => "fail", "message" => 'E-mail addresses don\\'
                  t match.
                  ');
                  die();
               }
            } else {
               if (!isset($_POST['confirmemail'])) {
                  $response = array("validation" => "fail", "message" => 'Confirmation e-mail not entered.');
               }
               elseif(!isset($_POST['name'])) {
                  $response = array("validation" => "fail", "message" => 'Please enter a name.');
               }
            }
         } else {
            $response = array("validation" => "fail", "message" => 'Please select a country.');
         }
         echo json_encode($response);
      }
   } ?
   >
load more v
40%

$(document).ready(function(){
    $.ajax({
        url: 'ajaxfile.php',
        type: 'get',
        dataType: 'JSON',
        success: function(response){
            var len = response.length;
            for(var i=0; i<len; i++){
                var id = response[i].id;
                var username = response[i].username;
                var name = response[i].name;
                var email = response[i].email;

                var tr_str = "<tr>" +
                    "<td align='center'>" + (i+1) + "</td>" +
                    "<td align='center'>" + username + "</td>" +
                    "<td align='center'>" + name + "</td>" +
                    "<td align='center'>" + email + "</td>" +
                    "</tr>";

                $("#userTable tbody").append(tr_str);
            }

        }
    });
});
load more v
22%

dataFilter Type: Function( String data, String type ) => Anything A function to be used to handle the raw response data of XMLHttpRequest. This is a pre-filtering function to sanitize the response. You should return the sanitized data. The function accepts two arguments: The raw data returned from the server and the 'dataType' parameter. ,Save some data to the server and notify the user once it's complete.,The beforeSend, error, dataFilter, success and complete options all accept callback functions that are invoked at the appropriate times.,The available data types are text, html, xml, json, jsonp, and script.

$.ajax({
         accepts: {
            mycustomtype: 'application/x-some-custom-type'
         }, // Instructions for how to deserialize a `mycustomtype`  converters: {    'text mycustomtype': function(result) {      // Do Stuff      return newresult;    }  },   // Expect a `mycustomtype` back from server  dataType: 'mycustomtype'});
load more v

Other "return-values" queries related to "Multiple return values from PHP with jQuery AJAX"