What is the use of beforeSend Function in jQuery Ajax?
How to use the jQuery function?
I am Using jQuery 1.6.0, and Using Jersey API (Restful Web services) on Server Side.
$.ajax({
type: "GET",
url:ajax_url,
dataType: "json",
contentType: "application/json",
async: false,
beforeSend: function (xhr){
xhr.setRequestHeader('Authorization', "Basic "+ btoa(username + ':' + password));
},
success:function(data){
alert(data.groups);
},
error:function(xhr,err){
console.log("readyState:"+xhr.readyState+"\nstatus: "+xhr.status)
alert(xhr.responseText)
alert("Service is not Available , Try it after Some time");
}
});
Java Code :
#GET
#Produces(MediaType.APPLICATION_JSON)
public String authCheck(){
return "({"groups": "success"})";
}
Whenever I am sending for authentication I am getting success response.
How to use beforeSend function and does we need to do any thing on server side?
Generally beforeSend() is used to do some stuff before actually send AJAX request like set Custom header and etc...
but your need is different that you want to authenticate user before your ajax call than
create one another function which give you User is authenticated or Not in Response
suppose this function is checkAuth();
so use
type: "GET",
url:ajax_url,
dataType: "json",
contentType: "application/json",
async: false,
beforeSend:checkAuth,
.
.
.
Related
I have this function to perform a POST request to a SharePoint Online site collection:-
function SetListColumnReadOnly() {
$.ajax
({
// _spPageContextInfo.webAbsoluteUrl - will give absolute URL of the site where you are running the code.
// You can replace this with other site URL where you want to apply the function
url: "https://****.sharepoint.com/_api/web/lists/getByTitle('tickets')/fields/getbytitle('defineFields')",
method: "POST",
data: JSON.stringify({
'__metadata': {
// Type that you are modifying.
'type': 'SP.FieldText'
},
'ReadOnlyField': true
}),
headers:
{
// IF-MATCH header: Provides a way to verify that the object being changed has not been changed since it was last retrieved.
// "IF-MATCH":"*", will overwrite any modification in the object, since it was last retrieved.
"IF-MATCH": "*",
"X-HTTP-Method": "PATCH",
// Accept header: Specifies the format for response data from the server.
"Accept": "application/json;odata=verbose",
//Content-Type header: Specifies the format of the data that the client is sending to the server
"Content-Type": "application/json;odata=verbose",
// X-RequestDigest header: When you send a POST request, it must include the form digest value in X-RequestDigest header
//"X-RequestDigest": $("#__REQUESTDIGEST").val()
},
success: function (data, status, xhr) {
console.log("Success");
},
error: function (xhr, status, error) {
console.log("Failed");
}
});}
Now how we can run this POST inside the FireFox's RESTClient addin or anyother tool using the browser credentials?
when i tried this >> i got forbidden error:-
Also with those headers:-
I am having trouble accessing params in Sinatra after submitting a form. This is my form:
function submitForm(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/mix_addresses',
//grab the inputs from address_section
//data: $('.add_address_section .add_address_field').map(function() { return $(this).val() }),
data: [1,2,3],
dataType: "json",
success: function(data) {
debugger;
}
});
}
And this is my endpoint:
require 'sinatra'
require 'jobcoin_client'
get '/' do
erb :add_coins
end
post '/mix_addresses' do
puts params
end
I'm getting to the endpoint, but the params are blank. Shouldn't it be [1,2,3]? Instead, it's:
{"undefined"=>""}
Anyone see what I'm doing wrong?
Several issues here :)
Sinatra configuration
Main problem is coming from the fact that Sinatra doesn't deal with JSON payloads by default. If you want to send a JSON payload, then the easiest solution will be :
To add rack-contrib to your Gemfile,
Then, require it in your sinatra app: require rack/contrib
And load the middleware that deals with this issue: use Rack::PostBodyContentTypeParser
And you should be good to go!
Source: several SO post reference this issue, here, here or here for instance.
jQuery ajax call
Also, note that there might be some issues with your request :
You'll need to use a key: value format for your JSON payload: { values: [1,2,3] }
You'll need to stringify your JSON payload before sending it: data: JSON.stringify( ... )
You'll need to set the request content type to application/json (dataType is related to the data returned by the server, and doesn't say anything about your request format, see jQuery ajax documentation for more details).
Eventually, you should end up with something like this on the client side:
function submitForm(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/mix_addresses',
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify({ values: [1,2,3] }),
success: function(data) {
debugger;
}
});
}
I'm trying to convert a REST call using Cordova plugin to a JQuery AJAX POST. I don't have the JQuery code right, the call is getting a connection refused error (hitting localhost). I'm successfully making GET requests to my localhost, so there isn't a connectivity issue.
The REST API code:
#Path("/track")
public class TrackResource {
...
The method in TrackResource class i'm trying to hit :
#POST
#Path("{trackid}")
#Consumes("application/json")
#Produces("application/json")
public Response addToResource(#PathParam("trackid") String trackid, String bodyJson) {
The AJAX code:
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I'm not sure if i'm using the data option in the ajax call correctly, but it's my understanding that is where you would put the data you want to pass server side.
I do have other GET calls to this same TrackResource class working, so i know the base part of the URL is correct. I know the trackid value is populated correctly as well.
If you're posting a JSON string make sure you also set contentType: "application/json".
var trackingJSON = JSON.stringify(tracking_data);
var urlAjax = "http://localhost:7001/ds/resources/track/" + trackid;
$.ajax({
type: "POST",
url: urlAjax,
contentType: "application/json",
data: trackingJSON,
beforeSend: function() { $.mobile.showPageLoadingMsg("b", "Loading...", true) },
complete: function() { $.mobile.hidePageLoadingMsg() },
success: function(data) { alert("ajax worked"); },
error: function(data) {alert("ajax error"); },
dataType: 'json'
});
I needed to use the router address of my computer, 192...., in order to hit my localhost... I was running the application on an actual Android device, however, I guess trying to use localhost or 127.0.0.1 in the AJAX call must have been causing issues.
I am trying to call a URL through XHR.post on the DOJO 1.8. I need catch the STATUS property and getHeader() from promise response, but the problem is, when I call my URL with POST I don't have any promise, and when I call with GET I have all properties that I need, but I only can send the request as POST.
The most strange is that I have another code in AngularJS which works well, this code does the same thing. I am testing DOJO and AngularJS.
I need catch the STATUS information to check if it is 201(created), if true I need catch getHeader('location') and call the URL that I picked up from getHeader('location').
Look at my method in Dojo 1.8:
checkCreation: function(typeFile, id){
var promise = xhr('/rest/list/one', {
handleAs: 'json',
method: 'post',
accepts: 'application/json',
headers: {
Accept: 'application/json',
id: id,
type: typeFile
}
});
promise.response.then(function(response) {
console.log("status", response.status);
console.log("options", response.options);
console.log("url", response.url);
console.log("timestamp", response.options.timestamp);
console.log(response);
});
},
I discovered the problem, I commented the lines followings and now works fine.
//handleAs: 'json',
//accepts: 'application/json',
The handleAs you need to use only when you have a JSON response. About "accepts" I haven't found what difference between "accept" and "Accept"(inside headers) yet.
Now I can take my informations:
console.log('location: ', response.getHeader('location'));
console.log("status: ", response.status);
As of 10.04.2012,
There is a short paragraph in the Facebook developer document for 'batch request' entitled: Batch calls with JSONP, which reads:
"The Batch API supports JSONP, just like the rest of the Graph API -
the JSONP callback function is specified using the 'callback' query string
or form post parameter."
I thought that meant you can also do a batch request using JSONP from Javascript (which will be a GET request, as JSONP works only as a GET request), so I tried that, with adding a 'batch' parameter (containing objects describing requests for batch as in the doc) to the query string. Response from FB server was:
Only POST is allowed for batch requests
So, questions:
1. What did they mean in that paragraph?
2. Is there a way to do an asynchronous batch request from Javascript?
I get the same. Sample code is
jQuery.support.cors = true;
var AjaxRequest = jQuery.ajax( {
url: "http://graph.facebook.com/",
type: "POST",
contentType: "application/x-www-form-urlencoded",
data: { "access_token": AccessToken, "batch": BatchRequest },
dataType: "jsonp",
error: function( jqXHR, textStatus, errorThrown ) {
... show error stuff
},
success: function( Return, textStatus, jqXHR ) {
showLog( "Return " + JSON.stringify( Return ) );
showLog( "textStatus " + textStatus );
showLog( "jqXHR " + JSON.stringify( jqXHR ) );
if ( Return.error ) {
... go away
}
else {
... use the data
}
}
} ); // eo ajax request
which gives
Return {"error":3,"error_description":"Only POST is allowed for batch requests"}
textStatus success
jqXHR {"readyState":4,"status":200,"statusText":"success"}
i.e. it successfully sends back an error message. JSONP translates the POST type to a GET, which Facebook doesn't support...
To answer qu.2 you can use FB.api to do asynchronous batch request in javascript. I was trying out JSONP because IE8 keeps hanging on the return from Facebook with FB.api.