Jquery ajax call wrong payload - javascript

I have some troubles whit jquery ajax call, infact I tried to perform a post call passing like data a string variable:
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: myVar,
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
If I inspect the http call I can see that the payload is:
'Hello': ""
I don't know how it is possible and how fix the problem.

jQuery, by default, will put a Content-Type: application/x-www-form-urlencoded header on data it sends via Ajax.
You, however, are passing a plain text string.
You need to either change the Content-Type to match the data you are sending or the data you are sending to match the Content-Type. (Or you could change both).
The important things are:
The data and content-type need to match
The server needs to be able to handle data in the format you are sending
So you might:
$.ajax({
type: 'POST',
url : 'https://...',
data: myVar,
contentType: 'text/plain'
// ...
})
or, since jQuery will encode objects as URL encoded data:
$.ajax({
type: 'POST',
url : 'https://...',
data: { myVar },
// ...
})
or, if you want multipart data:
const data = new FormData();
data.append('myVar', myVar);
$.ajax({
type: 'POST',
url : 'https://...',
data,
contentType: false // XHR will read the content-type from the FormData object (which it needs to do in order to determine the boundary paramater), putting 'false' here stops jQuery overriding it
// ...
})
or, for JSON
$.ajax({
type: 'POST',
url : 'https://...',
data: JSON.stringify(myVar), // This will be a JSON text representing a string
contentType: 'application/json'
// ...
})

i think you are passing payload in the wrong formate.
myVar = 'Hello';
$.ajax(
type: 'POST',
url : 'https://...',
data: {
'name':myVar
},
success : function(data) {
},
complite: function() {...},
error: function(err) {...}
)
On the server side you will get the value in the key 'name' you can fetch the value using 'name' key.

Related

Request payload is [Object Object] in the AJAX post request triggered

I am sending a ajax request with the following data. The data here is an object and I intend to send an object itself (not stringified JSON). But when I see the request in browser, the request payload is displayed as [object object] even though I am sending a project JS object.
let emailIdForAPICall = { "email": "abc#gmail.com"};
$.ajax({
type: 'POST',
url: gigyaServlet,
data: {
'profile': emailIdForAPICall,
}
})
Once the above API call is triggered, the payload looks like below -
Tried using JSON.parse(JSON.stringify(emailIdForAPICall)) but it still did not work.
Whats worrying is, same type of request works a different site properly.
let emailIdForAPICall = {
"email": "abc#gmail.com"
};
$.ajax({
type: 'POST',
url: gigyaServlet,
data: JSON.stringify({ //stringify your obj
'profile': emailIdForAPICall,
}),
contentType: 'application/json', // add contentType
})
Ramya Shivu your request is from data or JSON. if JSON then please pass contentType: 'application/json',in header & if it is form data
let emailIdForAPICall = { "email": "abc#gmail.com"};
$.ajax({
type: 'POST',
url: gigyaServlet,
data: JSON.stringify({ //stringify your obj
'profile': emailIdForAPICall,
})
})

Send ajax request with multiple types of data

I am working on a application where user can set values via an interface and send ajax request (similar to as rest api).
I would like to know how to send data belong to multiple types in a single request. Example is given below,
Form Data
var data = {'key1':'Key1Value','key2':'Key2Value'};
//content-type : application/x-www-form-urlencoded
Raw Data
var data = 'This is plain text raw value';
//content-type : text/plain
How should I combine above values to send the ajax request below,
$.ajax({
type: "POST",
url: "ajax/activity.php",
data: {combined data},
timeout: 3000,
async: true,
success: APIClient.baseSuccess,
error: APIClient.baseError
});
Maybe send json object with those two as parameters?
$.ajax({
type: "POST",
url: "ajax/activity.php",
data: {
first: data_object,
second: data_string
},
timeout: 3000,
async: true,
success: APIClient.baseSuccess,
error: APIClient.baseError
});
Try like this..
var data = {'key1':'Key1Value','key2':'Key2Value'};
var text= 'This is plain text raw value';
data.text = text; //adds text to data object
Then
In ajax
data: data,
Use the $.extend() function.
var dataText = 'This is plain text raw value';
$.ajax({
type: "POST",
url: "ajax/activity.php",
data: $.extend({
key1:'Key1Value',key2:'Key2Value'
}, dataText),
timeout: 3000,
async: true,
success: APIClient.baseSuccess,
error: APIClient.baseError
});
You could use JSON to send all your various types of data:
{
"data": {
"arrayOfValues": {
"key1": "Key1Value",
"key2": "Key2Value"
},
"someString": "This is some tring value that I want to send"
}
}
Assign this object to a variable and send it in your AJAX call. Of course you need to factor in what/how this data will be received server side.

JQuery, Ajax and PHP : Sending FormData AND String values

I'd like to send to a PHP page a FormData value and some String values.
Here's my code on the JS side:
$.ajax({
url: 'upload-pic.php',
type: 'post',
data: {
type : type,
id : id,
formData : formData
},
processData:false,
success: function(data, status) {
//stuff i'm doing with the data
}
});
And on the PHP side :
if(isset($_POST['type']) && isset($_POST['id'])){
//stuff i'm doing
}
Then, I get an error saying that type and id are not set. I'm guessing that this comes from the processData: false from my ajax call.
But without this, I get the inevitable Illegal Invocation, coming from trying to send the FormData.
Is there any way to send the FormData AND my String values on the same call ?
Thanks!
I assume you are using the FormData object, in that case you need to append the string values to the FormData object, and pass the object in as the data parameter in jQuery's $.ajax.
You can append data to the FormData object, with the method append.
This should work:
formData.append('type', type);
fromData.append('id', id);
$.ajax({
url: 'upload-pic.php',
type: 'post',
data: formData,
processData:false,
contentType: false,
success: function(data, status) {
//stuff i'm doing with the data
}
});

Trouble Accessing Ajax POST variable on Codeigniter end

I'm using jquery to make ajax calls. Basically I don't know how to access the data I'm sending to the server with a post request. I don't know what the variable is called or... something. I don't know!
Ajax functions:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = JSON.stringify({
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
});
return ajax_client(base_url+'ajax_port/gather_records', json);
}
Codeigniter Function:
public function gather_records()
{
$data = json_decode($this->input->post('ids'));
log_message('debug', $data);//null
return json_encode($data);//null :(
}
I'm having no trouble receiving data back from the server here (and accessing with jQuery), my problem is that I can't get the data I'm sending to codeigniter. I'm developing on MAMP if that makes any difference.
I've tried other variable names like,
$this->input->post('data');
$this->input->post('json');
None seem to work.
Thanks very much for any help I can get!
You don't need to do JSON.stringify({..
just pass an object, and everything will be fine. I mean:
function ajax_client(url, json) {
return $.ajax({
url: url,
type: 'POST',
data: json,
dataType: 'json'
});
}
function gather_records(data, inp_col, fetch_col, limit) {
var json = {
"ids" : data,
"inp_col" : inp_col,
"fetch_col" : fetch_col,
"limit" : limit
};
return ajax_client(base_url+'ajax_port/gather_records', json);
}
One more thing. You don't need to json_decode it in your PHP side. Because default contentType in jQuery is 'application/x-www-form-urlencoded; charset=UTF-8'
Change line
$data = json_decode($this->input->post('ids'));
to
$data = $this->input->post('ids');
But if you really want to send JSON, you can add contentType
return $.ajax({
url: url,
type: 'POST',
data: json,
contentType: 'application/json',
dataType: 'json'
});
dataType you have set is "The type of data that you're expecting back from the server." (http://api.jquery.com/jquery.ajax/)

dataType 'application/json' vs. 'json' [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
$.ajax - dataType
I am using jQuery 1.8.2, and for some reason 'application/json' does not work, but 'json' works as dataType to a standard jquery ajax call. Is this a glitch? A version related difference? or is there an established difference between the two?
$(document).ready(function() {
$.ajax({
type : "POST",
url : '<c:url value="/url.htm" >',
//dataType : "application/json", <-- does not work
dataType: 'json' // <-- works
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
});
dataType takes json, it means the request expects a json response.
contentType takes application/json, it means the request is sending json data
You can send as well as expect json in a request e.g.
$.ajax({
type : "POST",
url : url,
contentType : "application/json",
dataType: 'json',
data: JSON.stringify({some: 'data'}),
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
here you're sending json and expecting xml
$.ajax({
type : "POST",
url : url,
contentType : "application/json",
dataType: 'xml',
data: JSON.stringify({xmlfile: 'file.xml'}),
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
and here you're sending x-www-form-urlencoded(jQuery automatically sets this for you), and expect json back
$.ajax({
type : "POST",
url : url,
dataType: 'json',
data: {id: '1'},
success : function(data) {
// do something
},
error : function(data) {
// do something else
}
});
contentType sets the ContentType HTTP request header, telling the server that the body of this request is of the given type.
dataType sets the Accept header to tell the server that this is the type of response we want e.g.
Accept:application/json, text/javascript, */*; q=0.01
but regardless of what type of response the server sends jQuery will still attempt to parse it as whatever type you set in the dataType field.
"application/json" is the correct mime type for json. The jquery dataType field, however, is expecting one of the following strings:
"xml"
"html"
"script"
"json"
"jsonp"
Per the json documentation, the correct dataType is "json".
http://api.jquery.com/jQuery.ajax/
Here are the options supported:
xml
html
script
json
jsonp
text

Categories

Resources