PHP / JSON data analysis in Javascript

I am trying to pass AJAX, JSON to PHP, and then PHP is returning some data, and I'm trying to parse it using Javascrpt.

From php server, I'm coming back,

    echo json_encode($data); 

    // it outputs ["123","something","and more something"]

and then on the client side,

success : function(data){

    //I want the data as following

    // data[0] = 123
    // data[1] = something
    // data[3] = and more something
}

But it gives like:

        data[0] = [ 
        data[1] = " 
        data[2] = 1

It reads every character, but I need strings from an array, not individual characters. What's going on here? Thanks in advance, I am new to Javascript and JSON, AJAX.

+5
source share
5 answers

JSON.parse(data) gotta do the trick.

+8
source

Check it out ... Should work

success: function (data) {

var result = data;

result=result.replace("[","");

result=result.replace("]","");

var arr = new Array();

arr=result.split(",")

alert(arr[0]); //123

alert(arr[1]); //something

alert(arr[2]); //......
}
+3
source

dataType ajax json. jQuery .

$.ajax({
    url : ...,
    data : ...,
    dataType : "json",
    success : function(json) {
        console.log(json);
    }
});

- PHP, JQuery , JSON.

header("Content-Type: application/json");
echo json_encode($data);
+2

, .

JSON.parse

and if broser doesn't support JSON then use json polyfill from https://github.com/douglascrockford/JSON-js

dataArray = JSON.parse(dataFomXHR);
+1
source

I'm not sure if this is what you want, but why don't you want php to return it in this format:

{'item1':'123','item2':'something','item3':'and more something'}

To do this, you need to make sure the array json_encode()is associative. It should be in the form below

array("item1"=>123,"item2"=>"something","item3"=>"more something");

You can even do stripslashes()it if some of the values ​​in the array may be URLs

Then you can do JSON.parse()in the JSON string and access the values

It will help!

+1
source

All Articles