How do I differentiate array values from PHP in Ajax success function? - javascript

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!

Related

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.

PHP to JSON Array Output is Wrong

What I am trying to do doesn't feel difficult, but for some reason I can't seem to find the correct way to ouput this JSON array, from php.
PHP code:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$a = array();
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP DateTime
$a = array(
"time" => $dt->format('Y-m-d H:i:s'),
"signal" => $row['signal'],
"symbol" => $row['symbol'],
"price" => $row['price'],
"timeframe" => $row['timeframe'],
"epoch" => $row['time']);
echo json_encode($a, JSON_UNESCAPED_SLASHES);
}
Output:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
{
"time":"2016-11-14 17:07:59",
"signal":"Sell",
"symbol":"GBPJPYecn",
"price":"135.13200",
"timeframe":"M1",
"epoch":"1479143279"
}
The correct output should have },{ NOT }{ between each object.
What I am ultimately trying to do:
function getTrades(a) {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "core/engine.php",
data: "q=data&account="+a,
dataType: "html", //expect html to be returned
success: function(response){
if(response=="nologin") {
alert("Sorry, but either your account is not activated or your login is incorrect!");
} else {
var j = $.parseJSON(response);
$.each(j, function (k, v) {
$("#trades").html('<span class="tradesignal"><!-- span class="signalarrowup"></span-->'+v.time+'<span style="color:#2DC14E;"> '+v.signal+'</span>   <button class="tsym" id="sym_'+v.epoch+'">'+v.symbol+'</button>  '+v.price+'  '+v.timeframe+'</span>');
});
}
//alert(response);
console.log(response);
}
});
}
Each {json},{json} object will have its data printed into a span on an html page.
Appreciate the guidance!
Try creating a results array and push each one of the objects there, then after the loop finishes, convert the array to json and print it.
example:
$results = array();
$i = 0;
while($row = mysqli_fetch_array($result)){
//your code here
$a = array("time" => ....);
$results[] = $a; //this will add $a to $results
}
echo json_encode($results, JSON_UNESCAPED_SLASHES);
Just to add a little more explanation in addition to the code the other answers are suggesting. The problem is, you aren't outputting a JSON array. Each time you do
echo json_encode($a, JSON_UNESCAPED_SLASHES);
inside your loop, you output a valid JSON object like:
{
"time":"2016-11-14 17:23:00",
"signal":"Sell",
"symbol":"XAUUSDecn",
"price":"1221.64000",
"timeframe":"M1",
"epoch":"1479144180"
}
However, when you output the subsequent objects, getting a result like
{
"time": ...
}
{
"time": ...
}
You no longer have valid JSON. Even though each of the individual objects is valid, concatenating them together isn't. Simply adding a comma between the objects will still not make it valid. In order to produce an actual JSON array, the comma separated objects will need to be enclosed in square brackets like this:
[
{
"time": ...
},
{
"time": ...
}
]
That's why you need to add each of the arrays you're creating in the loop to an outer array and then json_encode the whole thing after the loop. The outer PHP array will become the outer JSON array you need.
As Xorifelse said, you want to put the data in an array, and then call json_encode on the array. Here is a code that should work:
$a = array();
$i=0;
while($row = mysqli_fetch_array($result))
{
$i++;
$epoch = $row['time'];
$dt = new DateTime("#$epoch"); // convert UNIX timestamp to PHP Date
$a[] = array("time" => $dt->format('Y-m-d H:i:s'), "signal" => $row['signal'], "symbol" => $row['symbol'], "price" => $row['price'], "timeframe" => $row['timeframe'],"epoch" => $row['time']);
}
echo json_encode($a, JSON_UNESCAPED_SLASHES);

jQuery submitHandler: function not displaying data

I am using jQuery to input data to a php file and return the results via json. However, the json is appearing in firebug, but the variable 'messageOutput' is not displaying results on the form. If I replace 'messageOutput' with 'msg.box' then it prints fine.
If I enter more than 1 item on my form, then it errors with: 'object object'.
Can someone point out where my error is as I have been struggling with this for ages. If you need to see any further code, please ask. many thanks.
jQuery code:
submitHandler: function() {
if ($("#BA_boxform").valid() === true) {
var data = $("#BA_boxform").serialize();
$.post('/domain/admin/requests/boxes/boxesadd.php', data, function(msg) {
var messageOutput = '';
for (var i = 0; i<msg.length; i++){
messageOutput += msg[i].box+' ';
}
$("#BA_addbox").html("You have entered box: " + "<b>" + messageOutput + "</b><br /> You may now close this window.");
$("#BA_boxform").get(0).reset();
}, 'json');
} else
{
return;
}
},
success: function(msg) {
//$("#BA_addbox").html("You have entered a box");
//$("#BA_boxform").get(0).reset();
}
boxesadd.php
<?php
$dept = mysql_real_escape_string($_POST['customerdept']);
$company = mysql_real_escape_string($_POST['BA_customer']);
$address = mysql_real_escape_string($_POST['customeraddress']);
$service = mysql_real_escape_string($_POST['BA_service']);
$box = mysql_real_escape_string($_POST['BA_box']);
$destroydate = mysql_real_escape_string($_POST['BA_destdate']);
$authorised = mysql_real_escape_string($_POST['BA_authorised']);
$submit = mysql_real_escape_string($_POST['submit']);
$boxerrortext = 'You must enter a box for intake';
$array = split('[,]', $_POST['BA_box']);
if (isset($_POST['submit'])) {
foreach ($array as $box) {
if (empty($box)) {
$error = array('boxerrortext'=>$boxerrortext);
$output = json_encode($error);
echo $output;
}
else
{
$form=array('dept'=>$dept,
'company'=>$company,
'address'=>$address,
'service'=>$service,
'box'=>$box,
'destroydate'=>$destroydate,
'authorised'=>$authorised,
'submit'=>$submit);
$result=json_encode($form);
echo $result;
?>
its hard to debug it without knowing what the the request response looks like. Are you sure that the server returns an array? I'm not familiar with php, so i am not to helpful there, looking quickly it seems that the php 'array' is really more akin to a js object literal then a js array. I.e. it looks like it is a bunch of key/value pairs.
in which case, you should use the for/in loop instead of the for/each
for ( var key in msg )
messageOutput += msg[key] // => concats dept, company, address, etc
if you are really expecting an array of those objects (where you have a bunch of objects with the prop 'box') then you are doing it correctly in the javascript but you may not be sending the right object back from the server.
can you pop open the dev panel/firebug and show us what is being returned from the server?
try adding:
console.log($.isArray(msg))
and seeing if it returns true or not. One way of ensuring what is returned is an array is to use, what i call a splat utility:
function splat(obj){
return $.isArray(obj) ? obj : [ obj ];
}
this makes sure you are always dealing with an array, albeit sometimes an array of one time

JSON for jqPlot

I would like to use jqPlot usinge data from server side coming in JSON, like described in this example: http://www.jqplot.com/tests/data-renderers.php
My code is nearly the same like the example:
function myGraph(jsonurl) {
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
// have to use synchronous here, else the function
// will return before the data is fetched
async: false,
url: url,
dataType:"json",
success: function(data) {
ret=data;
console.warn(data);
}
});
return ret;
};
var plot1 = $.jqplot('chartdiv', jsonurl, {
title: 'myTitle',
dataRenderer: ajaxDataRenderer,
dataRendererOptions: { unusedOptionalUrl: jsonurl },
series: [{
label: 'myLabel',
neighborThreshold: -1
}],
axes: {
xaxis: {
renderer: $.jqplot.DateAxisRenderer,
// min:'August 1, 2010 16:00:00',
tickInterval: '2 months',
tickOptions:{formatString:'%Y-%m-%d.%H:%M:%S'}
},
yaxis: {
tickOptions:{formatString:'$%.2f'}
}
},
});
On server side i'm using PHP (and Yii). The webpage returns an array, which is encoded to JSON by using CJSON::encode($resultArray); (this Yii function passed trough to the PHP JSON encode function).
The Results from the PHP script lookes like that:
{"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5}
The Ajax request on client side resolved something like this (output from console.info(); )
Object { 2011-04-25 14:46:40=2, 2011-04-26 14:46:40=3, ...}
Probably, jqPlot expect the following format:
[[["2011-04-25 14:46:40":0],["2011-04-26 14:46:40",3],["2011-04-27 14:46:40",0]]]
All the time i get the error uncaught exception: [object Object]
What is wrong?
Is there a way to convert the object for to the typical array form?
Thank you
I have something like this . I had 2 arrays for values,labels .You should construct string as below from arrays .
$size = count($labels);
for ($i = 0; $i < $size; $i++) {
$result = $result . "['" . $labels[$i] . "'," . $values[$i] . "]";
if($i != $size -1 ){
$result = $result . ",";
}
}
OR if you dont have 2 arrays and just have this string {"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5} you can replace { with [ , } with ] and , with ],[ . A dirty but quick solution .
After above code you might need to append '[' and ']' on both sides and return value.
Do not parse the result on the client side, jquery will do much better. Actually, the array you need for jqplot is in fact valid json. All you have to do is prepare your data and create the appropriate array structure in PHP:
$pairs = array(1=>2, 3=>5, 4=>7, 5=>12, 7=>23); // simple example
$result = array();
foreach ($pairs as $label => $value) {
$result[] = array($label,$value); // make a "small" array for each pair
}
echo json_encode(array($result)); // wrap the result into another array; multiple plot data go like "array($result, $result2, ...)"
The result looks like this:
[[[1,2],[3,5],[4,7],[5,12],[7,23]]]
and is excatly what you need.
From http://www.jqplot.com/tests/date-axes.php
Note, although jqPlot will parse most any human readable date, it is safest to use javascript time stamps when possible. Also, it is best to specify a date and time and not just a date alone. This is due to inconsistent browser handling of local time vs. UTC with bare dates.
And example data from site:
var line1=[['2008-09-30 4:00PM',4], ['2008-10-30 4:00PM',6.5], ['2008-11-30 4:00PM',5.7], ['2008-12-30 4:00PM',9], ['2009-01-30 4:00PM',8.2]];
So you need array filled with 2 element arrays. First string with date (use timestamp if can) and X value. I've tried to find input format for datetime parsing or something like that but with no result.
You generated
{"2011-04-25 14:46:40":2,"2011-04-26 14:46:40":3,"2011-04-27 14:46:40":5}
which is object with 3 fields. First field name is "2011-04-25 14:46:40" and it's value set to 2. You need to generate array like this:
[["2011-04-25 14:46:40", 0],["2011-04-26 14:46:40", 3],["2011-04-27 14:46:40", 0]]
JSFiddle with your data seems to work - so don't need timestamps ;)
http://jsfiddle.net/zpygcvps/1/
sine curve with PHP json_encode function
server side
<?php
$y = array();
$index = 0 ;
for($x = 0 ; $x< 13 ; $x += 0.5) {
$y[$index] = sin($x);
$index++ ;
}
$series = array();
$series[0] = $y ;
$data = json_encode($series);
echo $data;
?>
client side
<script type="text/javascript">
$(document).ready(function(){
var ajaxDataRenderer = function(url, plot, options) {
var ret = null;
$.ajax({
async: false,
url: url,
dataType:"json",
success: function(data) {
ret = data;
}
});
return ret;
};
// The url for our json data
var jsonurl = "/test/chart/jqplot-data.php";
var plot2 = $.jqplot('chartdiv', jsonurl,{
title: "AJAX JSON Data Renderer",
dataRenderer: ajaxDataRenderer,
dataRendererOptions: {
unusedOptionalUrl: jsonurl
}
});
});
</script>

Categories