jQuery weird JSON behaviour - javascript

I'm getting a array of the selected checkboxes and push them into an array.
After that I JSON.stringify() the array and send it to my PHP script.
But the weird thing is that when I send the array variable, it returns strange things.
Here is the code:
var _items = new Array();
$('input:checkbox:checked.item').each(function () {
_items.push($(this).val());
});
$.ajax({
type: 'POST',
url: btn.data('url'),
data: {_token: token, items: JSON.stringify(_items)},
dataType: 'json',
success: function () {
//
}
})
When I console log the `_items variable I get a array back with the selected boxes like this:
["3", "4"]
In my PHP I do:
dd(json_decode(Input::get('items')));
But the strange thing is the _items variable returns an array of this in my PHP script:
0: 2
1: 0
2: 3
3: 1
4: 1
5: 4
6: 1
When I manually created the _items variable like so: var _items = ["3", "4"];
It does return the correct array..
EDIT: When I try to send it as a array it will return the same result as the strange thing above..
EDIT2: The code where I print the PHP array with. I catch the route with laravel (this is working as it should) and then I die and dump (dd) the input. Same as $_POST['items']:
Route::post('user/destroy/multiple', function () {
dd(json_decode(Input::get('items')));
});
EDIT3: Strange things is when I output Input::get('items') it does return a JSON string, but for some reason I just can't json_decode it..
What can be wrong with the code...?

From http://laravel.com/docs/4.2/requests:
Note: Some JavaScript libraries such as Backbone may send input to the
application as JSON. You may access this data via Input::get like
normal.
So in your JavaScript you should do the following:
$.ajax({
type: 'POST',
url: btn.data('url'),
data: {_token: token, items: _items},
dataType: 'json',
success: function () {
//
}
})
And in PHP you should do:
Route::post('user/destroy/multiple', function () {
dd(Input::get('items'));
});

The problem is that you are encoding the array to Json in your javascript code, you don't have to do that, just send the array itself, the Ajax call will encode it for you. By doing that you are encoding twice the array to Json ! Replace data: {_token: token, items: JSON.stringify(_items)} by data: {_token: token, items: _items},

You want to serialize object, not array
Change your code:
var _items = {};
and something like this
$('input:checkbox:checked.item').each(function (i,v) {
_items[i] = v;
});

Related

Error to pass to PHP Papa Parse object using AJAX

I would like to extract a CSV local file in PHP using AJAX.
To do that I tried to use Papa Parse and it works great. The problem is to pass the results with AJAX. I tried with JSON.stringify, I tried to pass only the first field; I tried also to create a JSON object and then add the results to this object but, I don't know why, when I extract in PHP I got only the values of the original object.
values = {};
values['row_1'] = 'value1';
values['row_2'] = 'value2';
i = 3
$("input[type=file]").parse({
config: {
delimiter: ",",
step: function(results) {
value = results.data[0]
values['row_' + i] = value
i = i + 1
}
}
});
$.ajax({
type: "POST",
url: "extract-csv.php",
data: {
id: $('#id').val(),
...
values: values
}
...
})
With this code on PHP I returned only "value1" and "value2" (if I print "values" in the console I get object with 2++ elements)
Papa Parse worked after Ajax, so the solution is to put the Ajax call in the "Complete" Papa Parse function and then everything works fine!

Sending an array per ajax request

I want to send as ajax request with array(which can be any length) as 1 parameter, something like :
mandatoryFields = [];
for (i = 1; i <= post_type_max_elements; i++) {
...
var mandatoryItem = []
mandatoryItem['optionName'] = optionName;
mandatoryItem['optionValue'] = optionValue;
}
var data = {
action: 'update_mandatory_fields',
post_type: select_post_type,
mandatoryFields: mandatoryFields
};
jQuery.ajax({
type: 'POST',
dataType: "json",
data: data,
...
Seems, that this not work, as on server parameter mandatoryFields is not defined.
Which is the best way?
Thanks!
You can use JSON.stringify() to convert your array into a String.
The JSON.stringify() method converts a JavaScript value to a JSON string, optionally replacing values if a replacer function is specified, or optionally including only the specified properties if a replacer array is specified.
In your example:
$.ajax({
type: "POST",
url: url,
data: {yourData: JSON.stringify(data)},
success: function(response){
//Callback function - do something if the request succeeded
}
});
Note that you can also use $.post() instead of $.ajax().
To reconstruct the array with php, you can use json_decode($_POST['yourData']);
jQuery, by default, serializes array in the PHP way:
$.ajax({
url: "http://example.com/",
data: {
foo: [1, 2]
}
})
will serialize to http://example.com/?foo[]=1&foo[]=2. If your serverside framework supports this style of parameter passing, you should get an array reconstructed in the parameters object.
If not, and if your server supports multiple parameter values for the same name, you can $.ajaxSetup({ traditional: true });; this will make ajax serialize to http://example.com/?foo=1&foo=2.
The third option, as mentioned by maja, is to explicitly JSON-encode (and on serverside, JSON-decode) all composite values.
Since you did not specify what you have for your serverside solution, I can't tell you which of the first two elegant scenarios you can use; the third, manual one is foolproof.
I made on client :
mandatoryFields[mandatoryFields.length]= JSON.stringify( {optionName: optionName, optionValue: optionValue} )
and on server I see that $_POST(php) var has value:
update_mandatory_fields $_POST::Array
(
[action] => update_mandatory_fields
[post_type] => post
[mandatoryFields] => Array
(
[0] => {\"optionName\":\"post_type_mandatory_selection:post::element_1\",\"optionValue\":\"post_type_mandatory_selection:post::element_1:C\"}
)
)
In circle I did not find the right way how deal with string
[0] =>
{\"optionName\":\"post_type_mandatory_selection:post::element_1\",\"optionValue\":\"post_type_mandatory_selection:post::element_1:C\"}
foreach( $mandatoryFields as $nextMandatory ) {
$optionValue= json_decode($nextMandatory['optionValue']); // NULL
$optionName= json_decode($nextMandatory['optionName']); // NULL
which is the right way?

Ajax array only returns 1 value?

I am new to PHP and Ajax so please bear with me. I've searched around and found some answers but still am having trouble. I have an array of check box input values. If a user checks an item it is added to my array list. An example would be:
listOfPrograms = [chrome, firefox, sqlworkbench]
I want to send this array list to a PHP script on my server. My current Ajax script is as follows:
function ajaxPostToPhp(listOfPorgrams)
{
$.ajax
({
url: 'script.php',
type: 'post',
data: ("listOfPrograms" : listOfPrograms), // I believe this is where my issues lies as I do not know exactly that this is doing. I have read the PHP documentation. I tried converting to JSON and kept getting a 500 error.
success: function(data)
{
console.log(data);
}
});
}
My PHP script is as folllows:
$myArray = $_Request['listOfPrograms'];
echo $myArray;
This returns only 1 item from the array. I tried setting myArray = [] but I get an undefined index.
Thanks for your help! Sorry for such a noob question.
You need to fix a few things:
1- Javascript array:
var listOfPrograms = ['chrome', 'firefox', 'sqlworkbench'];
2- Ajax Data:
function ajaxPostToPhp(listOfPrograms)
{
myListData = {};
myListData['Programs'] = listOfPrograms;
$.ajax({
url: 'script.php',
type: 'post',
data: myListData,
success: function(data)
{
console.log(data);
}
});
}
3- Php Code:
$myArray = $_POST['Programs'];
var_dump($myArray);
You are passing an array as post parameter but they can only be strings. You should convert the array to a JSON string first. An easy function for that purpose is JSON.stringify()
var listOfPrograms = ["chrome", "firefox", "sqlworkbench"]
// I guess you need strings here
function ajaxPostToPhp(listOfPorgrams) {
$.ajax ({
url: 'script.php',
type: 'post',
// Convert listOfPrograms to a string first
data: ("listOfPrograms" : JSON.stringify(listOfPrograms)),
success: function(data) {
console.log(data);
}
});
}
jquery will kindly turn array values in ajax post data to an array for you. the issue is that in php you can't just echo an array. as a commenter stated, your php file needs to look like
$myArray = $_Request['listOfPrograms'];
echo json_encode($myArray);
also you should consider using $_POST over $_REQUEST

Passing an array variable from JS to PHP using AJAX call

I have a array variable in jQuery which is created as follows:
var values = $('input:checked').map(function() {
return this.value;
}).get();
Assume the values in the array variable as 1,2,3. I am trying to pass this variable to php using the below ajax call:
doAjaxCallDelete("delete_checked", "values");
The ajax function is written as below:
function doAjaxCallDelete(mode, values) {
$.ajax({
url: ajaxURL,
type: "post",
data: {mode: mode, values: values},
async: false,
success: function(data){
responseData = data;
},
error:function(){
alert('Connection error. Please contact administrator. Thanks.');
}
});
return responseData;
}
I am retrieving this value in php using:
$myArray = $_REQUEST["values"];
But when I echo $myArray its showing 'values' instead of the real values inside the variable.
Can anybody suggest a solution to pass values of the array variable properly. Thanks in advance.
it is the double quotes you use in the function call
doAjaxCallDelete("delete_checked", "values");
you pass a string "values" instead of variable values.
use doAjaxCallDelete("delete_checked", values); instead.
note:
use $_POST['values'];

Get Param value passed after sucess of Ajax call

<a class="removeApp" data-app="12">Close Something </a>
$('.removeApp').click(function (e) {
$.ajax({
async: false,
type: 'POST',
url: '#Url.Action("Remove", "Something")',
data: {
id: $(this).data("app")
},
success: function (result, data) {
console.log(this.data ); //gives id=12
console.log (this.data["id"] ) ///gives nothing how do i get just 12
}
})
});
I am trying to get the data that is passed by parameter name how can i do so?
Well the data should look something like "{'id' : 12}", this would then be JSON and you could use the jQuery.getJSON() function and this would return a javascript object - which is what you want.
I think that currently you're getting a string equal to "id=12" as a response - all HTTP data is a string, that's just how it works.
You can parse the string with a bit of javascript:
var id = parseInt(data.split("=")[1]);
That's a bit hardcoded and ugly however.

Categories