I am posting my form using AJAX:
$(function () {
$("#Compare").click(function (e) {
$.ajax({
url: '#Url.Action("_Compare","API")',
dataType: 'application/json',
data: {
model: $("#CompareForm").serialize()
},
type: "post",
success: function(response) {
alert (response);
}
});
e.preventDefault();
});
});
I am trying to deserialize my JSON result but I am getting an 'Invalid Json Primitive Exception'.
My Json Result:
"%5B0%5D.Id=1&%5B0%5D.Description=Sutherland+Silver+Plans+offers+you...&%5B0%5D.Price=30&%5B0%5D.Title=Silver+Plan&%5B0%5D.isSelected=true&%5B0%5D.isSelected=false&%5B1%5D.Id=2&%5B1%5D.Description=Sutherland+Gold+Plans+offers+you...&%5B1%5D.Price=50&%5B1%5D.Title=Gold+Plan&%5B1%5D.isSelected=true&%5B1%5D.isSelected=false&%5B2%5D.Id=3&%5B2%5D.Description=Sutherland+Platinum+Plans+offers+you...&%5B2%5D.Price=80&%5B2%5D.Title=Platinum+Plan&%5B2%5D.isSelected=false"
You seem confused about what JSON is, and whether the issue is with the request or the response.
The issue is with the request. You are attempting to put the querystring that serialize() creates in to the model parameter of an object, which itself will be serialised and encoded again. Instead, just pass the querystring that serialise generates to the action:
$("#Compare").click(function (e) {
$.ajax({
url: '#Url.Action("_Compare","API")',
dataType: 'application/json',
data: $("#CompareForm").serialize(),
type: "post",
success: function(response) {
console.log(response);
}
});
e.preventDefault();
});
You have specified the response will be JSON. If this is the case, use console.log to inspect it, otherwise the alert() will only show [object Object].
Related
With my AJAX call, I want to get the json data entirely.
For example www.abc.com/api/3 gives {"information":.... json data with many levels...}}
I want to store this data in variable.So I try this:
$.ajax({
async: false,
type: 'GET',
dataType: 'json',
url: url,
data: data,
success: function(data) {
x=data;// It's wrong, but I don't know how to put whole json into x
}
})
You can use $.ajax() as a Promise:
$.ajax({
type: 'GET',
url: url,
}).then((data) => {
console.log(data);
});
I have the following Jquery code that sends a ajax request to add-to-cart.php.
var productData = {
"product_id": s_product_id,
"product_opties": s_product_opties,
"product_aantal": s_product_aantal
}
productData = JSON.stringify(productData);
$.ajax({
url: 'inc/add-to-cart.php',
dataType: "json",
contentType: "application/json; charset=utf-8",
data: productData,
type: 'POST',
success: function(response) {
alert(response.d);
},
error: function(e){
console.log(e);
}
});
Add-to-cart.php:
<?php
print $_POST['product_id'];
?>
I am having two problems, the first one is that the $_POST['product_id'] does not exists when i ask for it and secondly when the ajax response returns it goes directly to the error: function and not succes function
The console log says:
[object Object]{readyState: 4, responseText: "<br /> <b>N...", status: 200, statusText: "OK"}
If the status is OK why does it jump to the error: part?
Thanks!
Try with:
...
var productData = {
'product_id': s_product_id,
'product_opties': product_opties,
'product_aantal': product_aantal,
}
$.ajax({
url: 'inc/add-to-cart.php',
dataType: 'json',
data: productData,
type: 'POST',
success: function(response) {
console.log(response.d);
},
error: function(e){
console.log(e);
}
});
...
Omitting the AJAX contentType parameter and the part where you stringify your JSON, that's already ready to be sent to your url, so, isn't needed.
Remove the line
productData = JSON.stringify(productData);
Then do not return HTML <br> ... from add_to_cart.php, you need to return a JSON string created by the PHP function json_encode and NOTHING ELSE.
Like in:
<?php echo json_encode(array('d' => 'value of d'));
First: status Code from the Webserver is 200 cause he deliverd an existing site.
Second: You dont need to stringify the json object by urself
I have My jquery function that is returning me data of the formatt:
{"Suggestions":[{"name":"RR Restaurant","category_id":"166","locality":"Gayathri Nagar","listing_info":"listing","random_id":"1ll0f0wJ"},{"name":"Oko Restaurant","category_id":"166","locality":"Kumara Krupa","listing_info":"listing","random_id":"0F7ZGV9p"},{"name":"H2O Restaurant","category_id":"166","locality":"Maratha Halli","listing_info":"listing","random_id":"0JNPOyuP"},{"name":"Taj Restaurant","category_id":"166","locality":"Shivaji Nagar","listing_info":"listing","random_id":"7GeA0Kfq"},{"name":"PSR Restaurant","category_id":"166","locality":"Peenya Industrial Area","listing_info":"listing","random_id":"cRvJCwQ3"},{"name":"ac restaurant","category_id":"166","listing_info":"keyword"},{"name":"Indian Restaurant","category_id":"166","listing_info":"keyword"},{"name":"goan restaurant","category_id":"166","listing_info":"keyword"},{"name":"thai restaurant","category_id":"166","listing_info":"keyword"},{"name":"andhra restaurant","category_id":"166","listing_info":"keyword"}],"ImpressionID":"test"}
I wish to parse the same to get multiple variables with The field "Name" and "Random Id" in different js variables
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
My JSON object seems to be nested with "Suggestions" as the parent. Please help.
If you add a property to $.ajax function you be ensure that is json parsing:
dataType: 'json'
EDIT
To iterate above the string you can use for(in) or each() jquery
json = "[{'key':'value'},{'key':'value']";
for(var i in json) {
console.log(json[i]);
//if you see in console [OBJECT Object] you are
//in a new object you must to iterate nested of this.
}
$("#what").on("keypress", function() {
$.ajax({
type: "GET",
dataType: "JSON", //You need this to be inserted in your ajax call.
cache: false,
url: "/AutoComplete.do",
data: {
query: 'Pest',
city: 'Bangalore'
}, // multiple data sent using ajax
success: function(data) {
alert();
}
});
});
After insert dataType you can probably do this.
console.log(data.Suggestions);
Also take a look at the API Doc at below url regardless of dataType.
http://api.jquery.com/jquery.ajax/
The data object you are specifying is what will be sent as the arguments to your success method, if you use the GET method.
$("#what).on("keypress", function() {
$.get("/AutoComplete.do", function(response) {
var data = JSON.parse(response);
//data.suggestions = [lots of objects];
//data.suggestions[0].locality = "Gayathri Nagar"
});
});
Following is the code that Ii have used to get the response in json.
but when I add alert alert(response.Subject); it returns "undefined"
HTML:
<input type="text" id="subject" value='Subject'>
Javascript:
$.ajax({
url: "/ebays/prefilledcontentajax",
type: "POST",
cache: false,
async: true,
data: {
Type: $("#Type").val(),
},
success: function (response) {
console.log(response); // it show the json that response returns. I want to show in the input box prefilled with the data that response return
}
});
please help me out.
You can use val to set value in the textbox
$('#subject').val(response[0].Subject);
Also, you might want to change the ajax call:
$.ajax({
url: "/ebays/prefilledcontentajax",
type: "POST",
cache: false,
async: true,
data: {
Type: $("#Type").val(),
},
dataType: "json",
// ^^^^^^^^^^^^^
success: function (response) {
// response is JSON
$('#subject').val(response[0].Subject);
}
});
val
Set the value of each element in the set of matched elements.
http://api.jquery.com/val/#val2
ajax
Perform an asynchronous HTTP (Ajax) request.
http://api.jquery.com/jQuery.ajax/
It really depends the construction of your JSON object, but standart is responseText that you parse with JS
maybe you try to get the response text or response JSON
$.ajax({
url: "/ebays/prefilledcontentajax",
type: "POST",
cache: false,
async: true,
data: {
Type: $("#Type").val(),
},
success: function (response) {
console.log(JSON.parse(response.responseText));
//or
console.log(JSON.parse(response.responseJSON));
}
});
you can write like this:
$('#subject').val(response.Subject);
I thinks it's really easy. Just add:
$('#subject').val(response.Subject);
in your success handler.
I'm calling a page (external, on other domain), with this code:
var instagram_container = $('div#instagram-answer');
if (instagram_container.length>0)
{
var url = 'http://www.xxxx.it/admin/get_instagram_token';
$.ajax({
type : 'GET',
url : url,
async : false,
jsonpCallback: 'jsonCallback',
contentType: 'application/json',
dataType: 'jsonp',
success: function(response)
{
console.log(response);
instagram_container.html(response.client_id);
},
error: function(e)
{
console.log(e);
}
});
}
I have answer with console.log(e) (basically it recognizes as error)?
Object { readyState=4, status=200, statusText="success", altri elementi...}
But in Firebug, under NET tab, I have the right answer...
This is the console. Line 19 is exactly the
console.log(e);
in error section.
My goal is obtain that Json. Thank you
Is your server returning plain text, or an actual JSON file? Jquery will ignore the response if the server returned a string instead of JSON.
The response type should be: "application/json"
EDIT:
I'd recommend you to use the basic jquery ajax call:
$.ajax({
url: "test.html",
cache: false
})
.done(function( response ) {
console.log(response);
});