I'm trying to retrieve data in a javascript file from a php file using json.
$items = array();
while($r = mysql_fetch_array($result)) {
$rows = array(
"id_locale" => $r['id_locale'],
"latitudine" => $r['lat'],
"longitudine" => $r['lng']
);
array_push($items, array("item" => $rows));
}
ECHO json_encode($items);
and in the javascript file I try to recover the data using an ajax call:
$.ajax({
type:"POST",
url:"Locali.php",
success:function(data){
alert("1");
//var obj = jQuery.parseJSON(idata);
var json = JSON.parse(data);
alert("2");
for (var i=0; i<json.length; i++) {
point = new google.maps.LatLng(json[i].item.latitudine,json[i].item.longitudine);
alert(point);
}
}
})
The first alert is printed, the latter does not, it gives me error: Unexpected token <.... but I do not understand what it is.
Anyone have any idea where am I wrong?
I also tried to recover the data with jquery but with no positive results.
This should do it.
$.post("Locali.php",{
// any parameters you want to pass
},function(d){
alert("1");
for (var i=0; i<d.length; i++) {
point = new google.maps.LatLng(d[i].item.latitudine,d[i].item.longitudine);
alert(point);
}
}, 'json');
the PHP is fine if it is giving the response you mentioned above.
I think u should look more for the data you are getting from the php file. Definitely this is a parse error and must be missing some bracket/something else, ultimately not making the data returned to be a json parseable string.
You should be Ok with this slight modifications:
$items = array();
while($r = mysql_fetch_array($result)) {
$items[] = array(
"id_locale" => $r['id_locale'],
"latitudine" => $r['lat'],
"longitudine" => $r['lng']
);
}
echo json_encode($items);
And the jQuery:
$.ajax({
type:"POST",
dataType: 'json',
url:"Locali.php",
success:function(data){
console.log(data);
for (var i=0; i<data.length; i++) {
point = new google.maps.LatLng(data[i].item.latitudine,data[i].item.longitudine);
alert(point);
}
}
})
data $.ajax({
type:"POST",
dataType: json,
url:"Locali.php",
success:function(data){
for (i in data) {
point = new google.maps.LatLng(json[i].item.latitudine,json[i].item.longitudine);
alert(point);
}
}
})
Try it like that.
yeah just try
for (var i=0; i<json[0].length; i++) {
cause you have an object there..
Related
I have this code:
var temp = 'tag1,tag2'.split(','),
tags = [];
if (temp.length > 0) {
for (i = 0; i < temp.length; ++i) {
tags.push(temp[i]);
}
}
Now I want to send this array as an Ajax request:
var data = {
action: 'my_wp_ajax',
ajax_req: JSON.stringify(tags)
};
$.post(
ajaxurl,
data,
function (data) {
console.log('this is data: '+data);
}
);
On the other side I have these codes:
echo $_POST['ajax_req'];
$temp = json_decode($_POST['ajax_req']);
$error = json_last_error();
echo $error;
The result I see in browser console is:
this is data: "[\\\"tag1\\\",\\\"tag2\\\"]4"
As you can see in above result, last json error is 4 which means invalid json syntax. I don't know what is wrong in above codes. If I try
foreach (json_decode($_POST['ajax_req']) as $hi)
echo $hi;
In console it only shows me
this is data: ""
What am I doing wrong?
Edit:
I tried var_dump(get_magic_quotes_gpc(), $_POST); and the result in console:
"bool(false)\narray(2) {\n [\"action\"]=>\n string(8) \"my_wp_ajax\"\n [\"ajax_req\"]=>\n string(19) \"[\\\"tag1\\\",\\\"tag2\\\"]\"\n}\n0"
No need to double stringify array, data passed to array is going to be properly handled by jQuery:
var tags = 'tag1,tag2'.split(',');
var data = {
action: 'my_wp_ajax',
ajax_req: tags
};
I'm trying to retrieve data from table using PHP and AJAX, at the moment I'm able to display the result of my query in json format, what I want to do is select an specific data from that array, for example I get this array:
{data: [{IdProduct: "1", Name: "Name here..........",…}]}
For example I want to select only Name, I tried doing this:
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
success: function (data) {
var aRC = JSON.parse(data);
for (var i = 0; i < aRC.length; i++) {
console.log(aRC[i].Name);
}
}
});
}
But this doesn't shows anything, how can I do this? This is my PHP code:
while($row = mysqli_fetch_array($registros)) {
$table.='{
"IdProduct":"'.$row['IdProduct'].'",
"Name":"'.$row['Name'].'",
"Description":"'.$row['Description'].'",
"ImagePath":"'.$row['ImagePath'].'"
},';
$table = substr($table, 0, strlen($table) -1);
echo '{"data":['.$table.']}';
}
There are couple of things you need to change in your code, such as:
That's not how you should create a json string. Create an empty array before the while() loop and append the row details to this array in each iteration of the loop. And after coming out of the loop, simply apply json_encode() function to the resultant array to get the final json string.
$table = array();
while($row = mysqli_fetch_array($registros)) {
$table[]= array(
'IdProduct' => $row['IdProduct'],
'Name' => $row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
);
}
echo json_encode($table);
Since you're expecting a json string from server, add this setting dataType:'json' to your AJAX request. dataType is the type of data you're expecting back from the server. And in the success() callback function, simply loop through the json result to get the relevant data.
function LoadProductos() {
$.ajax({
url: '../../class/loadProd.php',
method: 'POST',
dataType: 'json',
success: function (data) {
for (var i = 0; i < data.length; i++) {
alert(data[i].Name);
}
}
});
}
First off, your shouldn't echo the json data in the loop. It should be outside the loop.
You shouldn't build your own json data either.
Let's build an array that looks like the json response you want. Then we'll use the function json_encode() to encode it as a proper json-string:
// Define the response array
$response = [
'data' => []
];
while($row = mysqli_fetch_array($registros)) {
// Push a new array to 'data' array
$response['data'][] = [
'IdProduct' => $row['IdProduct'],
'Name' =>.$row['Name'],
'Description' => $row['Description'],
'ImagePath' => $row['ImagePath']
];
}
// Now, let's encode the data:
echo json_encode($response);
In you PHP file make changes according to this:-
$outp = array();
$outp = $res->fetch_all(MYSQLI_ASSOC);
For make sure that json_encode don't return null
function utf8ize($d) {
if (is_array($d)) {
foreach ($d as $k => $v) {
$d[$k] = utf8ize($v);
}
} else if (is_string ($d)) {
return utf8_encode($d);
}
return $d;
}
echo json_encode(utf8ize($outp));
You JavaScript is okay You just need to change code in PHP.
I used AJAX to send back an array with many variables worth of data to my page to have displayed. The array looks something like this right now:
{"dateName":"05/18/2016","hour1":null,"hour2":null,"hour3":null,"hour4":null,"hour5":null,"hour6":null,"hour7":null,"hour8":null,"hour9":null,"hour10":null,"hour11":null,"hour12":null,"hour13":null,"hour14":null,"hour15":null,"hour16":null,"hour17":null,"hour18":null,"hour19":null,"hour20":null,"hour21":null,"hour22":null,"hour23":null,"hour24":null}
Now I am displaying the parts of the array in my data boxes using
//AJAX Data
success: function(data) {
var array = data.split(",");
$("#date").html(array[0]);
i = 0;
while (i < 25) {
$("#hour"+i).html(array[i]);
i++;
}
This displays data that looks like this on my webpage
"hour1":"sleep"
As you can see, the variable name in quotes and the variable value that was passed through ajax. But I only want
sleep
displayed (no quotes, no variable) . How do I get the variable name and quotes out of my displayed data?
Thank you so much!
use this
$.ajax({url: "demo_test.txt", success: function(result){
// $("#div1").html(result);
var parsed = JSON.parse(result);
alert(parsed["hour1"]);
}});
//AJAX Data
success: function(data) {
var hour = "hour";
for(var i=0; i<data.length; i++) {
hour += i;
console.log(data.hour)
}
Through the help of a few of you awesome members here at stackexchange I have finally figured out how to send an ajax, call back multiple variables, and arrange them cleanly on my page. Attached is my code, I hope that this can help future users.
//SEND MULTIPLE DATA THROUGH AJAX
<script>
function ajax() {
$.ajax({
type: "POST",
url: "changeDate.php",
data: {
amount: changeDate,
loginName: "benjamin_lawson"
},
success: function(result) {
//make array out of data
var array = JSON.parse(result);
$("#date").html(array[0]);
i = 0;
while (i < 25) {
//call array information for parts
$("#hour"+i).html(array[i]);
i++;
}
}
});
}
</script>
<?php
//create the array
$response_arr = array();
//add your variables to the array
$response_arr[] = date("m/d/Y", strtotime("+" . $amount . " day"));
$response_arr[] = $row[$dateName];
//echo the final array to be sent to your ajax
echo json_encode($response_arr);
?>
success: function(data) {
var json_obj =JSON.parse(data)
$("#date").html(json_obj['datename']);
i = 0;
while (i < 25) {
$("#hour"+i).html(json_obj['hour'+i]);
i++;
}
}
You can use JSON.parse to convert the string to json obj :
json_obj=JSON.parse(data)
$("#date").html(json_obj['']);
I am trying to send data from form to PHP file using JavaScript. PHP file pushes this data to database. For now, almost all works well but I have a problem with array from getElementsByClassName. After sending to database I can see only "Array" but no values of this array.
Here's a JS:
function przekaz_form($wejscie) {
var datas = document.formularz.datas.value;
var klient = document.formularz.firma.value;
var comment = document.formularz.comment.value;
var collect = document.getElementsByClassName($wejscie);
var datan = document.formularz.datan.value;
var items = new Array();
for(var i = 0; i < collect.length; i++) {
items.push(collect.item(i).value);
}
jQuery.ajax({
url: 'addtobase.php',
type: 'post',
data:{
devices: items,
datas: datas,
klient: klient,
comment: comment,
datan: datan
},
success: function(output) {
alert('Success');
}
});
}
One way to do this is:
$inputData = json_decode(file_get_contents('php://input'));
Once you have the $inputData variable you can access the data in the JSON by:
$devices = (!is_null($inputData) && property_exists($inputData, "devices")) ? strip_tags($inputData->{"devices"}) : 0;
You should also try to better format the JSON : http://json.org/example
I have PHP associative array and I use JQuery AJAX to get the result array but my problem is when that result is pass to jquery and use looping to extract each Sequence,Percent and Date then that extracted data will store to new Jquery Array for data manipulation purposes. Please see my sample code so far.
sample code PHP ARRAY:
$Sequence=array(
array("Seq1","20%"),
array("Seq2","40%"),
array("Seq3","60%"),
array("Seq4","80%"),
array("Seq5","100%")
);
****For loop here****
$ResultArray[$arrayIndex]=array(
'Sequence' => $Sequence[$arrayIndex][0],
'Percent' => $Sequence[$arrayIndex][1],
'Date' => $row['exactDate']
);
echo json_encode($ResultArray); // then pass result array to jquery
JQUERY :
$(document).ready(function(){
var ListOfSequence = []
var ListOfPercentage = [];
var ListOfDates = [];
$("#button").click(function(){
var _WOID = $('#txtWOID').val();
$.ajax({
url:'getStatus.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
//here is where the problem begin
for (var key in output) {
if (output.hasOwnProperty(key)) {
//here where extracted data will store to designated array
ListOfSequence.push(key);//<---store extracted Sequence
ListOfPercentage.push(key);//<---store percentage
ListOfDates.push(output[key]);//<---store dates
}
}
ListOfPercentage.reverse();
console.log(ListOfPercentage);
console.log(ListOfDates);
console.log(ListofSequence);
}
});
});
});
and here's the console.log:
Thank you in advance
Since you are already using jQuery you could use $.each() :
$(document).ready(function(){
var ListOfSequence = []
var ListOfPercentage = [];
var ListOfDates = [];
$("#button").click(function(){
var _WOID = $('#txtWOID').val();
$.ajax({
url:'getStatus.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(json){
$.each(json, function(index, object){
ListOfSequence.push(object.Sequence);
ListOfPercentage.push(object.Percent);
ListOfDates.push(object.Date);
});
}
});
});
});
You should set the json response header before sending the content to the browser like so:
header('Content-type: application/json');
die(json_encode($ResultArray);)