$("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);
Related
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;
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.
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.
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 + '¶m_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.
I am echoing two array values from PHP. How do I differentiate these values in ajax.
if(#mysql_select_db("trainer_registration"))
{
$select_query_num = #mysql_query("select program_id,facilitator_id,availability_status from program_facilitator");
$select_query_name = #mysql_query("select facilitator_id,firstname,lastname,email_id from facilitator_details");
$num_rows = #mysql_num_rows($select_query_num);
$trainerdetails = [];
$traineravaildetails = [];
$i = 0;
while($row = #mysql_fetch_assoc($select_query_num))
{
$trainerdetails[$i]['pgidi'] = $row['program_id'];
$trainerdetails[$i]['facilitatorid'] = $row['facilitator_id'];
$trainerdetails[$i]['avail_status'] = $row['availability_status'];
$trainerdetails[$i]['idi'] = $row['facilitator_id'];
$i++;
}
while($row1 =#mysql_fetch_assoc($select_query_name))
{
$traineravaildetails[$i]['facilitatorid'] = $row1['facilitator_id'];
$traineravaildetails[$i]['firstname'] = $row1['firstname'];
$traineravaildetails[$i]['lastname'] = $row1['lastname'];
$traineravaildetails[$i]['emailidvalue'] = $row1['email_id'];
$i++;
}
echo json_encode($trainerdetails);
echo json_encode($traineravaildetails);
}
?>
function loadavailabletrainers (m) {
$.ajax({
url: 'assignavailtrainers.php',
data: { action:'test' },
type: 'post',
success: function(output) {
console.log(output);
}
});
}
I've seen a examples of multiple return values from php and handling them in ajax, but I didn't understand them. Can someone please explain how to differentiate output values in my case?
OUTPUT:
[[{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"1","avail_status":"2","idi":"1"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"1","idi":"2"},{"pgidi":"3","facilitatorid":"2","avail_status":"2","idi":"2"}],{"7":{"facilitatorid":"1","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*******#gmail.com"},"8":{"facilitatorid":"2","firstname":"Vignesh","lastname":"Anandakumar","emailidvalue":"vign*****#gmail.com"},"9":{"facilitatorid":"3","firstname":"Vignesh","lastname":"Anand","emailidvalue":"v*****#hotmail.com"},"10":{"facilitatorid":"4","firstname":"Vignesh","lastname":"Anand","emailidvalue":"****#live.com"}}]
It's a nice practice to send only one stream of values so you can process it all at once.
First, you could create a container array:
$data = array('trainerdetails' => $trainerdetails,
'traineravaildetails' => $traineravaildetails);
Then
echo json_enconde($data);
This will generate a merged output.
The encoded string returned by your PHP code needs to be decoded in the client side (more details: Parse JSON in JavaScript?). Because of that, you could use $.getJSON(), which is an alias for a specific call to $.ajax (doc: http://api.jquery.com/jquery.getjson/).
The 'success' function will pass a 'key'=>'value' array data. In this case you'd need to treat the value as they may contain extra levels of arrays. It helps if you can visualize your data structure as tree view, like this: http://jsonviewer.stack.hu/ (paste your output there).
I hope it helps!