I'm learning how to make AJAX calls with JQuery and one thing I was wondering if it's possible to do is include some data as URL parameters and other data in the post body. For example, I'd like to do something like this:
$.ajax({
url: '/myURL',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
but in addition to the JSON data which is being sent in the POST request body, I'd like to include URL parameters. Is there a way to do this?
You would be able to include the variables in the url portion of your code. For example
var example1 = "some_information";
$.ajax({
url: '/myURL',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
would become
var example1 = "some_information";
$.ajax({
url: '/myURL?var1=example1',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
You may need to put quotes around the example1 variable to ensure it doesn't break when there are spaces in the url.
You can send parameters normally in the URL as in the get request
either using ? and &
$.ajax({
url: '/myURL?data2=' + data2 + '&data3=' + data3,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
or by set them between /
$.ajax({
url: '/myURL/' + data2 + '/' + data3,
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8'
})
The way of including the parameters on the URL will depends of the way you receive/parse them on the server side, however this is not considered as good practice for the post request.
Related
I have python api which can get the multiple data in same query such as.
createdata?ob=120&st=cool&st=warm
It can get st as ["cool","warm"] in python.
st = request.query_params.getlist("st")
print(st) #["cool","warm"] get the data as array.
Now I want to do the same thing from ajax
I try this
$.ajax({
type: "POST",
url: "defapp/createdata",
method: "GET",
data: {"ob":130,"st":"warm","st":"cool"},
contentType: "application/json",
and this.
$.ajax({
type: "POST",
url: "defapp/createdata",
method: "GET",
data: {"ob":130,"st":["warm","cool"]},
contentType: "application/json",
However former one get ["cool"] as st
later one get [] as st.
It's don't work,because you api not recive a data body,but it recive a params value.
You can changed to these below.
$.ajax({
type: "POST",
url: "defapp/createdata?ob=120&st=cool&st=warm",
method: "GET",
data: {},
contentType: "application/json",
I hope is can work in your case.
I tried to find information in google, but no results there. I want send to server array with keys ('data':'unknown','datakey':'status') and file.
I tried this one, but settings contentType:false and processData:false removing keys:
$('#null').on('click', function(efile) {
var inFile = new FormData();
inFile.append('outFile', efile.target.files[0]);
});
$.ajax({
cache:false,
contentType:false,
processData:false,
url:'fileservice.php',
data:{'data':'unknown','datakey':'status', inFile},
type:"POST",
success: function(eresponse) {
alert(eresponse);
}
});
"contentType" is type of data you sending such as 'application/json; charset=utf-8'
Default is: "application/x-www-form-urlencoded"
Try below code
$.ajax({
url:'fileservice.php',
cache:false,
contentType: "application/json; charset=utf-8",
data : JSON.stringify({'data':'unknown','datakey':'status', inFile}),
processData:false,
type:"POST",
success: function(eresponse) {
alert(eresponse);
}
});
Let me know if still not solved you problem.
I was making a POST request in the following manner, using URL params (which worked):
var PAYLOAD = `
<myxmlcontent>
<attribute name="id">1</attribute>
<attribute name="FullName">Joe Bloggs</attribute>
</myxmlcontent>
`
var URL = 'http://www.somewhere.com/integration?apiKey=company&apiToken=123&payload=' + PAYLOAD;
client.request({
url: URL,
type: 'POST',
contentType: 'application/xml'
}).then(
function(data) {
console.log(data);
}
);
But I wish to put the payload data into the request body.
Is this the correct way to do it? I am not sure, but my attempt has proved unsuccessful so far:
var PAYLOAD = `
<myxmlcontent>
<attribute name="id">1</attribute>
<attribute name="FullName">Joe Bloggs</attribute>
</myxmlcontent>
`
client.request({
url: 'http://www.somewhere.com/integration',
type: 'POST',
contentType: 'application/xml',
headers: {
apiKey: 'company',
apiToken: '123'
},
dataType: 'xml',
data: 'data=' + JSON.stringify(PAYLOAD)
}).then(
function(data) {
console.log(data);
}
);
I am currently building a client-side Zendesk app.
First you have to make sure the endpoint accepts data via POST, otherwise it will fail even if you are seding your data correctly, secondly, if you want to send data as an url-encoded form, you need to change the contentType to application/x-www-form-urlencoded and send the body as either an url-encoded string or by using the FormData object (if it's available in your framework), e.g.:
var myData = new FormData();
myData.append("payload", encodeURI(PAYLOAD));
client.request({
url: 'http://www.somewhere.com/integration',
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
headers: {
apiKey: 'company',
apiToken: '123'
},
dataType: 'xml',
data: myData
}).then(
function(data) {
console.log(data);
}
);
Don't forget to also encode the content of payload. In case your endpoint only accepts xml-encoded strings then you'd have to send the string as-is, just make sure to specify the correct contentType, in which case would be application/xml or text/xml.
SOLVED. This is what I had to do (thank you):
var PAYLOAD = `
<myxmlcontent>
<attribute name="id">1</attribute>
<attribute name="FullName">Joe Bloggs</attribute>
</myxmlcontent>
`
var URL = 'http://www.somewhere.com/integration';
client.request({
url: URL,
type: 'POST',
contentType: 'application/x-www-form-urlencoded',
dataType: 'xml',
data: {
apiKey: 'company',
apiToken: '123',
payload: PAYLOAD
}
}).then(
function(data) {
console.log(data);
}
);
Helpful article: How are parameters sent in an HTTP POST request?
I am trying to convert old javascript ajax call to angular by using $http method in Angular.
My old one is like
var payload ={'id':'id-abc'}
$.ajax({
type: 'post',
url: 'myurl/com',
dataType: 'json',
data: payload,
success: function (returndata) {
//parse returndata
});
});
in Angular way,
$http({
method: 'post',
url: ‘myurl/com’,
dataType: 'json',
data: payload
}).then(function(returndata) {
console.log(returndata);
})
The angular way gave me
Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response. Issue.
If I mimic the old way and setup the content-type header like
$http({
method: 'post',
url: ‘myurl/com’,
dataType: 'json',
data: payload,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}).then(function(returndata) {
console.log(returndata);
})
The server response is saying I am missing a params (it doesn’t).
I don’t have the control on the server side so I am not sure how to covert the old $ajax request to the new Angular one. Any ideas? Thanks a lot!
$http default is to serialze data as json
To send form encoded you need to use $httpParamSerializerJQLike which also needs to be injected wherever you use it
$http({
url: myUrl,
method: 'POST',
data: $httpParamSerializerJQLike(myData),
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
});
You could also set up global defaults for the header and a $httpInterceptor to do this transform instead of putting in each individual request
I try to understand one thing.
I want to post an object with jquery Ajax POST , something like this:
var dataPostYear = {
viewType:GetViewType(),
viewDate:'2009/09/08',
languageId:GetLanguageId()
};
$.ajax({
type: "POST",
url: url,
data: dataPostYear,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnLoadYearListSuccess,
error: OnLoadYearListError
});
and it doesn't work.
But this one works fine:
var dataPostYear = "{viewType:'"+ GetViewType() + "',viewDate:'2009/09/08',languageId:'"+GetLanguageId()+"}";
$.ajax({
type: "POST",
url: url,
data: dataPostYear,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnLoadYearListSuccess,
error: OnLoadYearListError
});
GetViewType() return --'0'
languageId() return --'1'
it's just a string
there is a way to post an object, something what I try to do in my first way ? Or not ?
Thanks
Use jQuery.param(). Here is the documentation
You should look at .postJSON.
Essentially, you just add json as a 4th argument to the $.post
From the site:
// Send the request
$.post('script.php', data, function(response) {
// Do something with the request
}, 'json');
If you want the .ajax call version, you can convert it using the .post docs.