I've been stuck from this issue in couple of days. I want to send some headers data in jQuery.load(). It seems that jQuery.load never send the headers, like ajax. Can somebody explain how to, or Is it necessary? Btw, sory my bad English.
This is the syntax :
$loadingBay.load(href, settings.data, function (data, status) {
prep(status === 'error' ? $tag(div, 'Error').html(settings.xhrError) : $(this).contents());
});
Many Thanks
You can not pass headers data to $.load() , but you can set default setup using $.ajaxSetup() like this :
$.ajaxSetup({
'headers':{
'header1':'value1',
'header2':'value2',
}
}
);
//give the load call here
$('selector').load('url',function(){
//do things
})
Disclaimer From jquery doc:
Its use is not recommended.
The best way is do the is thing using $.ajax() :
$.ajax({
url: "test.html",
headers : {header1 : "header1"}
}).done(function(data) {
$('selector').html(data);
});
You can use beforeSend option in jquery ajax , like as follows :
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
beforeSend: function(xhr){xhr.setRequestHeader('X-TOKEN', 'xxxxx');},
success: function() { alert('Success!' + authHeader); }
});
or can also use headers like,
$.ajax({
url: "http://localhost/restTest",
data: { uname: "asdf" },
type: "GET",
headers:{ "X-TOKEN": 'xxxxx'},
success: function() { alert('Success!' + authHeader); }
});
Related
Hi I am currently learning php and I am trying to get data from php file using the below script but i am not getting any response
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " ); // not triggering
}
});
my php return stmt
There might be problems with File URL or file access. You can use complete callback to check request for errors like that:
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert("Response : " );
},
// This method will be fired when request completes
complete: function(xxhr, status) {
alert("Status code: " + status);
}
});
If the status code is not success that means there is something wrong with your request.
You can check more callback options here.
It doesn't matter whether you use return or echo in your PHP file.
The success method must get a call if it's fine. However, if you use
return instead of echo, nothing will append to your request's data.
On the other hand, The PHP response will include in your 'data' variable in the function success.
You need use data in the assync function success
success: function(data) {
alert("Response : " + data);
},
Thanks for your Responses. I got the Solution to my problem. It seems since Ajax is asynchronous... its taking time to receive the resultant echo value from my php file. so I had to synchronize my Jquery using async : False.
$(function(){
$('#formID').on('submit',function(){
const data_set={
name:"Nipu chakraborty",
"phone":"01783837xxx"
}
$.ajax({
type: 'POST',
url: "mark_mod.php",
data: data_set,
dataType: "JSON",
success: function(data) {
alert(data);
}
});
});
});
Within the following jQuery showLoader can be set to show a loading icon while the AJAX request is made.
$.ajax({
url: baseUrl,
data: (paramData && paramData.length > 0 ? paramData + '&ajax=1' : 'ajax=1'),
type: 'get',
dataType: 'json',
cache: true,
showLoader: true,
timeout: 10000
});
I want to know if there is a proper way to customise this to some html that i have set for loading icons to make loading icons uniform across my site.
I can agree with Gopal, but be careful about handling errors. If the request fails, the loader should be hidden and user should be informed. See http://api.jquery.com/jquery.ajax/
The complete callback is better for this purpose, because it will be called anyway.
$.ajax({
type: "GET",
url: ""
beforeSend: function(){
$(".show_load_icon").show();
},
complete: function(){
$(".show_load_icon").hide();
}
});
Or you can handle the error manually.
$.ajax({
type: "GET",
url: ""
beforeSend: function(){
$(".show_load_icon").show();
},
success: function(){
$(".show_load_icon").hide();
},
error: function(){
$(".show_load_icon").hide();
alert("Error"); // inform the user about error
}
});
From jQuery 3.0 you can use .done() and .fail()
For my suggestion there is no option for default ajax
showloader
So you can go better for this way.
$.ajax({
type: "POST",
url: "someURL"
data: "someDataString",
beforeSend: function(msg){
$(".show_load_icon").show();
},
success: function(msg){
$(".show_load_icon").hide();
}
});
I was hoping that someone may be able to give me a pointer on how to achieve the following.
Currently, I have:
A JS function: A jQuery AJAX query that will get items from a SharePoint custom list.
A JS function: it will put the list results in to a datatable.
A JS function, that can turn an InitatorId into the real name of a user (GetDisplayName).
function GetDisplayName(userid) {
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : GetDisplayNameSuccess,
error : GetDisplayNameFail
});
}
function populateMyOutstandingItems() {
SP.SOD.executeFunc("sp.js", "SP.ClientContext", function() {
SP.SOD.executeFunc("sp.runtime.js", "SP.ClientContext", function() {
var context = SP.ClientContext.get_current();
var queryUrl = "https://companyname.sharepoint.com/subsite/_api/Web/Lists/getbytitle('Read%20Requests')/GetItems"; //change the Url
var camlXML = "<Query><Where><And><Eq><FieldRef Name='ReaderId' LookupId='True' /><Value Type='Integer'>" + _spPageContextInfo.userId + "</Value></Eq><Neq><FieldRef Name='Read' /><Value Type='Text'>YES</Value></Neq></And></Where></Query>"
var requestData = { "query" :
{"__metadata":
{ "type": "SP.CamlQuery" }
, "ViewXml": camlXML
}
};
return jQuery.ajax({
url: queryUrl,
type: "POST",
data: JSON.stringify(requestData),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
},
success: onQuerySuccessMyOutstandingItems,
error: onQueryErrorMyOutstandingItems
});
});
});
}
function onQuerySuccessMyOutstandingItems(data) {
var jsonData = data.d.results
console.log(jsonData)
$("#resultsDivMyOutstandingItems").dataTable( {
"data" : jsonData,
columns: [
{ data: "Document_x0020_Name" },
{ data: "Document_x0020_Library_x0020_Nam" },
{ data: "Request_x0020_Made_x0020_Date" },
{ data: "InitatorId" },
{ data: "Request_x0020_ReadBy_x0020_Date" }, ],
order: [[3, "asc"]]
} ); }
At the moment, in the datatable, I have the InitatorID (ie. 30) but I would like to have the real name of the user in the table.
I understand some type of recursive AJAX query will be needed, but I'm not sure what the best way forward would be to achieve this, and was hoping that someone would be able to point me in the right direction.
After reading a bit about chained requests, I tried the code below, but it's wrong I guess, since Chrome complains of an 'unexpected ending':
var request = $.ajax({
url: queryUrl,
type: "POST",
data: JSON.stringify(requestData),
headers: {
"X-RequestDigest": $("#__REQUESTDIGEST").val(),
"Accept": "application/json; odata=verbose",
"Content-Type": "application/json; odata=verbose"
}
}),
chained = request.then(function( data ) {
return $.ajax( spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + data.InitatorId + ")",
{ data: { user: data.Title }} )
});
chained.done(function( data ) {
console.log(data)
});
In short, what is the best to achieve what I'm trying to do?
Many thanks
Glen
I am not sure I completely understand what you're asking, so here's my best guess at the scenario (please correct me if I am wrong)
Make an AJAX call to get a list of items from a SharePoint custom
list, but alas, one of the columns in this list has an InitatorID instead of a user name.
To fix this, we want to make another AJAX call that will get a list of usernames for a matching set of InitatorIDs we just retrieved.
Once we have that, we want to put the data in a dataTable for display.
Without knowing the details, I would just do nested AJAX calls. Basically, once the first call is done, call the second AJAX function. Once that one is done, update the dataTable. Something like:
$.ajax({
url: MY_FIRST_URL,
data: myFirstData
}).done(function (data) {
// The first call gets completed after some time and the 'done' function is called.
// here, extract the various InitatorID values, and pass them to the
// second AJAX call, so you can then get the usernames for those Ids
var initatorIds = // ... do data massaging here to get the initatorIds
// into the format you want from the 'data' variable
// passed in the done function...
$.ajax({
url: MY_SECOND_URL,
data: initatorIds
}).done(function (data2) {
// once the SECOND call is complete, populate the dataTables
var jsonData = // ... some manipulation of data and data2 results
// to get the combined output you want.
$("#resultsDivMyOutstandingItems").dataTable( {
"data" : jsonData,
columns: [
....
....
});
}).fail(function (jqXHR, textStatus) {
// do stuff if the second call fails
});
}).fail(function (jqXHR, textStatus) {
// do stuff if the first call fails
});
And at the risk of over-complicating the solution, I'd personally look to load the data directly into the table via the ajax functionality found within the dataTable plugin (read more about that here). But definitely if it minimizes confusion to lay it out as above, do that first!
I have trouble with a piece of ajax code. This is the error message I get from mod security:
/ajaxController.php?mod=catalog&op=ajaxSeenProducts HTTP/1.1
Access denied with code 400 (phase 2). Operator EQ matched 0 at
REQUEST_HEADERS. [file "/usr/local/apache/conf/modsec2.user.conf"]
[line "12"] [id "960012"] [msg "POST request must have a
Content-Length header"] [severity "WARNING"] [tag
"PROTOCOL_VIOLATION/EVASION"]
There is a module in the web shop I am working on, which shows the last viewed products, and the jquery code I have is this:
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
While searching for the solution, I have found in various places that I need to set the
Content-length
parameter, but all I have found is in this format:
xmlHttp.setRequestHeader("Content-length", params.length);
Is there any way to set the request header in the code format I have provided above? I have already tried something like:
headers: {
"Content-Length": params.length
}
but with no result. Any help would be appreciated.
use code like:
var url = '{HOME}ajaxController.php?';
var data = "mod=catalog&op=ajaxSeenProducts";
$.ajax({
url: url,
data: data,
dataType: "html",
type:'post',
success:function(seenProducts){
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
},
error:function(response){
}
});
you can use the beforeSend function to set the headers
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
or other way you can do it like
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
headers: {"X-Test-Header": "test-value"},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
I'm getting data from a remote server, that can produce JSONP but needs the callback-function name in a non-standard way.
For code structure & simpler error-handling, I'd prefer to use the default function. Is there a way for me to get the autogenerated function name, and give that as a data-parameter?
What I'd like to be able to do is something in the lines of:
$.ajax("http://mydomain.com/xxx",
{
dataType: "jsonp",
type : 'GET',
success : function(response) {
doSomething(response);
},
data: {
format_options : 'callback:' + jQueryAutoGeneratedCallbackFunction,
outputFormat : 'json'
}
}
);
Is this possible?
..So it turns out I thinking it from a wrong angle.
The answer is, that I can change the "callback"-parameter like this.
$.ajax("http://mydomain.com/xxx",
{
dataType: "jsonp",
jsonp: "format_options",
jsonpCallback:"callback:myFunction",
type : "GET",
success : function(response) {
doSomething(response);
},
data: {
foo : "bar"
}
}
);
Just as clarification, the "callback:"-part in "callback:myFunction" is needed just for the API i'm using, I included it here as i'd included it in the question.