Ligthers Ligthers - 3 days ago 3
PHP Question

json stringify 2 arrays needed to place them in variables using javascript

I have an ajax response in json format. Then in my javascript (ajax response success) i have the two arrays stringify. Now I need to place data in one curly bracket to 2 variables and then other curly bracket in another 2 variables.

Here's the code

var results = JSON.stringify(result).substr(1,JSON.stringify(result).length-2);


Here's the ajax(.js file)(part of it now whole code)

$.ajax({
url: "ajax/default_q.php",
dataType: "json",
type: 'POST',
data: {dtime: n},

success: function(result) {
var results = JSON.parse(result);
var mtime = results.microtime;
var srp = results.srp;

alert(mtime);
alert(srp);


Here's the php

$sql = "SELECT microtime,srp FROM loading WHERE submit_id = 'XXXXXXXXXXXXXXXXXX' AND microtime BETWEEN UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL 30 day)) and 1480573758";
$res = mysqli_query($GLOBALS['link'],$sql);
while($row = mysqli_fetch_assoc($res)){
$content[] = $row;
}
echo json_encode($content);


enter image description here

Ok. I want the microtime which is highligthed in yellow be stored in variable a so if I alert the a it will look like the photo below although not exactly the same. And same as the srp.

enter image description here

How will I achieve that. PLease help/.

Answer

You can parse your JSON ajax response and traverse it as a object rather than using substr to break the string.

var results = JSON.parse(result);
var mtime = results[0].microtime;
var srp = results[0].srp;

Update

Since you have already used dataType: "json" jQuery has already parsed JSON string into object. You don't have to explicitly parse JSON again. Here is the updated code:

var mtime = results[0].microtime;
var srp = results[0].srp;

You can loop through the array to traverse through all values.

Comments