I want to know which way is the best way to execute a function when a function with the ajax call has completed.
My code:
jQuery.when(AjaxCallToBokningar()).done(function () {
console.log("AjaxCallComplete");
});
function AjaxCallToBokningar() {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items
var call = jQuery.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
//Done
call.done(function (data, textStatus, jqXHR) {
//Filling globalArray
window.globalBokningsArray = data.d.results;
});
//Fail
call.fail(function (jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
});
}
Am I on the right track or is there a better way?
If you want to be able to make the Ajax call and then call a function when it's complete you can use a function reference as a parameter and do it like this...
function AjaxCallToBokningar(doneCallback) {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items
var call = jQuery.ajax({
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
//Done
call.done(function (data, textStatus, jqXHR) {
//Filling globalArray
window.globalBokningsArray = data.d.results;
doneCallback();
});
//Fail
call.fail(function (jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
});
}
Then you can call it like this...
function ajaxCallComplete1() {
// this is executed after the 1st call is done - do something here
}
function ajaxCallComplete2() {
// this is executed after the 2nd call is done - do something here
}
AjaxCallToBokningar(ajaxCallComplete1);
AjaxCallToBokningar(ajaxCallComplete2);
or...
AjaxCallToBokningar(function() {
// this is executed after the call is done - do something here
});
You can also try something like this: (not tested)
function ajaxCallToBokningar() {
var url = `${_spPageContextInfo.webAbsoluteUrl}/_api/web/lists/getbytitle('Bokningar')/items`;
var options = {
url: url,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
};
return jQuery.ajax(options);
}
function updateBoknigarArray(data) {
window.globalBokningsArray = data.d.results;
}
function showError(jqXHR, textStatus, errorThrown) {
console.log('Loading Bokningar content faild: ' + textStatus + jqXHR.responseText);
}
ajaxCallToBoknigar()
.done(updateBoknigarArray)
.fail(showError)
Related
I want the loader to stay until the complete execution is complete and statement $("#xyzDiv").html(data) has been executed. Currently the loader gets hidden after the first ajax call. Even if i add "beforeSend: function () { $("#loader").show(); }" to GetDataList(), the loader is not staying.
$.ajax
({
type: "POST",
url: ajaxUrl,
data: dataObj,
beforeSend: function () { $("#loader").show(); },
success: function (data)
{
if (data.result)
{
GetDataList();
toastr.success(data.strMsg);
}
else
{
toastr.error(data.strMsg);
}
},
error: function (jqXHR, textStatus)
{
var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
console.log(msg);
toastr.error('An error occurred. Please try again');
},
complete: function () { $("#loader").hide(); }
});
function GetDataList()
{
$.ajax
({
type: "Get",
url: ajaxUrl,
data: dataObj,
success: function (data)
{
$("#xyzDiv").html(data);
},
error: function (jqXHR, textStatus)
{
var msg = HandleAjaxErrorMessage(jqXHR, textStatus);
console.log(msg);
toastr.error('An error occurred. Please try again');
}
});
}
I have two $.ajax() calls in my javascript code.
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'district'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_district = JSON.parse(response);
district = L.geoJSON(json_district, {
onEachFeature: return_district,
});
ctl_layers.addOverlay(district, "district", "Overlays");
ar_district_object_names.sort();
$("#text_district_find_project").autocomplete({
source: ar_district_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: 'province'
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_province = JSON.parse(response);
province = L.geoJSON(json_province, {
onEachFeature: return_province,
});
ctl_layers.addOverlay(province, "province", "Overlays");
ar_province_object_names.sort();
$("#text_province_find_project").autocomplete({
source: ar_province_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
changes on both ajax are as below:
tbl: 'district' -> tbl: 'province'
json_district -> json_province
return_district -> return_province
(district, "district", "Overlays") -> (province, "province", "Overlays")
ar_district_object_names -> ar_province_object_names
$("#text_district_find_project") -> $("#text_province_find_project")
Is there a way I can call this $.ajax() inside a function with one parameter and call the function afterwards. As an example:
function lyr(shpName){
$.ajax({
url: 'http://localhost/webmap201/php/load_data.php',
data: {
tbl: `${shpName}`
},
type: 'POST',
success: function(response) {
console.log(JSON.parse(response));
json_shpName = JSON.parse(response);
shpName = L.geoJSON(json_shpName, {
onEachFeature: return_shpName,
});
ctl_layers.addOverlay(shpName, `${shpName}`, "Overlays");
ar_shpName_object_names.sort();
$("#text_shpName_find_project").autocomplete({
source: ar_shpName_object_names,
});
},
error: function(xhr, status, error) {
alert("Error: " + error);
}
}
);
}
lyr (district);
Can I use template strings? Can I use that a function inside a function. Any help would be highly appriceated.
Create a function for ajax call.
For eg.:-
function serviceajaxjson(_successfun, _failurefun, _url, _data, _async, _global) {
if (_successfun == null) _successfun = ajax_return_successfun;
if (_failurefun == null) _failurefun = ajax_return_failurefun;
if (_global != false) { _global = true; }
if (_async != false) { _async = true; }
$.ajax({
type: "POST",
url: _url,
data: _data,
global: _global,
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
async: _async,
success: _successfun,
error: ajax_return_error,
failure: _failurefun
});
}
function ajax_return_successfun(response) {
console.info("success for " + response.d);
}
function ajax_return_failurefun(response) {
console.error("failuer occoured for " + response);
}
function ajax_return_error(response) {
console.warn("error occoured for " + response);
}
// // // call the above function
function myResponseFn(response){
if(response.data){
// // your code...
}
}
var data = "{'tbl': 'district'}";
serviceajaxjson(myResponseFn,myResponseFn,"http://localhost/webmap201/php/load_data.php",data);
If you're using latest version of popular browser (IE's dead, use Edge instead), then the simplest answer is yes. You might need some tweaking on the parameters and its use, but it should work
How to access this json data in JavaScript.
when I alert it the result is undefined
Here is jQuery code
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Here is the problem
alert(data[0]['Result']);
}
});
This is PHP code
$data=array($no);
for($i=0;($i<$no && ($row=mysql_fetch_array($result)));$i++)
{
$data[$i]=array();
$data[$i]['Result'] = $row['Result'];
$data[$i]['TestCode'] = $row['TestCode'];
$data[$i]['TestStatus'] = $row['TestStatus'];
$data[$i]['SrNo'] = $row['SrNo'];
}
$data1=json_encode($data);
echo $data1;
exit;
I have tested the PHP file independently,
The json data is output as follows:
[{"Result":"1","TestCode":"22","TestStatus":"0","SrNo":"1"},{"Result":"1","TestCode":"23","TestStatus":"1","SrNo":"2"}]
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = jQuery.parseJSON(data)
alert(data[0]['Result']);
}
});
You can access to your data by doing
data[0].Result
It's an Object, not an array.
so data[0]['Result'] it's not the proper way
EDIT:
Since you have more objects, you have to do a loop this way:
$.each(data, function(key, val){
console.log(val.Result);
console.log(val.TestCode);
//...
});
When you see something like
{
"foo":"bar",
...
}
you can access to it the same way as above:
name_of_the_object.foo
that will have the value "bar"
Try to add parse JSON. I have added. Now it may be work.
$.ajax({
type: "POST",
url: "frmMktHelpGridd.php",
data: {
labNo: secondElement
},
dataType: "json",
beforeSend: function () {
// Do something before sending request to server
},
error: function (jqXHR, textStatus, errorThrown) {
alert('error has occured');
alert(errorThrown);
},
success: function (data) {
//Added parse json
var data = $.parseJSON(data)
alert(data[0]['Result']);
}
});
Heylow everyone!
I have an ajax() call like so:
$.ajax({
type: "post",
url: "whatever.php",
data: {
theData: "moo moo"
},
success: function(data) {
console.log(data);
}
});
Is it possible to wrap this inside a custom function but retain the callback?
Something like:
function customAjax(u, d, theCallbackStuff) {
$.ajax({
type: "post",
url: u,
data: d,
success: function(data) {
//RUN theCallbackStuff
}
});
}
theCallbackStuff will be something like:
var m = 1;
var n = 2;
alert(m + n + data);
EDIT:
Got a recent upvote for this and I feel compelled to state that I would no longer do it this way. $.ajax returns a promise so you can do pretty much what i just did here in a more consistent and robust way using the promise directly.
function customRequest(u,d) {
var promise = $.ajax({
type: 'post',
data: d,
url: u
})
.done(function (responseData, status, xhr) {
// preconfigured logic for success
})
.fail(function (xhr, status, err) {
//predetermined logic for unsuccessful request
});
return promise;
}
Then usage looks like:
// using `done` which will add the callback to the stack
// to be run when the promise is resolved
customRequest('whatever.php', {'somekey': 'somevalue'}).done(function (data) {
var n = 1,
m = 2;
alert(m + n + data);
});
// using fail which will add the callback to the stack
// to be run when the promise is rejected
customRequest('whatever.php', {'somekey': 'somevalue'}).fail(function (xhr, status, err) {
console.log(status, err);
});
// using then which will add callabcks to the
// success AND failure stacks respectively when
// the request is resolved/rejected
customRequest('whatever.php', {'somekey': 'somevalue'}).then(
function (data) {
var n = 1,
m = 2;
alert(m + n + data);
},
function (xhr, status, err) {
console.log(status, err);
});
Sure i do this all the time. You can either execute the callback within the actual success callack or you can assign the callback as the success callback:
function customRequest(u,d,callback) {
$.ajax({
type: "post",
url: u,
data:d,
success: function(data) {
console.log(data); // predefined logic if any
if(typeof callback == 'function') {
callback(data);
}
}
});
}
Usage would look something like:
customRequest('whatever.php', {'somekey': 'somevalue'}, function (data) {
var n = 1,
m = 2;
alert(m + n + data);
});
function customAjax(u, d, theCallbackStuff) {
$.ajax({
type: "post",
url: u,
data: d,
success: theCallbackStuff
});
}
customAjax(url, data, function(data){
//do something
});
On this note, you can pass a complete function as a callback to this:
function customRequest(u,d,callback) {
$.ajax({
type: "post",
url: u,
data:d,
success: function(data) {
console.log(data); // predefined logic if any
if(typeof callback == 'function') {
callback(data);
}
}
});
}
// Then call it as follows:
function initiator() {
customRequest( '/url/to/post', 'param1=val', function() { alert( 'complete' ); })
}
Simply passing it as an anonymous function will work too.. Just for the sake of showing :)
I'd like to know if there is a better approach to creating re-usable ajax object for jquery.
This is my un-tested code.
var sender = {
function ajax(url, type, dataType, callback) {
$.ajax({
url: url,
type: type,
dataType: dataType,
beforeSend: function() {
onStartAjax();
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
callback.failure(XMLHttpRequest, textStatus, errorThrown);
},
success: function(data, textStatus) {
callback.success(data, textStatus);
},
complete: function (XMLHttpRequest, textStatus) {
onEndAjax();
}
});
},
function onStartAjax() {
// show loader
},
function onEndAjax() {
// hide loader
}
};
<script type="text/javascript">
var callback = {
success: function(data, textStatus) {
$('#content').html(data);
},
failure: function(XMLHttpRequest, textStatus, errorThrown) {
alert('Error making AJAX call: ' + XMLHttpRequest.statusText + ' (' + XMLHttpRequest.status + ')');
}
}
sender.ajax(url, type, dataType, callback);
</script>
You can set the basic options that you always have the same separately.
for instance if you always use the same thing here:
type: type,
dataType: dataType,
for those types, you can set them separately.
Here is how you do that type of thing:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}"
});
NOW those are set and you can simplify your individual ajax calls.
EDIT:
NOTE: Setting parameters to $.ajax override these defaults. Thus presetting “data” to an empty JSON string is safe and desired. This way, any $.ajax call that does specify a data parameter will function as expected, since the default will not be used. This helps avoid issues that can be difficult to find on a deployed site.
Here is what I did:
var ajaxclient = (function (window) {
function _do(type, url)
{
return $.ajax({
url:url,
type:type,
dataType:'json',
beforeSend: _onStartAjax
}).always(_onEndAjax);
}
function _onStartAjax()
{
console.log("starting ajax call");
}
function _onEndAjax()
{
console.log("finished ajax call");
}
return {
do:_do
}
}(this));
Example usage:
ajaxclient.do("get","http://...").done(function(data) {console.log(data);})
I'd probably go the whole hog and have an Ajax Object create.
var ajax = new MySuperAjax(url, data);
ajax.onComplete = function(){}
or similar. You seem to have a halfway between a function which has some defaults it extends with those you apss in and an object for it.