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;
}
?>
Related
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 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");
}
});
}
A JSON array has the form:
[[a,b,c],[a,b,c],[a,b,c]]
Is there a better way than split?
No, this is most certainly not the best way to parse JSON. JSON parsers exist for a reason. Use them.
In JavaScript, use JSON.parse:
var input = '[[1,2,3],[1,2,3],[1,2,3]]';
var arrayOfArrays = JSON.parse(input);
In PHP, use json_decode:
$input = '[[1,2,3],[1,2,3],[1,2,3]]';
$arrayOfArrays = json_decode($input);
You do not need to use regular expressions. As has been mentioned, you must first have valid JSON to parse. Then it is a matter of using the tools already available to you.
So, given the valid JSON string [[1,2],[3,4]], we can write the following PHP:
$json = "[[1,2],[3,4]]";
$ar = json_decode($json);
print_r($ar);
Which results in:
Array
(
[0] => Array
(
[0] => 1
[1] => 2
)
[1] => Array
(
[0] => 3
[1] => 4
)
)
If you want to decode it in JavaScript, you have a couple options. First, if your environment is new enough (e.g. this list), then you can use the native JSON.parse function. If not, then you should use a library like json2.js to parse the JSON.
Assuming JSON.parse is available to you:
var inputJSON = "[[1,2],[3,4]]",
parsedJSON = JSON.parse(inputJSON);
alert(parsedJSON[0][0]); // 1
In JavaScript , I think you can use Eval() → eval() method...
I am using $.getJSON() to pass some data to the server side (PHP, Codeigniter) and using the return data to do some work. The data that I am sending over to the server is in the form of an array.
Problem: When an associative array is sent to the server, no result is received on server side. However, if a normal array with numerical indexes is sent, the data is received on server side. How can I send an array of data over to the server?
JS Code (Not Working)
boundary_encoded[0]['testA'] = 'test';
boundary_encoded[0]['testB'] = 'test1';
$.getJSON('./boundary_encoded_insert_into_db_ajax.php',
{boundary_encoded: boundary_encoded},
function(json) {
console.log(json);
});
JS Code (Works)
boundary_encoded[0][0] = 'test0';
boundary_encoded[0][1] = 'test1';
$.getJSON('./boundary_encoded_insert_into_db_ajax.php',
{boundary_encoded: boundary_encoded},
function(json) {
console.log(json);
});
PHP Code
$boundary_encoded = $_GET['boundary_encoded'];
print_r($_GET);
Error Msg
<b>Notice</b>: Undefined index: boundary_encoded in <b>C:\xampp\htdocs\test\boundary\boundary_encoded_insert_into_db_ajax.php</b> on line <b>11</b><br />
Array
(
)
Working Result
Array
(
[boundary_encoded] => Array
(
[0] => Array
(
[0] => test
[1] => test1
)
)
)
The reason this isn't working is because JavaScript does not support associative arrays. This assignment:
boundary_encoded[0]['testA'] = 'test';
appears to work in JS because you can assign a new property to any object, arrays included. However they won't be enumerated in a for loop.
Instead, you must use an object literal:
boundary_encoded[0] = {'testA':'test'};
You can then use JSON.stringify to convert boundary_encoded to a JSON string, send that to the server, and use PHP's json_decode() function to convert the string back into an array of objects.
I would suggest using converting the arrays to JSON. If you can't do so in PHP (using the json_encode function), here are a couple of JS equivalents:
http://phpjs.org/functions/json_encode:457
http://www.openjs.com/scripts/data/json_encode.php
In your getJSON call, use
{boundary_encoded: JSON.stringify(boundary_encoded)},
instead of
{boundary_encoded: boundary_encoded},
[registration] => Array
(
[first_name] => test
[location] => Array
(
[name] => Santa Ana
[id] => 1.08081209215E+14
)
[gender] => female
[password] => 123654789
)
and i need to insert that data into a database by using:
$carray = fns_create_talent($login, $pass, $gender, $name);
any idea on how to get them from a place to another?
i was thinking that i need to assign the array values to the post vars. maybe:
$login = registration.first_name...
any ideas?
thanks
$login = $json['registration']['first_name']
What you have shown is not JSON, but PHP's array. I am assuming this is the structure of the data you want to be sent to the server.
You can do it like that (remember, there are no associative arrays in JavaScript!):
on Javascript side do something similar to this:
var data = {
'registration': {
'first_name': 'test',
'location': {
'name': 'Santa Ana',
'id': '1.08081209215E+14'
},
'gender': 'female',
'password': 123654789
}
}
and then use data in eg. jQuery .post() as the second parameter.
on the PHP side just read from $_POST as you read multi-dimensional associative arrays. In this case it should look similar to:
// I have made assumption here (you do not have
// 'login' variable in your example)
$login = $_POST['registration']['first_name'];
$pass = $_POST['registration']['password'];
$gender = $_POST['registration']['gender'];
$name = $_POST['registration']['first_name'];
$carray = fns_create_talent($login, $pass, $gender, $name);
Here you go.
EDITED:
Where $arr is the array you submitted.
$carray = fns_create_talent(
/* your login var */,
$arr['registration']['password'],
$arr['registration']['gender'],
$arr['registration']['first_name']
);
I don't see your login inside the array, so I just put a comment for the login var, but you should get the idea.