Ajax result as array and JSON.parse error - php

I have coded an ajax request and the data is returned as an array to be used in a timepicker.
Ajax Call:
<script type="text/javascript">
$.ajaxSetup({ cache: false });
var consultdate;
var userid;
var cat;
var timezone;
var consultstart;
var consultend;
$('#consultdate').change(function() {
consultdate = $('#consultdate').val();
userid= '<?php echo $user_id;?>';
cat = '<?php echo $category;?>';
timezone = '<?php echo $time_zone;?>';
consultstart = '<?php echo $consultation_start;?>';
consultend = '<?php echo $consultation_end;?>';
//alert(consultdate);
$.ajax({
type: "POST",
url: 'user_date-time_qry.php',
cache: false,
dataType : "text",
data: {consultdate : consultdate, userid : userid, cat : cat, timezone : timezone, consultstart : consultstart, consultend: consultend },
success: function(data)
{
if (!$('input#consulttime').data("set")) {
alert(data);
var result = $.parseJSON(data);
$("input#consulttime").val('');
$('input#consulttime').prop("disabled", false);
$('input#consulttime').timepicker('remove').timepicker({'timeFormat': 'h:i A','disableTextInput': true, 'minTime':result[0] ,'maxTime': '<?php echo $consultation_end; ?>','step': 15,'disableTimeRanges':result[1]});
}
},
error : function() {
alert("Error while loading data");
}
});
});
</script>
I expect var result to be an array of json encoded values, which is used in minTime as result[0] and disableTimeRanges as result[1]
The relevant portion of user_date-time_qry.php is as follows:
UPDATED: user_date-time_qry.php
$consultation_start = '"'.$consultation_start. '"';
$consult_time_UTC = '['.implode(',',$consult_time_UTC).']';
$prebooked_time_UTC = $consult_time_UTC ; //require format as ['8.30 AM', '8.45 AM'], ['12:15 PM', '12:30 PM']
echo $result = array($consultation_start, $prebooked_time_UTC);
$result = array($consultation_start, $prebooked_time_UTC);
foreach ($result as $results) {
echo $results;
}
In console
Getting value as "06:00 PM"[]
"06:00 PM" is value 1 && [] is value 2. How to get it as separate values in ajax response ?
Update:
Since i am unable to comprehend it, trying another solution with 2 ajax calls. Thanks for all the feedback anyway.

Change this line
echo $result = array($consultation_start, $prebooked_time_UTC);
to this
$result = array($consultation_start, $prebooked_time_UTC);
echo json_encode($result);
Actually to get data in JSON format in PHP you can just store all the data in an array and use json_encode function to convert them.

The issue is here:
echo $result = array($consultation_start, $prebooked_time_UTC);
you cannot echo an array, instead you have to use json_encode like:
echo json_encode(array($consultation_start, $prebooked_time_UTC));
and do not wrap the values in quotes like:
'"'.$consultation_start. '"'

simple way:--
The data is coming back as the string representation of the JSON and you aren't converting it back to a JavaScript object. Set the dataType to just 'json' to have it converted automatically.
Example Like:--
$.ajax({
type: "POST",
url: 'user_date-time_qry.php',
cache: false,
dataType : "json",
data: {consultdate : consultdate, userid : userid, cat : cat, timezone : timezone, consultstart : consultstart, consultend: consultend },
success: function(data)
{
//ENTER CODE
},
error : function() {
alert("Error while loading data");
}
});

Anoter example using this way:--
user_date-time_qry.php file all convert into json format using below example all array convert into json format using this way:--
<?php
$marks = array(
"mohammad" => array (
"physics" => 35,
"maths" => 30,
"chemistry" => 39
),
"qadir" => array (
"physics" => 30,
"maths" => 32,
"chemistry" => 29
),
"zara" => array (
"physics" => 31,
"maths" => 22,
"chemistry" => 39
)
);
echo json_encode($marks);
?>
These respone provide (ALL DATA CONVERT INTO JSON FORMAT):--
{"mohammad":{"physics":35,"maths":30,"chemistry":39},"qadir":{"physics":30,"maths":32,"chemistry":29},"zara":{"physics":31,"maths":22,"chemistry":39}}

Related

Sending a multidimensional array with ajax

I have multidimensional array on client side, when I send that array to a PHP server, the array is received as string.
My code like this
let data_barang = [];
var nama_barang = $("#nama_barang_add").val();
var id_barang = $("#nama_barang_add").data("id_barang");
var perkiraan = $("#nama_barang_add").data("perkiraan");
var qty = $("#qty_add").val();
var satuan = $("#satuan_add").val();
data_barang.push([nama_barang, qty, satuan, id_barang, perkiraan]);
$.ajax({
url: '<?= base_url("Admin/Pengadaan/tambahSPB") ?>',
type: 'POST',
dataType: 'json',
data: {
id_rab: id_rab,
tgl_order: tgl_order,
id_supplier: id_supplier,
kode_supplier: kode_supplier,
alamat_supplier: alamat_supplier,
nama_supplier: nama_supplier,
provinsi_supplier: provinsi_supplier,
data_barang: data_barang // data barang is multidimensional array
},
success: function(data) {
alert(data.data_barang);
});
Server side code:
$data_barang[] = $this->request->getPost("data_barang");
$dataStatus = [
"message" => $message,
"detail" => $data_detail,
"data_barang" => $data_barang
];
echo json_encode($dataStatus);
I tried to use json.stringifiy on the client side and on server side I use json_decode, but it did not work
convert your array to string with JSON.stringify
data: {
id_rab: id_rab,
tgl_order: tgl_order,
id_supplier: id_supplier,
kode_supplier: kode_supplier,
alamat_supplier: alamat_supplier,
nama_supplier: nama_supplier,
provinsi_supplier: provinsi_supplier,
data_barang: JSON.stringify(data_barang) // data barang is multidimensional array
}
you can check array with
$data = json_decode($_POST['data_barang']);
print_r($data);

Parse JSON in JQuery and set in inputs

I'm implementing a web and I need to use AJAX+JQuery to complete some fields without recharging the page. I test it and it works correctly but when I tried to use a real JSON (created by MySQL) I'm not be able to parse it.
The format of JSON is this:
[
{
"ID":"5847"
},
{
"Usuari":"admin"
},
{
"Nom":"admin"
},
{
"Cognom1":null
},
{
"Cognom2":null
},
{
"Tipus":"admin"
},
{
"Progres":"0"
}
]
And the AJAX code is this:
$(document).ready(function(){
$("#botoBuscar").click(function(){
$.ajax({url: "http://192.168.1.39/web/api/buscarUser.php?user="+ $("#userInput").val(), success: function(data){
var obj = $.parseJSON(data);
$("#id").val(obj[0]['ID']);
$("#user").val(obj[0]['Usuari']);
$("#nom").val(obj[0]['Nom']);
$("#cognom1").val(obj[0]['Cognom1']);
$("#cognom2").val(obj[0]['Cognom2']);
$("#tipus").val(obj[0]['Tipus']);
$("#progres").val(obj[0]['Progres']);
}});
});
});
If I print only the var "data", it prints correctly the full JSON, but if I try to use data['ID'] or data[0]['ID'], etc.. it doesn't print anything. What I'm doing wrong? Thanks!
If you need, the code to generate JSON is this (PHP):
$sql = "SELECT id, user, nom, cognom1, cognom2, tipus, progres FROM users WHERE user='".$_GET['user']."'";
$result = $db->query($sql);
$row = $result->fetch_array(MYSQLI_ASSOC);
$id = $row['id'];
$user = $row['user'];
$nom = $row['nom'];
$c1 = $row['cognom1'];
$c2 = $row['cognom2'];
$tipus = $row['tipus'];
$progres = $row['progres'];
//build the JSON array for return
$json = array(array('ID' => $id),
array('Usuari' => $user),
array('Nom' => $nom),
array('Cognom1' => $c1),
array('Cognom2' => $c2),
array('Tipus' => $tipus),
array('Progres' => $progres));
echo json_encode($json);
mysqli_close($db);
Thanks!
I found the solution to get the values correctly. The code is the following one:
$(document).ready(function(){
$("#botoBuscar").click(function(){
$.ajax({url: "http://XX.com/api/buscarUser.php?user="+ $("#userInput").val(), success: function(data){
var obj = $.parseJSON(data);
$("#id").val(obj[0]['ID']);
$("#user").val(obj[1]['Usuari']);
$("#nom").val(obj[2]['Nom']);
$("#cognom1").val(obj[3]['Cognom1']);
$("#cognom2").val(obj[4]['Cognom2']);
$("#tipus").val(obj[5]['Tipus']);
$("#progres").val(obj[6]['Progres']);
}});
});
});

PHP parse array posted from jQuery

I have this jQuery code that adds to an array inside an $each loop:
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
new_file_edits.push(JSON.stringify(new_edit));
jQuery new_file_edits array output
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
and im trying to post it to call.php like this:
$.ajax({
type: "POST",
url: "/call.php",
data: "edit_files="+ arrayVarHere,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
alert(+msg);
}
});
In the PHP file call.php i have this code:
if(isset($_POST['edit_files'])){
$edit_array = $_POST['edit_files'];
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
but i get this error and i cant figure out how to fix it, been googling it for a while now...
error:
Warning: Invalid argument supplied for foreach() in /home2/dddd/public_html/call.php on line 237
Line 237: foreach($edit_array as $key => $value){
Any help is much appreciated!
-Morten
EDIT 1:
I changed $edit_array = $_POST['edit_files']; to $edit_array = array($_POST['edit_files']);
And now it outputs:
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
How do i go from here with the foreach($edit_array as $key => $value){ part?
Edit 2:
i build my arrayVarHere like this:
$.each( $selected_files_array, function( index, value ){
//i get $file_id, $new_file_realname and $new_file_folder with some code here
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
arrayVarHere.push(JSON.stringify(new_edit));
});
change your code like this:
data: "edit_files="+ arrayVarHere,
call json data by json_decode in call.php
if(isset($_POST['edit_files'])){
$edit_array = json_decode($_POST['edit_files'],true); //return array
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
in your ajax alert should be
success: function(msg){
alert(msg); //remove plus sign ,this can output `NaN`
}
check edit_array is array print_r($edit_array);
check contentType is used form data then correct otherwise used json type
if form data then check data: edit_files[]: arrayVarHere,
It returns this array
Array ( [0] => [{"file_id":"1857","file_realname":"aq53pop_460sv[1].mp4","file_folder":"/"},{"file_id":"1859","file_realname":"aKqbD8Q_460sv[1].mp4","file_folder":"/"},{"file_id":"1856","file_realname":"aDopymK_700b[1].jpg","file_folder":"/"}] )
how can i loop the array and access file_id value etc?
The way you are passing Data to PHP may not be that ideal. Here is what might get you started:
PHP: call.php
<?php
$data0 = isset($_POST['data_0']) ? json_decode($_POST['data_0'], true) : null;
$data1 = isset($_POST['data_1']) ? json_decode($_POST['data_1'], true) : null;
$data2 = isset($_POST['data_2']) ? json_decode($_POST['data_2'], true) : null;
$arrData = array(
'data0' => $data0,
'data1' => $data1,
'data2' => $data2,
);
foreach($arrData as $dataKey=>$dataObject){
$tempFileID = $dataObject->file_id;
$tempFileName = $dataObject->file_realname;
$tempFileFolder = $dataObject->file_folder;
// DO SOMETHING WITH THESE DATA AND THEN BUILD UP A RESPONSE FOR AJAX + SEND IT...
// UNCOMMENT TO SEE THE DATA IN YOUR NETWORKS CONSOLE BUT
// IF YOU DO THIS (SINCE YOU EXPECT JSON RESPONSE) YOUR AJAX WILL RESPOND WITH AN ERROR...
// var_dump($dataObject);
}
// RESPOND WITH THE SAME DATA YOU RECEIVED FROM AJAX: JUST FOR TESTING PURPOSES...
die( json_encode($arrData));
?>
JAVASCRIPT: BUILDING THE DATA FOR PHP
<script type="text/javascript">
var dataForPHP = {};
var iCount = 0;
$.each( $selected_files_array, function( index, value ){
var keyName = "data_" + iCount;
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
dataForPHP[keyName] = new_edit;
iCount++;
});
</script>
JAVASCRIPT: AJAX REQUEST
<script type="text/javascript">
$.ajax({
type : "POST",
url : "/call.php",
datatype : "JSON",
data : dataForPHP,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
if(msg){
alert("Ajax Succeeded");
console.log(msg);
}
}
});
</script>

From PHP array to jQuery array sent via ajax

Now this is a pretty simple question, but due to my lack of jQuery knowledge I have to ask this..
In JS I have this variable, which is an array of marker data for Google Maps:
var Locations = {
1: {
info: '1. New Random info and new position',
lat: -37,
lng: 124.9634
},
2: {
info: '2. New Random info and new position',
lat: 70,
lng: 14.5144
},
3: {
info: '3. New Random info',
lat: 30,
lng: 24.5144
},
4: {
info: '4. New Random info',
lat: 34,
lng: 26.5144
},
5: {
info: '5. 55555. Added',
lat: -37,
lng: 0
}
};
I then have an ajax call to retrieve a new array of locations with PHP.
The PHP looks like this example (note that I echo 3 pieces of data delimited by | ):
$arrayccordinates = array();
$countercords = 0;
echo 'Data1 |';
echo 'Data2 |';
foreach ($results as $result) {
$countercords = $countercords + 1;
$arrayccordinates[] = array( $countercords => array( 'info' => $infos, 'lat' => $latdata, 'lng' => $lngdata )
);
}
echo json_encode($arrayccordinates);
Here is the ajax call. Here I split the 3 data pieces up and the locations array is found in arr[2].:
//Ajax code
var interval = 5000; // 5000 ms = 5 secs
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
dataType : 'html',
success: function (data) {
var arr = data.split('|');
jQuery('#counterint').html(arr[0]);
jQuery('#extrainfoscounter').html(arr[1]);
jQuery('#testdiv').html(arr[2]);
var newlocations = arr[2];
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
Now, I have tested this and it doesn´t seem to work. The array from PHP stored in "newlocations" variable does not seem to work as the original "Locations" variable.
I have really no clue what I´m doing wrong, though I suspect my use of json_encode is completely wack..
You're setting the datatype to html, but sending JSON. If you set datatype: json, then jquery will decode the json into a native JS array for you.
And besides, since you ARE outputting JSON from PHP, there almost certainly won't be ANY | characters in the string to split on.
As i mentioned in my comments: if you change dataType from html to json you can use the argument inside the success function like you would an array object in javascript.
Your "array" looks like this:
var Locations = {
1: {
info: '1. New Random info and new position',
lat: -37,
lng: 124.9634
},
2: {
info: '2. New Random info and new position',
lat: 70,
lng: 14.5144
},
3: {
info: '3. New Random info',
lat: 30,
...
which is not an array, but an object with properties 1, 2, 3 etc. pointing to an object
Your php json_encode will return:
[
{ "1": {
info: '1. New Random info and new position',
lat: -37,
lng: 124.9634
}},
{ "2": {
info: '1. New Random info and new position',
lat: -37,
lng: 124.9634
}},
...
which is a valid array of objects having a property "1", "2", etc pointing to a nested object - quite a difference.
Either change the layout of your initial object (and the code accessing) or don't use json_encode
Thanks to Axel Amthor I figured it all out.
I just needed to change 2 minor things.
Firstly I needed to change the PHP code to this:
$arrayccordinates = array();
$countercords = 0;
foreach ($results as $result) {
$countercords = $countercords + 1;
$arrayccordinates[$countercords] = array( 'info' => $result->info, 'lat' => $result->lat, 'lng' => $result->lng);
}
echo json_encode($arrayccordinates);
Then I needed to modify my Ajax call slightly into this:
//Ajax code
var interval = 5000; // 1000 = 1 second, 3000 = 3 seconds
function doAjax() {
jQuery.ajax({
type: 'POST',
url: '/codes/LiveVisitsStats/postlivecounter.php',
dataType: "json",
success: function (data) {
var NewLocation = data;
},
complete: function (data) {
// Schedule the next
setTimeout(doAjax, interval);
}
});
}
setTimeout(doAjax, interval);
Of course I then need to make seperate ajax calls for other kind of ajax updates..

Display object in javascript

I write a script to make an ajax call here is my code
function ajax_post(obj) {
obj = '#'+ obj;
var formData = $(obj).serializeArray();
$.ajax({
url: '__core/info.php',
type:'get',
dataType: 'json',
data: formData,
success: function(resp){
alert(resp);
}
})
}
and here is my info.php
$last_Res = theme::get_last_themes_desk(); //$last_Res is an array
echo(json_encode($last_Res));
but when alert it shows return object object ..... what should i do if datatype is json should i convert it to another format ? $last_Res is an array
In response to your comment (showing the response data, which is an array, containing a single object):
//resp = [{"id":"2","name":"babak_theme","sh_describ":"support css3 and ie 9 ","rate":"3","time":"2"}];
resp = resp[0];
alert('id => ' + resp.id + ', Name => ' + resp.name);//etc...
Will serve you just fine...
$last_Res is an associative array, most likely. JS doesn't have assoc arrays, but converts these to objects/ object literals:
//php:
$foo = array('foo' => 'bar');
//in JS:
var foo = {foo: 'bar'};
alert(foo);//alerts [object Object]
console.log(foo);//shows you what properties/prototypes/methods the object has
That's all there is too it. To access the data:
for (var prop in resp)
{//for "assoc arrays"
if (resp.hasOwnProperty(prop))
{
alert(prop + ' => '+resp[prop]);
}
}
for (var i=0;i<resp.length;i++)
{//for regular arrays
alert(i + ' => ' + resp[i])'
}
In your info.php, you should set the Content-Type header to application/json to indicate what you are returning:
header('Content-Type: application/json');
you haven't posted the json format. usually you can access resp. values like this:
if the json format is:
data['index']['subindex1'] = 'value1'
data['index']['subindex2'] = 'value2'
you can
alert(resp.index.subindex1);

Categories