jquery ajax data object with multiple values for the same key - javascript

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

Related

How to pass query string parameter to ajax call from data

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&param2=val2

How to access the elements of an object in the success property of $.ajax method?

function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: {id:id},
dataType: 'json',
success: function(data) {
console.log(data);
}
});
};
The JSON object returned from the get_data.php script is:
{
id: 5,
username: "Anthony",
status: "accupied"
}
I am able to the length of the data object if I do console.log(data.length). However, I can see the object when I console.log(data) in the success property.
I am not able to access the elements of the data obejct if I do console.log(data.username), doing this displays undefined in the console.
I created a variable, data1, outside the scope of the function getReportedInfo and assigned the data retrieved via the success property to
this variable after I tried to display the constents of data1 outside the function.
Sounds like data is a string not an object. You can convert this to an object by using JSON.parse. Try the following code.
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: {id:id},
dataType: 'json',
success: function(data) {
var dataObject = JSON.parse(data);
console.log(dataObject.username);
}
});
};
Edit
After discussing with OP in comments below, it was determined the object returned data was in a structure like the following, and is already in an object form (not a string)
{
"0": {
id: 5,
username: "Anthony",
status: "accupied"
}
}
Therefor the following code should work.
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: {id:id},
dataType: 'json',
success: function(data) {
console.log(data["0"].username);
}
});
};
If in php your return like this way
<?php
echo json_encode($array);
// or
return json_encode($array);
In JavaScript you can use it as you try to use, now, apparently you are not returning a JSON even though you are indicating it in the request, in this case it uses parse:
function getReportedInfo(id) {
$.ajax({
url: 'includes/get_data.php',
type: 'POST',
data: { id:id },
success: function(data) {
var response = JSON.parse(data);
console.log(response.id); // return 5
}
});
};

Ajax function: data fields with multiple value

I have a doubt about the data fields of ajax function.
Usually, we have that a syntax for ajax function may be:
$.ajax({
url: "/aaa/bbb/ccc",
method: "SomeMethod",
data: someData,
success: function (response) {
do something
}
My question is: in data fields, can i put more than one data? In other words, can I pass from:
data: someData,
to:
data: data1, data2, data3...
and so on?
You can create an object that holds the data. data: {date1Name: data1Value, date2Name: data2Value}.
Your complete code should look like this.
$.ajax({
url: "/aaa/bbb/ccc",
method: "SomeMethod",
data: {date1Name: data1Value, date2Name: data2Value},
success: function (response) {
do something
}
You can create an object of key/value pairs.
$.ajax({
...
data : { data1: 'bar', data2: 'foo' },
...
});
Here is how you can build multiple params, hold them in an object and send them as JSON.stringify():
var paramsToSend = {};
paramsToSend['data1'] = 'data1';
paramsToSend['data2'] = 'data2';
$.ajax({
...
data: {params:JSON.stringify(paramsToSend)},
...
});
$.ajax({
url: "/aaa/bbb/ccc",
method: "SomeMethod",
data: "name=value&name1=value1&name2=value2",
success: function (response) {
//do something
}
});
$.ajax({
url: "/aaa/bbb/ccc",
method: "SomeMethod",
data: {name : 'Luca', country : 'NA'},
success: function (response) {}
})
It looks like you want to pass it as an array?
$.ajax({
url: "/aaa/bbb/ccc",
method: "SomeMethod",
data: { data:[data1, data2, data3] },
success: function (response) {
do something
}
I would recommend putting the array in a dictionary / JSON object so you have a variable name to key off of in whatever backend language you are using.

How to escape brackets in an ajax request?

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 Unable to Parse a JSON in JQuery

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

Categories

Resources