I hope anyone can help me. My JSON isn't indexed (i.e. there isn't any key above any element)
[
{
"nome":"LABORGHINI GALLARDO",
"descrizione":"LAMBORGHINI GALLARDO ED. NERA- ANNO 2007- ",
"indirizzo_pubblicato":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/LABORGHINI GALLARDO31072013-023853.json",
"indirizzo_immagine_copertina":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/IMG_1414 (600x448).jpg",
"indirizzo_paginaauto":"autocaricateeea\/LABORGHINI GALLARDO31072013-023853\/index.html"
},
{
"nome":"RENAULT MEGANE",
"descrizione":"RENAULT MEGANE -ANNO 2006-DIESEL-CC. 1461",
"indirizzo_pubblicato":"autocaricateeea\/RENAULT MEGANE31072013-024103\/RENAULT MEGANE31072013-024103.json",
"indirizzo_immagine_copertina":"autocaricateeea\/RENAULT MEGANE31072013-024103\/P1080949 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/RENAULT MEGANE31072013-024103\/index.html"
},
{
"nome":"FORD MONDEO",
"descrizione":"FORD MONDEO SINISTRATA- ANNO 2009- DIESEL- CC. 1997-",
"indirizzo_pubblicato":"autocaricateeea\/FORD MONDEO31072013-045216\/FORD MONDEO31072013-045216.json",
"indirizzo_immagine_copertina":"autocaricateeea\/FORD MONDEO31072013-045216\/P1080971 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/FORD MONDEO31072013-045216\/index.html"
}
]
but after running unset() to remove an element with PHP the output JSON appears like this:
{
"1": // <--- **** add a key before an element
{
"nome":"Fiat Punto ",
"descrizione":"Fiat Punto Bianca",
"indirizzo_pubblicato":"autocaricateeea\/Fiat Punto 14072013-042703\/Fiat Punto 14072013-042703.json",
"indirizzo_immagine_copertina":"autocaricateeea\/Fiat Punto 14072013-042703\/P1080713 (600x450).jpg",
"indirizzo_paginaauto":"autocaricateeea\/Fiat Punto 14072013-042703\/index.html"
},
...........
...........
...........
How you can see there is a key before the element of JSON.
I know that this behavior is caused by unset (PHP json_encode as object after PHP array unset()).
There is a way to prevent this behavior?
had the same issue until i found this solution:
In addition to the array_values technique it is possible to use array_splice and remove an element and re-index in one step:
unset($a[1]);
Instead:
array_splice($a, 1, 1);
quoted from here: https://stackoverflow.com/a/3869219/4809658
The best way to do that is,
$json_arr = array_values($json_arr);
Although you have solved your issue at client side, I thought it would be helpful to show my solution to this issue using PHP, the idea is to construct a new array and exclude items that are not wanted, this way you will not have the indexing issue caused by unset, something like this:
$new_nodes= array();
for ($j = 0; $j < count($composition->nodes); $j++)
{
//exclude some nodes
if ($id!= $composition->nodes[$j]->id)
{
// store only the nodes that you want:
array_push($new_nodes, $composition->nodes[$j]);
}
}
// and finally, use the new modified nodes array:
$composition->nodes= $new_nodes;
Why do you need to prevent this behavior? When you convert the json to a PHP array, regardless of the JSON format is going to be an index array (have the numbers you shown) regardless.
If the numbering is incorrect use http://php.net/manual/en/function.array-values.php to fix.
Regenerated your json with this PHP script
<?php
$arr = array
(array('nome' => 'LABORGHINI GALLARDO',
'descrizione' => 'LAMBORGHINI GALLARDO ED. NERA- ANNO 2007-',
'indirizzo_pubblicato' => 'autocaricateeea/LABORGHINI GALLARDO31072013-023853/LABORGHINI GALLARDO31072013-023853.json',
'indirizzo_immagine_copertina' => 'autocaricateeea/LABORGHINI GALLARDO31072013-023853/IMG_1414 (600x448).jpg',
'indirizzo_paginaauto' => 'autocaricateeea/LABORGHINI GALLARDO31072013-023853/index.html'),
array('nome' => 'RENAULT MEGANE',
'descrizione' => 'RENAULT MEGANE -ANNO 2006-DIESEL-CC. 1461',
'indirizzo_pubblicato' => 'autocaricateeea/RENAULT MEGANE31072013-024103/RENAULT MEGANE31072013-024103.json',
'indirizzo_immagine_copertina' => 'autocaricateeea/RENAULT MEGANE31072013-024103/P1080949 (600x450).jpg',
'indirizzo_paginaauto' => 'autocaricateeea/RENAULT MEGANE31072013-024103/index.html'),
array('nome' => 'FORD MONDEO',
'descrizione' => 'FORD MONDEO SINISTRATA- ANNO 2009- DIESEL- CC. 1997-',
'indirizzo_pubblicato' => 'autocaricateeea/FORD MONDEO31072013-045216/FORD MONDEO31072013-045216.json',
'indirizzo_immagine_copertina' => 'autocaricateeea/FORD MONDEO31072013-045216/P1080971 (600x450).jpg',
'indirizzo_paginaauto' => 'autocaricateeea/FORD MONDEO31072013-045216/index.html')
);
$arr_json = json_encode($arr);
var_dump($arr_json);
?>
Preferably the JSON may be parsed with JS so that the required car is accessed. There is no need to modify the JSON with PHP.
I searched and tried anyway to implement the behaviour that i searched in my question but i didn't find nothing. I supposed that, like you can see in this answer, unset function adds indices to the array because the JSON_encode not support arrays with hole. So, to solve my problem, i load the JSON file with a jQuery function, delete the elements with jQuery and i call a ajax function to delete the files linked at the address contained in the json file:
$.getJSON('loadauto.json', function(result) {
var y = result;
$.each(result, function(i, field){
if(field.indirizzo_paginaauto == x){
delete result[i];
}
});
$.ajax({
async: true,
cache: false,
type: 'POST',
url: 'deleteauto.php',
data: { nuovofilejson: y, indirizzo: x},
success: function(data) {
alert ("Auto cancellata definitivamente");
},
error: function(data) {
alert ("Error");
}
});
}
Related
I'm struggling to retrieve and display results from PHP json_encode via JQuery. Any help appreciated. Here's my code php side:
$return_it = array();
$query= mysql_query("SELECT * FROM $tableName");
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$row_array[] = $row;
array_push($return_it,$row_array);
}
echo json_encode($return_it);
and on success I have this.
dataType: 'json',
success: function(data)
{
$.each(data, function() {
var name = data.name;
var values = data.values;
$('#output').append("<tr style=\"background-color:#ccc\"><td>id: </td><td> name: </td></tr><tr><td>"+name+"</td><td>"+values+"</td></tr>");
});
}
this is looping but returning undefined, I know I'm probably missing something obvious :-/
Your array nesting in php is unnecessary and doesn't match the way you are trying to parse the results. Just use the return_it array for each row
$return_it = array();
$query= mysql_query("SELECT * FROM $tableName");
while ($row = mysql_fetch_array($query, MYSQL_ASSOC)) {
$return_it[] = $row;
//array_push($return_it,$row_array); /* remove */
}
echo json_encode($return_it);
The result in javascript currently would look like
[
[ {name:'foo',values:'123'} ],
[ {name:'foo2',values:'345'} ]
]
Without the extra nesting:
[
{name:'foo',values:'123'},
{name:'foo2',values:'345'}
]
This will not change the $.each parsing, rather you would need to look inside each sub array if maintain current structure.
You are however misisng critical arguments for $.each callback
$.each(data, function() {index, row){
var name = row.name;
});
I think it should be:
dataType: 'json',
success: function(data)
{
$.each(data, function(d) {
var name = d[0].name;
var values = d[0].values;
$('#output').append("<tr style=\"background-color:#ccc\"><td>id: </td><td> name: </td></tr><tr><td>"+name+"</td><td>"+values+"</td></tr>");
});
}
The each method applies a method to each element that is passed to the method. As it happens, you are not passing anything to function(), so you should add the parameter (in my example it is d) and manipulate d, rather than data.
As apparently you are nesting the json array (returing an array of single arrays) the d[0] part would return the attributes of the first element of your nested array, which, in your case would be your {name:"...",values:"..."}.
However, if you remove your nested JSON array as mentioned in another answer, then you don't need to add the d[0].name, and use only d.name as now each line of your JSON array is the collection of attributes, rather than an array of size 1, which would have the attributes.
Essentially you are encapsoulating your results. You should either remove the encapsoulation, or adjust the data parsing from JSON.
Hope this helps.
I have this PHP array storing code(the data of array is came from database query) then the array will be pass to JQuery. My problem is I'm getting Undefined value when I retrieve the data from php Array. I use $.Each loop in JQuery. My question is, how to iterate loop of php associative array using JQuery?
Here's my code so far:
CONSOLE.LOG/NETWORK IMAGE
PHP Array storing
**** loop here*****
$ListOfWorkOrderDates[$rowInnerJoin['WorkOrder']][$rowInnerJoin['DateField']] =
array('DatePosted' => $rowInnerJoin['DatePosted']);
echo json_encode($ListOfWorkOrderDates);
Jquery Loop
/// Here where I get confuse. How can I retrieve those data from php using jquery loop
$.ajax({
url:'getWorkOrders.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
console.log(output);
$.each(output, function(index, object){
counter++;
ListOfPercentage.push(object.DateField);
ListOfDates.push(object.DatePosted);
});
}
});
$ListOfWorkOrderDates[$rowInnerJoin['WorkOrder']][$rowInnerJoin['DateField']] =
array('DatePosted' => $rowInnerJoin['DatePosted']);
Did you check your exact json response using firebug or chrome dev tools.
I believe object.WorkOrder might return undefined, because your json does'nt seem to have a WorkOrder key?
for the js to work, your json response should be something like
[
{
"WorkOrder": "w1",
"DateField": "D1",
"DatePosted": "DP1"
},
{
"WorkOrder": "w2",
"DateField": "D3",
"DatePosted": "DP2"
}
]
a quick code i used to generate the above response
$response=array();
$response[0]=array("WorkOrder"=>"w1","DateField"=>"D1","DatePosted"=>"DP1");
echo json_encode($response);
I've been experiencing a lot of trouble with my issue all afternoon. Endless searches on Google and SO haven't helped me unfortunately.
The issue
I need to send an array to a PHP script using jQuery AJAX every 30 seconds. After constructing the array and sending it to the PHP file I seemingly get stuck. I can't seem to properly decode the array, it gives me null when I look at my console.
The scripts
This is what I have so far. I am running jQuery 1.11.1 and PHP version 5.3.28 by the way.
The jQuery/Ajax part
$(document).ready(function(){
$.ajaxSetup({cache: false});
var interval = 30000;
// var ids = ['1','2','3'];
var ids = []; // This creates an array like this: ['1','2','3']
$(".player").each(function() {
ids.push(this.id);
});
setInterval(function() {
$.ajax({
type: "POST",
url: "includes/fetchstatus.php",
data: {"players" : ids},
dataType: "json",
success: function(data) {
console.log(data);
}
});
}, interval);
});
The PHP part (fetchstatus.php)
if (isset($_POST["players"])) {
$data = json_decode($_POST["players"], true);
header('Content-Type: application/json');
echo json_encode($data);
}
What I'd like
After decoding the JSON array I'd like to foreach loop it in order to get specific information from the rows in the database belonging to a certain id. In my case the rows 1, 2 and 3.
But I don't know if the decoded array is actually ready for looping. My experience with the console is minimal and I have no idea how to check if it's okay.
All the information belonging to the rows with those id's are then bundled into a new array, json encoded and then sent back in a success callback. Elements in the DOM are then altered using the information sent in this array.
Could someone tell me what exactly I am doing wrong/missing?
Perhaps the answer is easier than I think but I can't seem to find out myself.
Best regards,
Peter
The jQuery.ajax option dataType is just for the servers answer. What type of anser are you expexting from 'fetchstatus.php'. And it's right, it's json. But what you send to this file via post method is not json.
You don't have to json_decode the $_POST data. Try outputting the POST data with var_dump($_POST).
And what happens if 'players' is not given as parameter? Then no JSON is returning. Change your 'fetchstatus.php' like this:
$returningData = array(); // or 'false'
$data = #$_POST['players']; // # supresses PHP notices if key 'players' is not defined
if (!empty($data) && is_array($data))
{
var_dump($data); // dump the whole 'players' array
foreach($data as $key => $value)
{
var_dump($value); // dump only one player id per iteration
// do something with your database
}
$returningData = $data;
}
header('Content-Type: application/json');
echo json_encode($returningData);
Using JSON:
You can simply use your returning JSON data in jQuery, e.g. like this:
// replace ["1", "2", "3"] with the 'data' variable
jQuery.each(["1", "2", "3"], function( index, value ) {
console.log( index + ": " + value );
});
And if you fill your $data variable on PHP side, use your player id as array key and an array with additional data as value e.g. this following structure:
$data = array(
1 => array(
// data from DB for player with ID 1
),
2 => array(
// data from DB for player with ID 2
),
...
);
// [...]
echo json_decode($data);
What I suspect is that the data posted is not in the proper JSON format. You need to use JSON.stringify() to encode an array in javascript. Here is an example of building JSON.
In JS you can use console.log('something'); to see the output in browser console window. To see posted data in php you can do echo '<pre>'; print_r($someArrayOrObjectOrAnything); die();.
print_r prints human-readable information about a variable
So in your case use echo '<pre>'; print_r($_POST); to see if something is actually posted or not.
I am trying to parse some very basic JSON, but I don't know where I'm going wrong when trying to display it to the screen.
Am I not GRABBING the data correctly, such as, "data.re1Code"?
I hope someone can shed some light onto my basic question sorry.
JSON Data
[
{
"rep1FullName": "Justin Giesbrecht",
"rep1Code": "dc",
}
]
Javascript
$.ajax({
type: "GET",
url: "testJSONData.php",
dataType: "json",
success: function(data) {
$("#output").append(data.rep1FullName);
},
error: function () { alert("Error"); }
}); // End of generated json
The brackets [] make data a JSON array with your object as the 0th element so to get "Justin Giesbrecht" use the code: $("#output").append(data[0].rep1FullName); or remove the brackets and make the JSON:
{
"rep1FullName": "Justin Giesbrecht",
"rep1Code": "dc",
}
Your data is an array.
So you'd want
$("#output").append(data[0].rep1FullName);
You are returning a jSon array so you would need to access it via data[0].rep1FullName or return the jSon as below and then use data.rep1FullName
{
"rep1FullName":"Justin Giesbrecht",
"rep1Code":"dc"
}
Also, remove the last comma from the object notation.
[
{
"rep1FullName": "Justin Giesbrecht",
"rep1Code": "dc" // <-- No comma, breaks in IE if you have a comma.
}
]
Some of the other posters did this, but didn't mention it.
I am trying this new method I've seen serializeArray().
//with ajax
var data = $("#form :input").serializeArray();
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
So I get these key value pairs, but how do I access them with PHP?
I thought I needed to do this, but it won't work:
// in PHP script
$data = json_decode($_POST['data'], true);
var_dump($data);// will return NULL?
Thanks, Richard
Like Gumbo suggested, you are likely not processing the return value of json_decode.
Try
$data = json_decode($_POST['data'], true);
var_dump($data);
If $data does not contain the expected data, then var_dump($_POST); to see what the Ajax call did post to your script. Might be you are trying to access the JSON from the wrong key.
EDIT
Actually, you should make sure that you are really sending JSON in the first place :)
The jQuery docs for serialize state The .serializeArray() method creates a JavaScript array of objects, ready to be encoded as a JSON string. Ready to be encoded is not JSON. Apparently, there is no Object2JSON function in jQuery so either use https://github.com/douglascrockford/JSON-js/blob/master/json2.js as a 3rd party lib or use http://api.jquery.com/serialize/ instead.
The OP could have actually still used serializeArray() instead of just serialize() by making the following changes:
//JS
var data = $("#form :input").serializeArray();
data = JSON.stringify(data);
post_var = {'action': 'process', 'data': data };
$.ajax({.....etc
// PHP
$data = json_decode(stripslashes($_POST['data']),true);
print_r($data); // this will print out the post data as an associative array
its possible by using the serialize array and json_decode()
// js
var dats = JSON.stringify($(this).serializeArray());
data: { values : dats } // ajax call
//PHP
$value = (json_decode(stripslashes($_REQUEST['values']), true));
the values are received as an array
each value can be retrieved using $value[0]['value'] each html component name is given as $value[0]['name']
print_r($value) //gives the following result
Array ( [0] => Array ( [name] => name [value] => Test ) [1] => Array ( [name] => exhibitor_id [value] => 36 ) [2] => Array ( [name] => email [value] => test#gmail.com ) [3] => Array ( [name] => phone [value] => 048028 ) [4] => Array ( [name] => titles [value] => Enquiry ) [5] => Array ( [name] => text [value] => test ) )
The JSON structure returned is not a string. You must use a plugin or third-party library to "stringify" it. See this for more info:
http://www.tutorialspoint.com/jquery/ajax-serializearray.htm
I have a very similar situation to this and I believe that Ty W has the correct answer. I'll include an example of my code, just in case there are enough differences to change the result, but it seems as though you can just use the posted values as you normally would in php.
// Javascript
$('#form-name').submit(function(evt){
var data = $(this).serializeArray();
$.ajax({ ...etc...
// PHP
echo $_POST['fieldName'];
This is a really simplified example, but I think the key point is that you don't want to use the json_decode() method as it probably produces unwanted output.
the javascript doesn't change the way that the values get posted does it? Shouldn't you be able to access the values via PHP as usual through $_POST['name_of_input_goes_here']
edit: you could always dump the contents of $_POST to see what you're receiving from the javascript form submission using print_r($_POST). That would give you some idea about what you'd need to do in PHP to access the data you need.
Maybe it will help those who are looking :)
You send data like this:
$.ajax({
url: 'url_name',
data: {
form_data: $('#form').serialize(),
},
dataType: 'json',
method: 'POST'
})
console.log($('#form').serialize()) //'f_ctrType=5&f_status=2&f_createdAt=2022/02/24&f_participants=1700'
Then on the server side use parse_str( $_POST['form_data'], $res).
Then the variable $res will contain the following:
Array
(
[f_ctrType] => 5
[f_status] => 2
[f_createdAt] => '2022/02/24'
[f_participants] => 1700
)
You can use this function in php to reverse serializeArray().
<?php
function serializeToArray($data){
foreach ($data as $d) {
if( substr($d["name"], -1) == "]" ){
$d["name"] = explode("[", str_replace("]", "", $d["name"]));
switch (sizeof($d["name"])) {
case 2:
$a[$d["name"][0]][$d["name"][1]] = $d["value"];
break;
case 3:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]] = $d["value"];
break;
case 4:
$a[$d["name"][0]][$d["name"][1]][$d["name"][2]][$d["name"][3]] = $d["value"];
break;
}
}else{
$a[$d["name"]] = $d["value"];
} // if
} // foreach
return $a;
}
?>