json stringify 2 arrays needed to place them in variables using javascript - 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);
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.
How will I achieve that. PLease help/.

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.

Related

How can i get value?

How can I extract value from response?
Output of alert is [{"maturitydays":"120"}]
I only want value!!
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response);
}
})
});
It appears your response is inside an array due to the square brackets, this means you need to get the value through:
response[0]['maturitydays']
So your code will look like:
$("#selectCrop").change(function(){ //this ajax will bring default configured crop data
var cropid = $("#selectCrop option:selected").val();
var url = "<?php echo base_url();?>index.php/user/cropConfig/getData";
$.ajax({
data : {'cropid':cropid},
type : 'post',
url : url,
success :function(response) {
alert(response[0]['maturitydays']);
}
})
});
It's json.
Use json_decode to make it array then grab the value from the array (if you must).
$array = json_decode('{"maturitydays":"120"}',true);
$value=$array["maturitydays"];
Echo $value;
https://3v4l.org/Uc51m
The data that you get as response is a JSON array with a number of JSON objects. JSON (JavaScript object notation) can be used as a JavaScript object right away (as long as its not in string form, in which case it has to be parsed with JSON.parse).
When you receive the response you can access it as you would with a normal JavaScript array (in case you are sure its ALWAYS only 1 object, you can select the first index right away):
let obj = response[0];
When you got the object, just access the value you want as you would with a normal JavaScript object:
let val = obj.maturitydays;

How to split ajax result

$("select#product-id").change(function(){
$("input#product-name").val("Loading...");
var value = $(this).val();
$.ajax({
url: "http://localhost/api/purchase-entry-data.php",
data: {
product_id : value
},
type: "POST",
success: function(data){
$("input#product-name").val(data);
},
error: function (){
$("input#product-name").val("No Data Available");
}
});
});
I am tring to use ajax result in two places (there is two value in the ajax result 1. Product Name, 2. Product Size).
So how to split up that that result in two different values in php.
This depends how you are returning the data back to ajax. There are several ways you can do this.
Using split
In your purchase-entry-data.php file you could return data with a separator then use split to get both values. Just make sure you use a separator that will not be contained in the data returned. Here I used a pipe
echo "productDesc|productSize";
Then in jquery you can split it up and access each element in the array
var result= $(data).text().split('|');
var productDesc = result[0];
var productSize = result[1];
Using JSON
In your php file return the data in an array and JSON
<?php
$arr = array('productDesc' => 'Description', 'productSize' => 'Size');
echo json_encode($arr);
?>
Then in jquery access it like
data = $.parseJSON(data);

Loop Array to Modify Values (JavaScript to PHP and Back to JavaScript)

I'm working with JavaScript and PHP using arrays, the first step is create the array, here
var ListaA=[];
var i = 0, len = options.length;
while (i < len){
var tmp = {
'proyecto':'test',
'pendientes1':0,
'pendientes2':0,
'terminadas1':0,
'terminadas2':0,
'solucion':0
};
ListaA.push(tmp);
i++;
}
Then i send it to my PHP file like this
var laLista = JSON.stringify(ListaA);
$.get("php/operation.php?test="+ {'test' : laLista }, function( data ){
var tmp = {
'proyecto':""+value['proyecto']+"",
'pendientes1':""+value['pendientes1']+"",
'pendientes2':""+value['pendientes2']+"",
'terminadas1':""+value['terminadas1']+"",
'terminadas2':""+value['terminadas2']+"",
'solucion':""+value['solucion']+""
};
ListaA.push(tmp);
});
As you can see above i have ready the code to get the data which represents the array sent by the PHP file, so i got covered that part, my issue here is in my PHP file, here.
$arrayWork = json_decode($_POST['test']);
Then i want to loop, this time, just for testing i'm just taking one of the values and incresing it to watch the result, like this
foreach($arrayWork as $value){
$value['pendientes1']++; // this is not working for me
}
I got the following: "invalid argument supplied in foreach". So, what's wrong with my code? and which is the properly way to loop it and return it to my JavaScript?
I hope you can help me out with this issue. Thank you for your time and attention, good night.
Using this code
$arrayWork = json_decode($_POST['test']);
your json isn't really converted into an associated array, look at below
mixed json_decode ( string $json [, bool $assoc = false [, int $depth = 512 [, int $options = 0 ]]] )
assoc
When TRUE, returned objects will be converted into associative arrays.
To convert json object into an array just add true to the second parameter to it
$arrayWork = json_decode($_POST['test'], true);**strong text**
To increment an index value in an array
foreach($arrayWork $key => as $value){
$arrayWork['pendientes1']++;
}
Edited.
also since you are using $_POST method change your ajax from $.get to $.post
$.post("php/operation.php?test="+ {'test' : laLista }, function( data ){
var result = JSON.parse(data); // parse json string into json object
...
});
If you want to read $_POST, you have to make a POST request:
$.ajax({
url:'php/operation.php',
type:"POST",
data: { test: ListaA },
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})
You can't use $.post, because you have to set the contentType to JSON.
Important: you don't need to run JSON.stringifyyourself, jQuery will take care of it for you - so pass the original ListaA array.

how to retrieve array in hidden field

I am storing my array in hidden field
var myarray = [];
if ($(this).prop('checked')) {
myarray.push(val);
$('#myhidden').val(JSON.stringify(myarray));
}
how can I retrieve that array ? because I want that array to past it to other page using jquery.ajax
I tried this
var retarray = $('#myhidden').val();
["110","118"]
when I send that using jquery.ajax
$.ajax({
type: 'post',
dataType: 'json',
url: 'tootherpage.php',
data: 'param1=' + param1 + '&param_array=' + retarray,
success: function(data) {
}
});
it gives me error because it is not an array.
Thank you in advance.
You're converting your array to a string here:
$('#myhidden').val(JSON.stringify(myarray));
If you need it to be an array, then you need to parse this array back from the string
var retarray = JSON.parse($('#myhidden').val());
for example:
var array = [1,2,3,4]; // create an array
var stringarray = JSON.stringify(array); // convert array to string
var array2 = JSON.parse(stringarray); // convert string to array
Try this
var retarray = encodeURIComponent($('#myhidden').val());
Your ajax request is is using the method POST and you have specified a data type of json which means your http request is sending json in the body.
So you can send your whole request message as json, like this:
// get json from input
var retarray = $('#myhidden').val();
// parse json into js
var arr = JSON.parse(retarray);
// create your request data
var data = { param1: param1, param_array: arr };
// stringify
var json = JSON.stringify(data);
$.ajax({
type: 'post',
dataType: 'json',
url: 'tootherpage.php',
data: json, // the json we created above
success: function(data) {
}
});
Then in your php script you can deserialize the json message to a php object like so:
$json = file_get_contents('php://input'); $obj = json_decode($json)
You can do this :
$('#myhidden').val(myarray.split("|")); //set "0|1".split("|") - creates array like [0,1]
myarray = $('#myhidden').val().join("|"); //get [0,1].join("|") - creates string like "0|1"
"|" is a symbol that is not present in array, it is important.

Create array of arrays from JSON

I am receiving after an ajax call the following as response using in php json_encode:
"['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]", "['2013-02-27', 6]", "['2013-02-28', 6]", "['2013-03-01', 3]", ...
How can I make in JavaScript from this an array of arrays? Is this even possible? I mean, I've tried with jQuery makeArray or with parseJSON with no success. What is the most preferred method?
Edit:
function submitForm(t) {
$.ajax({type:'GET', url: 'charts.php', data:$(page_id).serialize(), success:
function(response) {
var myFanRemovesData = new Array(response);
var myChart = new JSChart(chart_id, 'line');
myChart.setDataArray(myFanRemovesData);
I have to use the array of arrays to set myFanRemovesData with it
1) strip out the double-quotes ("):
var json = json.replace(/"/g, '');
2) wrap the whole thing in square brackets:
json = "[" + json + "]";
3) replace the single-quotes with double-quotes (because the singles won't parse):
json = json.replace(/'/g, '"');
4) parse the json string:
var arrays = JSON.parse(json);
Here is a working example. It will alert the first date in the first array. (note: the data is pulled from the DIV to simulate the AJAX call and to avoid me having to mess around with escaping quote characters)
Try:
var response = ["['2013-02-24', 0]", "['2013-02-25', 0]", "['2013-02-26', 1]"];
for (var i = 0; i < response.length; i++) {
var cleaned = response[i].replace(/'/g, "\"");
response[i] = $.parseJSON(cleaned);
}
DEMO: http://jsfiddle.net/hu3Eu/
After this code, the response array will contain arrays, made out of the original strings.
Just example.. because you haven't provide us with any code...
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" },
dataType: 'json',
}).done(function( responde ) {
$.each(responde, function(i, v){
alert(v.0 + ' --- ' + v.1);
});
});
If you receive and expecting json you directly can use it as array/object :)
If its array you have to make a each loop so you can access each value..

Categories