0

My wish is to send some information in a datastring through AJAX to a PHP page and then return variables for me to separate and ask jQuery to fill out in different elements. So that it would be able for me to just say:

$('.elemA').html($variableA);
$('.elemB').html($variableB); etc.

But I am not sure if it is possible or how to do it.. Maybe it can return an array for me to separate somehow? I don't know.


If anyone else finds this question - this script helped me out and actually showed me the meaning of the JSON encoding: http://www.jonsuh.com/demo/jquery-ajax-call-to-php-script-with-json-return

2
  • 3
    php arrays mean nothing to JS, but you can take a PHP array and json_encode() it, which jquery can take and convert to a javascript array. Commented Jan 25, 2013 at 16:49
  • look into jquery ajax. it's very easy to use: api.jquery.com/jQuery.ajax Commented Jan 25, 2013 at 16:51

1 Answer 1

3

You should use json_encode($array). Which uses JSON to encode your array and return a data string that can be read easily by Javascript.

To convert it to a Javascript array you can use parseJSON() or as suggested by @BishopZ use JSON.parse(ajaxResponse), which is built in most modern browsers.

Sign up to request clarification or add additional context in comments.

3 Comments

How do I create a javascript array afterwords? And How do I separate the variables, and use them?
@PhilipJensBramsted, parseJSON() is there for you.
In most browsers the Javascript syntax to read the JSON from the ajax response is JSON.parse(ajaxResponse). The JSON object is built into all modern browsers.

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.