I am new to JSON.
In JS, I create an array of values like so:
var arrFields = $("td>.frmInput").map(function(){
return {
id: this.id,
value: $(this).val()
};
}).get();
I then AJAX them to the server like so:
$.ajax({
type: "POST",
url: "ajax/ax_all_ajax_fns.php",
data: "Fields=" +JSON.stringify(arrFields),
success: function(recd) {
alert(recd);
}
});
Note that there is a mixture of strings, plus the JSON.stringified (?) array. (There are additional string values sent, so data must remain as string.)
On the PHP side, I need to turn the received Fields string into an associative array.
Doing this:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
Returns this text string in the alert():
[{"id":"rateDriver","value":"Jacques Villeneuve"},{"id":"rateCar","value":"Chev"}]
Doing this:
$arrFields = json_decode($jsonAsStr_Fields, TRUE);
$driver = $arrFields['rateDriver'];
$car = $arrFields['rateCar'];
$tire = $arrFields['rateTire'];
die('Driver: [' .$driver. '] Car: [' .$car. '] Tire: [' .$tire. ']');
Returns this:
Driver: [ ] Car: [ ] Tire: [ ]
How can I turn the $jsonAsStr_Fields string into an assoc array, and thereby output the correct values to my alert?
Do this instead for your creation of values:
var arrFields = {};
$("td>.frmInput").each(function(){
arrFields[this.id] = $(this).val();
});
This will create an object, when JSON-stringified, that looks like this:
{"rateDriver":"Jacques Villeneuve", "rateCar":"Chev"}
Which seems to be the format you want to use in your PHP code.
You have an array of associative arrays and your arrays don't have the specified props, rateDriver for example is the value of the first array's element's id:
$driver = $arrFields[0]['id'];
$car = $arrFields[1]['id'];
For seeing the array's contents you use the famous var_dump function.
From the Author:
For those who haven't fully understood what solved this problem.
The underlying problem was that the stringified JSON was being modified en route (immed after hit Submit button en route to the PHP side) by the AJAX. All quote marks were being escaped, which made it impossible for that string to work with json_encode.
This was discovered by grabbing the value of the received data once it hit the PHP side:
$jsonAsStr_Fields = $_POST['Fields'];
die($jsonAsStr_Fields);
And alerting the received data in the AJAX success function:
success: function(recd) {
alert(recd);
}
Both of the above were described in the OP.
However, because I assumed this was an unrelated problem, I "fixed" the string displayed in the alert() box when I posted the question. Lesson to be learned: don't help - just post what you actually see.
It really displayed like this:
{\"id\":\"rateDriver\",\"value\":\"Jacques Villeneuve\"}
but I wrote that it displayed like this:
{"id":"rateDriver","value":"Jacques Villeneuve"}
Of course, the json_decode() PHP function had no idea what to do with the backslashes, so the string did not convert.
Solution was to use str_replace() on the received JSON string over on the PHP side, to resolve the problem, like this:
str_replace("\\", "", $_POST['Fields']);
Related
I'm loading a large amount of data into a Node array. Then, I'm passing that data to a PHP page like this:
const rows = res.data.values;
axios.post('./template.php', qs.stringify({rows}))
.then((res) => {
console.log(res.data);
fs.writeFileSync('test.php', res.data, 'utf-8');
})
Then, when I get to test.php, the $_POST variable is only the first 100 entries of my array I just passed.
I noticed when debugging and using console.log() to print the same array, I was getting something that said "... 19 more items". I was able to resolve that by calling this:
util.inspect.defaultOptions.maxArrayLength = null;
At the top of my function. This worked great to stop the "... 19 more items" and now the full array displays with console.log(), however, it seems to have had no effect on my POST.
I'm stumped as to what I'm missing here -- does anyone know why my array is getting truncated when doing the POST? Thanks!
Something like this
let objectData = [{a: 1, b: 2}, {a: 5, b:6}];
axios.post(url, objectData, {
headers: {
"Content-Type": "application/json"
}
})
and at the PHP side, read the raw INPUT
$json = file_get_contents('php://input');
$data = json_decode($json);
I'm revising code written by another developer. Here he collects values and turns them from an array (dataId) into a comma-separated string:
$("#retrieve_works_form").on('submit', function(e) {
e.preventDefault();
$('#toggle_search_terms').trigger('click');
var dataId = new Array();
$('li.nw').each(function() {
var thisDataId = $(this).attr('data-id');
dataId.push(thisDataId);
});
$('li.added_gallery_item').each(function() {
var thisDataId = $(this).attr('data-id');
dataId.push(thisDataId);
});
$('#returned_gallery_work_ids').val(dataId.join(','));
The $_POST['returned_gallery_work_ids'] therefore holds a comma-separated string of the values in the dataId array. I want to revise this so it simply returns the array, with each element in a sequential index. I would think that doing this would do the trick:
$('#returned_gallery_work_ids').val(dataId);
...but it doesn't; it returns a comma-separate string of values, no different than what is returned when dataId.join(',') is the argument of the .val() operator.
There are really two questions here:
Why is the result a comma-separated string in each case?
How do I make it return the dataId array?
[The second question is the truly necessary question, but I want to understand the mechanics of what's taking place here.]
When storing a value of any kind in an input, it's stored as a string, so if you later retrieve it, you'll need to split it:
var galleryArray = $("#returned_gallery_work_ids").val().split(',');
Or in PHP on the server side, you'll use this:
$galleryArray = explode( ",", $_POST['returned_gallery_work_ids'] );
Hope this helps.
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'm trying to pass an array in an ajax request, but apparently it doesn't work...
$.post("process.php", array,
function(data) {
document.getElementById("output").innerHTML = JSON.parse(data);
});
My question is, how to use the data sent in the process file?
The array is built like that: [key (0/1/2...)] => ["prod_id"]. The id varies.
I read somewhere using $_POST["key"]; would work, but it doesn't.
It'd be even better if I could just get the array as is in the process file.
process.php (really basic - just to check wether it's working or not.):
<?php
print($_POST["test"]);
?>
Try to pass {data: array} instead of array. The AJAX call expects an object.
You need to build an Object of array elements. for example:
You can also try like:
{ 'key[]': [1, 2, 3] }
OR
{ key: [1,2,3] }
Read more about $.post()
In order to receive data in php you need to send key/value pairs, however you are only sending a value.
You receive in php with $_POST[key] which will return the value for that key.
JS:
$.post("process.php", {myAray: array}, function(data) {
$("#output").html(data);
});
php
$array= $_POST['myArray'];
To return this array from php as text just to test your ajax can use var_dump( $_POST) or var_dump($array);
If you intend to receive JSON in response from server, you do not need to use JSON.parse , jQuery will parse json internally. However you would need to add "json" as dataType argument to $.post
$.post("process.php", {myAray: array}, function(data) {
/* loop over json here*/
},'json');
if you want to pass an array, you have to "prepare" the key as following:
{'key[]' : ['value1', 'value2', 'value3']}
the same way you'd do it, when you want to pass an array in a form and set the name-attribute to "key[]".
I cannot convert JS object to exact string, my code:
jsonObj['payment_value']=100.10;
jsonObj['payment_date']="2012-06-15";
jsonObjStr = JSON.stringify(jsonObj);
alert(jsonObjStr);
$.post("test", jsonObjStr.toString(), function(output){
alert(output);
});
first alert displays:
{"payment_date":"2012-06-15","payment_value":100.1}
and in function test (i'm using codeigniter framework) it should print "payment_date" and "payment_value", code like this:
echo $this->input->post("payment_value");
echo $this->input->post("payment_date");
which is equvalent in "clear" php to:
echo $_POST["payment_value"];
echo $_POST["payment_date"];
but second alert displays clear string.
If I put
{"payment_date":"2012-06-15","payment_value":100.1}
instead of jsonObjStr.toString() it works fine
Does anyone knows how to fix it WITHOUT using json_decode? I need to have posted values in this format, not in other array
So i need to convert jsonObjStr exact to string (something inversely to function eval())
Thank in advice
According to $.post docs, second argument should be map or query string:
map example:
{
"payment_date":"2012-06-15",
"payment_value":100.1
}
query string example:
'payment_date=2012-06-15&payment_value=100.1'
When you use JSON.stringify, then you get:
'{"payment_date":"2012-06-15","payment_value":100.1}'
which is invalid query string. So the solution is: do not stringify anything, pass the object itself as 2nd argument:
jsonObj['payment_value']=100.10;
jsonObj['payment_date']="2012-06-15";
$.post("test", jsonObj, function(output){
alert(output);
});