27

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>";

thats the PHP i'm using and i want to echo another statement which i can put into another HTML element

Does this make sense?

4 Answers 4

59

Use json_encode() to convert an associative array from PHP into JSON and use $.getJSON(), which will return a Javascript array.

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);
});
Sign up to request clarification or add additional context in comments.

3 Comments

Do you use the .getJson inside the success function of the ajax post or completely separate of it?
@Arken I'm not sure what you mean. getJSON() takes a URL and success handler function that receives the decoded data as its argument. You needn't call it again in the handler, since the request has already been executed.
Great hint. I had to add var myData = JSON.parse(response); to convert the response from AJAX success, but same idea (instead of getJSON)
50

Make your response return JSON, you'll need to change your jQuery to this, so the expected dataType is json:

$.ajax
({
    type: "POST",
    url: "customerfilter.php",
    dataType: 'json',
    cache: false,
    success: function(data)
    {
        $(".custName").html(data.message1);
        $(".custName2").html(data.message2);
    }
});

Then you need to encode your response as a JSON Array:

 <?php echo json_encode(
      array("message1" => "Hi", 
      "message2" => "Something else")
 ) ?>

1 Comment

Should be dataType: 'json'. You are missing the quotes.
3

Why don't you return a JSON object. This way you can easily put many different results inside the ajax response.

Comments

0

You can use a separator and join the values like this in your response

echo $value1.'|'.$value2;

Now you can use JavaScript method split("|") as below:

var myarray = response.split("|");
var value_1 = myarray[0];
var value_2 = myarray[1];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.