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?
Related
I have the following JavaScript:
var ids = [
"ed4bbe0e-d318-e811-a95f-000d3a11f5ee",
"386c9468-d11b-e811-a95d-000d3a11ec14",
"2913f317-991d-e811-a95d-000d3a11ec14"
];
$.ajax({
method: 'POST',
url: `/Jobs?handler=CreateJobsInQBO`,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
// contentType: 'application/json',
data: { jobIds: ids }
})
POSTing to the Razor Page handler below
public async Task<JsonResult> OnPostCreateJobsInQBO(IEnumerable<string> jobIds) {
Result<List<Job>> result;
if (jobIds == null || !jobIds.Any()) {
result = "No jobs were submitted.";
} else {
result = await DoStuffAsync(jobIds);
}
return new JsonResult(result);
}
This works without issue.
The problem is that when my JavaScript array is large, roughly 3000 items, I get null for the incoming handler parameter value. I've tried setting the ajax contentType to application/json and also using JSON.stringify on the object before it's sent, but they don't seem to make a difference. I also tried setting [FormBody] on the parameter in the handler function, but again, it didn't work.
I know I'm missing something simple here. I just need a way to POST an array of string to a handler method that has roughly around 5000 items. Preferably without using the application/x-www-form-urlencoded content type as I think that is what's causing the large array to not work.
The default value of ValueCountLimit is 1024. It is a limit for the number of form entries to allow.
If the value count exceed 1024, you should increase it in Startup.cs
services.Configure<FormOptions>(options =>
{
options.ValueCountLimit = int.MaxValue;
});
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
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;
});
I have this working code:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']'),
complete: function (mydata) {
//do something with it
}
});
That successfully posts back any checked checkboxes and all textboxes. But now I want to add some arbitrary data as well to this. But not sure how to format it. Basically i want to simply add my own name=value pair "test=1" so that on the callback I see it like the others. But no matter what I try, I can't see to get the syntax correct in the format it expects. not sure if I should be adding it inside the jQuery() wrap or outside.. I've tried serializing, encodeURIComponent, basic string "&test=1"
Any ideas?
Your best bet is to build the parameters outside of the AJAX call, like so:
var params = jQuery(':input[name^="option"][type=\'checkbox\']:checked, :input[name^="option"][type=\'text\']');
params.test = 1;
params.test2 = 2;
Then in your AJAX call, simply use:
jQuery.ajax({
type: 'post',
url: 'http://www.someurl.com/callback.php',
dataType: 'json',
data: params,
complete: function (mydata) {
//do something with it
}
});
EDIT: Typically when using jQuery to collect input, I tend to use the .each function, like so:
var params = new Object();
$.each('input[name^=option]', function() {
if ((this.type === 'checkbox' && $(this).is(':checked')) || this.type === 'text' && this.value !== '') {
params[this.name] = this.value;
}
});
Then if you wish to add parameters, you'd do so either after this, or right after creating your new object.
I forgot I asked this previously. It was answered correctly so I'm sharing the link:
How can I pass form data AND my own variables via jQuery 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.