jQuery set cookies to post method - javascript

How is it possible to set cookie to post method in jQuery ajax method?
My code is:
$.ajax({
type: "POST",
url: "https://myUrl",
data: "data",
contentType: "application/x-www-form-urlencoded",
});
I want to put there cookies but not from current session, just as String (I get it from another website), tried to add something like:
cookie: "myCookies",
but it doesn't work.
How can I solve this issue?

You cannot set the custom cookie on cross-domain requests,
try to use this code. it sets the own domain's cookies:
$.ajax({
type: "POST",
url: "URL",
data: "data",
xhrFields: {
withCredentials: true
},
contentType: "application/x-www-form-urlencoded"
});

Why You want that cookie?
You could either use sessionStorage or localStorage if you just wanna track the data in the current session.

Related

Custom headers are not sent with my AJAX requests

I am trying to make an AJAX request from my client to my NodeJS/ExpressJS backend.
However, when the request is fired, my backend receive it well but doesn't recognize the custom headers . e.g.
$.ajax({
type: "POST",
url: "/foo",
headers: {"authorization": "Bearer 12345"},
data: formData,
dataType: "json",
encode: true,
})
in Node , when I do req.headers['authorization'] I get undefined.
I don't understand what I did wrong.
Any advice ?
I'm not sure whether the request you're making is cross-url or not, but if it is try the following:
$.ajax({
url: "yoururl",
type: "GET",
dataType: 'json',
xhrFields: {
withCredentials: true // edited
},
//...
});
I ran into the same error a few times before and it was due to me not adding this important attribute to the request - when authentication is required.

Javascript POST to API

So I am a bit lost and hoping you can help me out. I am writing an app in simple PHP/HTML/Javascript app.
My Goal: To POST json data to an API.
How can I go about this? I just can't find any good examples to show me the best way to handle this.
In my request I need to send Basic Authorization as well as the json values.
This is what I have right now
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
success: function (){
alert('Comment Submitted');
}
});
I can't get the above code to work. Im using a button to call a function that will start the ajax call but nothing is happening.
Any help be be amazing! Thank You.
Use
contentType:"application/json"
You need to use JSON.stringify method to convert it to JSON format when you send it,
And the model binding will bind the json data to your class object.
The below code will work fine (tested)
$(function () {
var customer = {contact_name :"Scott",company_name:"HP"};
$.ajax({
type: "POST",
data :JSON.stringify(customer),
url: "api/Customer",
contentType: "application/json"
});
});
If you're writing the API in PHP, and it uses $_POST to get the parameters, you shouldn't send JSON. PHP only knows how to decode multipart/form-data and application/x-www-form-urlencode. If you pass an object to $.ajax, jQuery will use the urlencode format.
Just take the quotes off the object that you're passing to the data: option.
$.ajax({
type: "POST",
url: "host.com/api/comments",
dataType: 'json',
async: false,
headers: {
"Authorization": "Basic xxxxxxxxxxxxxxxxxxxxxxx"
},
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
success: function (){
alert('Comment Submitted');
}
});
You also shouldn't use async: false, it is deprecated. Learn to write proper async code.
Nobody seems to have addressed one issue - the URL
If the page this is requested from is http://yourhost.com/path/file.html the request will be sent as http://yourhost.com/path/host.com/api/comments
As you have host.com in the URL, I assumed the request is to a different domain?
use one of
http://host.com/api/comments
https://host.com/api/comments
//host.com/api/comments
will only work if your page is loaded http and not https
will work only if the remote API supports https
will only always work properly if the remote API supports both http and https
The other issue is regarding the format of the sent data
The default content-type for $.ajax POST is application/x-www-form-urlencoded; charset=UTF-8
So, sending a POST request with various combinations of contentType and data shows the following
Firstly, without setting contentType
data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
request is sent as formData '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
request is sent as formdata, the following values:
value1: 2.0
value2: setPowerState
value3[state]: 0
looks better, because there's actually multiple values, not just a string
Now, let's set contentType
contentType: 'json', data: {"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}},
firefox does not tell me the format of the following string: 'value1=2.0&value2=setPowerState&value3%5Bstate%5D=0' - looks useless
And finally
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
sends the following JSON: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}'
So, finally, if the API requires JSON request data, and it's actually on a domain called "host.com"
$.ajax({
type: "POST",
url: "//host.com/api/comments",
dataType: 'json',
contentType: 'json', data: '{"value1":"2.0", "value2":"setPowerState", "value3":{"state":0}}',
});

Access POST string from PHP

I use JQuery.ajax to send a JavaScript object to a PHP script per POST. JQuery sends it in a way that makes it easily accessable from PHP:
JavaScript:
var request = $.ajax({
url: server,
dataType: 'text',
timeout: timeout,
type: 'POST',
data: {key:"value"}
});
PHP:
$_POST["key"]
When I send a simple string with $.ajax instead of a JS object, how can I access it in PHP? E.g. when simply sending "data", count($_POST) returns 0.
var request = $.ajax({
url: server,
dataType: 'text',
timeout: timeout,
type: 'POST',
contentType: "text/plain",
data: "data"
});
Do I have to use file_get_contents('php://input') or is there another way?
When I send a simple string with $.ajax instead of a JS object, how can I access it in PHP?
Do I have to use file_get_contents('php://input')
Yes. If you don't encode the data in a format that PHP can decode automatically, then you have to access the raw data like that.
Remember to set the content-type of the request to text/plain when you do that.
Your data should be valid, a string on its own isn't valid. Instead try:
var request = $.ajax({
url: server,
dataType: 'text',
timeout: timeout,
type: 'POST',
contentType: "text/plain",
data: {data: "mysimplestring"}
});
and access it with
$_POST['data'];

Ajax URL POST accept Localhost and IP

Im doing an ajax post but I have a problem.
I want to post to an url but I want to accept in the explorer, "localhost" and the "IP address".
If I put like this:
$.ajax({
url: 'http://192.168.9.30/test/suma.php',
type: 'post',
data: {rows:rowValues, columns:columnValues},
dataType: 'json',
success: function(data){
var rows = data.rows,
columns = data.columns;
// Insertar lo calculado
$("td.total").each(function(rowIndex){
$(this).text(rows[rowIndex+1]);
});
$("tr.totalCol td").each(function(columnIndex){
$(this).text(columns[columnIndex+1]);
});
}
});
Only accept me typing the url, its possible to do it with the url and localhost too?
Thank You in advance!
Just remove the whole domain part, only use the relative path:
$.ajax({
url: '/test/suma.php',
type: 'post',
// other stuff
});
I you are working in the same domain, use relative path.
If not, you need enable 'crossDomain' option.

Setting the POST-body to a JSON object with jQuery

I'm trying to write a JSON-based web API in a Sinatra app. I want to POST a JSON object as the post body (with the proper content-type set) but I'm struggling.
In Cocoa, I'd do something like
[mutableHTTPRequest setHTTPBody:dataRepresentationOfJSONObject];
And the content type, set to JSON, would then post the HTTP body as a JSON object. I'm trying to do this with jquery. The best I can do so far just takes the JSON object and turns it into a normal style key=value&… style post body, and that's not what I'm after.
My Javascript:
var data = { "user" : "me!" };
$.ajax({
type: "POST",
url: "/api/user/create",
contentType: 'application/json',
data: data,
success: function(r) {
});
Any pointers on how to do this? My goal is for my Sinatra to do like the following
post "/api/user/create" do
js = JSON.parse(request.body.read)
# do something with the js object… this works when POSTing from Cocoa
end
Add the processData parameter to your ajax request and set it to false. Additionally, you need to stringify your object to turn it into JSON.
var data = { "user" : "me!" };
$.ajax({
type: "POST",
url: "/api/user/create",
processData: false,
contentType: 'application/json',
data: JSON.stringify(data),
success: function(r) {
}
});
JSON.stringify will not work in older versions of IE unless you implement it. http://json.org

Categories