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);
});
Related
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
}
});
};
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.
This is what I am trying to do. On a home page.. say /home.jsp, a user clicks on a link. I read value of the link and on the basis of which I call a RESTful resource which in turn manipulates database and returns a response. Interaction with REST as expected happens with use of JavaScript. I have been able to get information from REST resource but now I want to send that data to another JSP.. say /info.jsp. I am unable to do this.
I was trying to make another ajax call within success function of parent Ajax call but nothing is happening. For example:
function dealInfo(aparameter){
var requestData = {
"dataType": "json",
"type" : "GET",
"url" : REST resource URL+aparameter,
};
var request = $.ajax(requestData);
request.success(function(data){
alert(something from data); //this is a success
//I cannot get into the below AJAX call
$.ajax({
"type": "post",
"url": "info.jsp"
success: function(data){
alert("here");
("#someDiv").html(data[0].deviceModel);
}
});
How do I go about achieving this? Should I use some other approach rather than two Ajax calls? Any help is appreciated. Thank You.
You can use the following function:
function dealInfo(aparameter) {
$.ajax({
url: 'thePage.jsp',
type: "GET",
cache: false,
dataType: 'json',
data: {'aparameter': aparameter},
success: function (data) {
alert(data); //or you can use console.log(data);
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': data},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
});
}
Or make the AJAX call synchronous:
function dealInfo(aparameter) {
var request = $.ajax({
async: false, //It's very important
cache: false,
url: 'thePage.jsp',
type: "GET",
dataType: 'json',
data: {'aparameter': aparameter}
}).responseText;
$.ajax({
url: 'info.jsp',
type: "POST",
cache: false,
data: {'oldValorFromFirstAjaxCall': request},
success: function (info) {
alert(info); //or you can use console.log(info);
$("#someDiv").html(info);
}
});
}
In this way I'm using.
"type": "post" instead of type: 'post'
Maybe it will help. Try it please. For Example;
$.ajax({
url: "yourURL",
type: 'GET',
data: form_data,
success: function (data) {
...
}
});
I have a javascript Object called Company, which may be instantiated multiple times.
I want each Company to handle its own communication with the server, so that its ajax calls will be contained within the class.
So far I have:
Company = new Object();
Company.SendData = function(){
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: this.ReceiveData,
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
The Ajax works fine, and the server correctly receives the data and returns the response, but the call back function does not trigger.
My guess would be because it no longer has any frame of reference to what "this" is.
Is there a way that I can keep the functions attached to an individual instance of the class?
There are several different choices for how to solve this issue. The crux of the problem is that you need to get the value of this set properly when your callback is called as it won't be correct by default.
In modern browsers, you can use the broadly useful .bind():
Company = new Object();
Company.SendData = function(){
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: this.ReceiveData.bind(this),
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
Or, you can instruct jQuery to do the work for you with the context option to $.ajax():
Company = new Object();
Company.SendData = function(){
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
context: this,
success: this.ReceiveData,
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
Or you can create your own stub function using a saved value of this (this is my least favorite option):
Company = new Object();
Company.SendData = function(){
var self = this;
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: function(result) {return self.ReceiveData(result);},
error: ErrorFunc
});
}
Company.ReceiveData = function(data){
alert("Received some data");
}
Try this:
Company.SendData = function(){
var self = this;
$.ajax({
type: "POST",
url: "<some url>",
data: <some data>,
dataType: "json",
success: function(res) {self.ReceiveData(res);},
error: ErrorFunc
});
}
This SO post might help to understand.
Update
Fixed the example by encapsulating the function.
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()+'¶m1='+value1+'¶m2='+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);
}
});