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"
});
});
Related
$("#nonjstest").click(function() {
$.ajax({
url:"https://petstore.swagger.io/v2/pet/findByStatus?status=sold",
type: "GET",
contentType:"application/json",
success: function(data){
alert(data[0].id)
}
})
})
Here, I am passing the required parameters directly in the URL status=sold.
I want to pass them via a variable instead, but it's not working. I've tried the following:
var requiredata = ["status=sold"]
$("#nonjstest").click(function() {
$.ajax({
url:"https://petstore.swagger.io/v2/pet/findByStatus",
type: "GET",
data: requiredata,
contentType:"application/json",
success: function(data){
alert(data[0].id)
}
})
})
The request itself is successful, but nothing is returned, meaning, the parameters are not passed correctly. What is the problem with the way I'm passing the Array string?
I've tried stringifying the data, but it didn't work either.
Why is it not working? How do I pass the array string data with a variable?
Try sending the params as an object instead of as an array:
var requiredata = {
status: 'sold'
};
$("#nonjstest").click(function() {
$.ajax({
url:"https://petstore.swagger.io/v2/pet/findByStatus",
type: "GET",
data: requiredata,
contentType:"application/json",
success: function(data){
alert(data[0].id)
}
})
});
Another option would be to pass the params as a string but it's worse because you have to pass it already encoded.
Check the docs for more information.
I'm using ajax call for hit the API & i want to send an query parameter, How can i send query parameter with ajax call. Here is my code. Any help on this will be appreciated, Thanks.
$("[id*=btnok]").click(function (e) {
e.preventDefault();
var obj = {};
obj = $.trim($("[id*=nodays]").val());
$.ajax({
url: "/apilink",
"data": {
"api": "api",
"params": "?userType=driver&type=true&count=" + obj
},
type: "post",
dataType: "json",
success: function (r) {
console.log(r)
}
});
});
As you're sending a POST request any properties in the data object will be added to the body of the request. To force a value to be sent in the querystring you need to manually append it to the string you provide to the url property.
Also note that defining obj as an empty object is redundant as $.trim() always returns a string.
$("[id*=btnok]").click(function (e) {
e.preventDefault();
var obj = $.trim($("[id*=nodays]").val());
$.ajax({
url: "/apilink?params=" + obj,
data: {
api: "api",
},
type: "post",
dataType: "json",
success: function (r) {
console.log(r)
}
});
});
As I see you make a post request so parameters are passed in params property in request body. But as an option you can add string params to your /apilink. Like that: /apilink?param1=val1¶m2=val2
I would like to send a GET request with only one parameter from an input form via AJAX, using jQuery.ajax().
To simplify things, instead of
data: $("#the_form").serialize()
I tried to explicitly pass the value of the input:
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: {
tx_search_pi1['sword']: val
},
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
Now this breaks because of the brackets and quotes in
tx_search_pi1[sword]: val
(which is required by the recipient of the get request)
How do I escape the brackets (and maybe also single quotes inside= correctly?
I've tried-and-errored many combinations, eg. with
tx_search_pi1%5Bsword%5D
encodeURIComponent("tx_kesearch_pi1[sword]")
etc...
You can try this,
data: $("#the_form").serialize()+'&sword='val,
Full Code,
function lookupSearch(val){
$.ajax({
type: "get",
url: "/search",
data: $("#the_form").serialize()+'&sword='val,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
And if you want to pass sword value then use,
data: {'sword':val}, // get using sword key
As per #Urs Comment the code should be,
// let it is initialised before,
// and it is an object like {}, tx_search_pi1 = {key:"1",...};
function lookupSearch(val){
tx_search_pi1['sword'] = val;
$.ajax({
type: "get",
url: "/search",
data: tx_search_pi1,
success: function(data)
{
$("#results").html(data);
console.log("Success");
}
});
}
try putting tx_search_pi1['sword'] this in a variable and pass it.
Like
var temp = tx_search_pi1['sword'];
And pass temp
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].
I would like to make an ajax call, and in the data object I need to have several values in the same key.
var data = {
foo: "bar",
foo: "baz"
}
$.ajax({
url: http://example.com/APIlocation,
data: data,
success: function (results) { console.log(results) },
dataType: 'json'
});
The intention is to get a URL that looks something like:
http://example.com/APIlocation?foo=bar&foo=baz
I tried structuring the data like this:
var data = {
foo: ["bar","baz"]
}
Which unsurprisingly, did not work because it encodes the url like this:
http://example.com/APILocation?foo%5B%5D=bar&foo%5B%5D=baz
I tried the solution here, but could not make it work.
You can use jQuery's $.param to convert an array to a parameter string that contains the same key multiple times. Set the second argument to true so it doesn't get url-encoded, and then just pass that string to the data property in the AJAX call:
var data = $.param({ foo: ['bar', 'baz'] }, true);
// data is now 'foo=bar&foo=baz'
$.ajax({
url: 'http://example.com/APIlocation',
data: data, // Will handle the string correctly.
success: function (results) { console.log(results) },
dataType: 'json'
});
Or, with an object, you can set the traditional property to true:
var data = {
foo: ["bar","baz"]
};
$.ajax({
url: 'http://example.com/APIlocation',
data: data,
success: function (results) { console.log(results) },
dataType: 'json',
traditional: true
});