Get Param value passed after sucess of Ajax call - javascript

<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.

Related

Passing php string as json to be received by jquery

I am trying to echo a string which is structured like json, but the jquery ajax post is not able to parse it properly. What I want to know is if this string will be treated like json in the jquery json parse just like when we echo a json_encode.
echo '{"mobno":'.$mobno.',"charge":'.$charge.',"capacity":'.$capacity.'}';
ajax code:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
var Vals = JSON.parse(response);
if(!Vals){
alert("Error1");
}else{
var capacity = parseInt(Vals.capacity);
if(capacity>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
I don't get a single alert out of the 3.
As per your edit and comment, your json string is correct. You just have to change your AJAX request.
Add this setting dataType: "json" in your AJAX request if you're expecting a json object as response from server.
So your AJAX request should be like this:
jQuery.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
dataType: "json",
success: function(response){
// you can access json properties like this:
// response.mobno
// response.charge
// response.capacity
var capacity = response.capacity;
if(capacity > 0){
alert("worked1");
}else{
alert("worked2");
}
}
});
Just so JavaScript can differ string and properties of json, please use double quote for starting and ending the string and for json properties use single quote or vice-versa. Try that out and let me know if you could not figure that out.
As other answers suggest you need to fix the quotes of the JSON the web service is sending back in the response.
Regarding you question, everything sent back in the response is actually a string. You need to decide what to do with it once it arrives.
One of the ways to allow both client side and server side programs understand what was sent is setting the right content type header.
For JSON the best way is to set the content type header to "application/json".
If you're using php you can do this:
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data);
On the client side jquery ajax you can do this:
$.ajax({
dataType: "json",
url: url,
data: data,
success: function(data, textStatus, jqXHR){}
});
In this example the "data" parameter passed to the "success" callback function is already a js object (after JSON.parse). This is due to the use of the "dataType" parameter in the ajax declaration.
Optionally, you can do this manually and write a simple $.post which receives a string and do the JSON.parse yourself.
Maybe you should do the manual parsing yourself at first, and use the console.log(data) before and after the parsing so you'd know you're doing it correctly. Then, move on to the automatic way with "dataType" set to "json".
Please see #Rajdeep Paul's JSON string correction. Then, have your response JSON object remapped to an array.
JSON string
echo "{\"mobno\":\"".$mobno."\",\"charge\":\"".$charge."\",\"capacity\":\"".$capacity."\"}";
Ajax
$.ajax({
type: "POST",
url: "file.php",
data: { type: $(this).val(), amount: $("#amount").val()},
cache: false,
success: function(response){
// map JSON object to one-dimensional array
var Vals = $.map( JSON.parse(response), function(el) { return el });
if(!Vals){
alert("Error1");
}else{
var count = parseInt(Vals.length);
if(count>0){
alert("worked1");
}else{
alert("worked2");
}
}
}
});
Reference: Converting JSON Object into Javascript array

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

jQuery weird JSON behaviour

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;
});

AJAX form submission hits proper endpoint but doesn't pass variables

I'm working on the review page before a user buys a product, and on the page is a small field for discount codes, which I want to pass to an endpoint via ajax. I'm using the following javascript function, and the submission happens and returns (even hits the intended endpoint) - but no data gets passed through (verified in logs).
Any idea why no params would be getting passed through?
<script>
$("#discount_code_submit").click(function() {
var url = "/confirm_discount"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#discount_form").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
return false; // avoid to execute the actual submit of the form.
});
</script>
This is because jQuery's serialize method creates a String representation of the form data, in the traditional url query string format. (Please see here: http://api.jquery.com/serialize/)
E.g., calling serialize can return a string such as:
'?query=help&numResults=200'
On the other hand, jQuery's ajax method expects the form data to be provided as an object literal. (Please see here: http://api.jquery.com/jQuery.ajax/)
E.g.
{
query: 'help',
numResults: 200
}
So you can change your ajax call to look like:
$.ajax({
type: "POST",
url: url,
data: {
param1: 'somevalue',
param2: 200
},
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
Or, you could also construct your object literal from the form using a custom function and then provide the reference in the ajax call.
$.ajax({
type: "POST",
url: url,
data: myPreparedObjectLiteral,
success: function(data)
{
alert(data); // show response
if(data != "false")
{
console.log(data);
}
}
});
You could also use http://api.jquery.com/serializeArray/ since it does pretty much what you'll need to convert a form to the json literal representation.
Finally, for a good discussion on converting forms to json objects for posting, you can see the responses here on an SO question: Convert form data to JavaScript object with jQuery

Categories