Ajax function: data fields with multiple value - javascript

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.

Related

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

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

jquery ajax data object with multiple values for the same key

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

how to pass a additional data with form serialized data on ajax?

How to pass an additional data with form serialize data on ajax post method?.
below is my code which was using for ajax post,
$(document).ready(function()
{
var additional_data=$("#extra_data").val();
$.ajax({
type: 'POST',
url: 'send_mail.php',
data: frm.serialize(),
success: function (data) {
alert(data);
}
});
});
here, how to pass a additional_data with serialize form data
From jQuery API DOCS
The .serializeArray() method creates a JavaScript array of objects
The .serialize() method creates a text string in standard URL-encoded notation.
I think to use push , we need to use serializeArray
try to use
var frmData = frm.serializeArray();
frmData.push({name: "name", value: "test"});
$(document).ready(function()
{
var additional_data=$("#extra_data").val();
$.ajax({
type: 'POST',
url: 'send_mail.php',
data: frmData,
success: function (data) {
alert(data);
}
});
});
You need to push the elements to the existing serialized data.
var frmData = frm.serialize();
frmData.push({name: nameofthevariable, value: valueofthevariable});
frmData.push({name: nameofthevariable2, value: valueofthevariable2});
frmData.push({name: nameofthevariable3, value: valueofthevariable3});
$(document).ready(function()
{
var additional_data=$("#extra_data").val();
$.ajax({
type: 'POST',
url: 'send_mail.php',
data: frmData,
success: function (data) {
alert(data);
}
});
});
serialize() create a query string of the form. So you can append additional parameters into it.
$(document).ready(function()
{
var additional_data=$("#extra_data").val();
$.ajax({
type: 'POST',
url: 'send_mail.php',
data: frm.serialize()+'&param1='+value1+'&param2='+value2,
success: function (data) {
alert(data);
}
});
});
serializearray() can be used to send additional parameters. PFB code for sending additional parameters.
var request = $('form').serializeArray();
request.push({name: "kindOf", value: "save"});
Ajax call
$.ajax({
url: "/ST/SubmitRequest",
dataType: "json",
//contentType: "application/json",
type: "POST",
data: request,
//data: r1,
success: function (response) {
//Setinterval();
//alert("Done...!");
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});

using object for ajax and php

To avoid duplicate codes, I plan to write OOP. It's a single page app, it has many operation performed by users. For example CRUD (create, read, update & delete).
var dltTask = $.ajax({
url: "process.php",
type: "POST",
data: {
insert: "something"
},
dataType: "text"
});
dltTask.done(function (msg) {
alert(msg);
});
How to pass argument to ajax as object? for example in my insert,
insert = new ajax(insert, data1,data2,data3);
you can pass values like that
postval = {
data1: data1,
data2: data2,
data3:data3
}
var dltTask = $.ajax({
url: "process.php",
type: "POST",
data: postval,
dataType: "text"
});
dltTask.done(function (msg) {
alert(msg);
});

Categories

Resources