2

PHP (processing.php):

$responce["x"] = 0;
$responce["y"] = [1, 3];
echo json_encode($responce);

javascript:

$.get("processing.php", function(data){
   alert("Data: " + data)
});

Output (alert):

Data: {"x":0,"y":["1","3"]}

I need to access the variable x, and the array y in javascript ?!!

0

3 Answers 3

5

Parse the JSON string with $.parseJSON().

Then, access data.x.

$.get("processing.php", function(data){
   data = $.parseJSON(data);
   var x = data.x;
});

Alternatively, you can set the dataType to json or use $.getJSON() which will automatically do it.

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

1 Comment

As a rule I set the dataType to json if I know that the data returned is always going to be jSON.
3

According to your response Data: {"x":0,"y":["1","3"]}

$.get("processing.php", function(data){
    alert(data.x); // Will alert "0"
    alert(data.y[0]); // Will alert "1"
    alert(data.y[1]); // Will alert "3"
}, "json");

Comments

1

With the jQuery.ajax Method you have the possibility to set the dataType attribute to json. Then you can have a function success: function ( data ) { alert (data.x + data.y); }. For more infos look at the documentation at your own.

Edit: jQuery.getJSON() is what you are looking for... it is like the jQuery.get method but parses the result to a javascript object.

Your code would than look like this:

$.getJSON("processing.php", function(data){
    var x = data.x;
    var y = data.y;
});

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.