Ajax to call another Ajax function upon done - javascript

var App = {
actionRequest: function (url,data,callback){
var that = this;
$('#menu').panel('close');
$.mobile.loading('show');
$.when(
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})
).done(function(data,html) {
that.refreshCart();
$.mobile.loading('hide');
}
);
}
refreshCart: function(){
App.loadExternalContent('content','scripts/data_ajax.php','action=getCart','templates/cart.htm');
}
}
I need to call refreshCart in ".done". How can i write a callback function in ".done" to do so? Sorry i am new with Ajax.

var object = {
actionRequest: function(url, data, callback) {
$('#menu').panel('close');
$.mobile.loading('show');
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
}).done(function(data, html) {
if ($.isFunction(callback)) {
callback();
}
$.mobile.loading('hide');
}
);
}
}
usage:
if refreshCart is function in the object you can also do this:
var object = {
actionRequest: function(url, data, callback) {
var that = this;
$('#menu').panel('close');
$.mobile.loading('show');
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
}).done(function(data, html) {
// without using a callback
that.refreshCart();
$.mobile.loading('hide');
}
);
},
refreshCart: function() {
App.loadExternalContent('content', 'scripts/data_ajax.php', 'action=getCart', 'templates/cart.htm');
}
}
Here is an example of how to use ajax requests
$.ajax({
url: 'http://echo.jsontest.com/title/ipsum/content/blah',
method: 'GET'
})
.done(function(response) {
console.log(response);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

I am assuming you are referring this code in class.
actionRequest: function (url,data,callback){
var self = this; //keep reference of current instance for more info read closures in JS
$('#menu').panel('close');
$.mobile.loading('show');
$.when(
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})
).done(function(data,html) {
self.refreshCart();
$.mobile.loading('hide');
}
);
}
refreshCart: function(){
App.loadExternalContent('content','scripts/data_ajax.php','action=getCart','templates/cart.htm');
}

Ajax function:
actionRequest: function (url,data,callback){
$('#menu').panel('close');
$.mobile.loading('show');
$.when(
$.ajax({
method: 'POST',
url: url + '?' + new Date().getTime(),
data: data
})
).done(function(data,html) {
callback();
$.mobile.loading('hide');
}
);
}
call function:
actionRequest(url, data, refreshCart);

Related

How can I use callback function from ajax in another function

How can I use callback function from ajax in another function
I've got function with ajax:
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
showTheValue(result);
}
});
}
var showTheValue = function(correct_day_value) {
console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
return correct_day_value;
};
And I want to have the response/data value from ajax in another function like that:
function correct_start_date() {
document.getElementsByTagName("INPUT")[1].value = showTheValue();
}
How can I use response data from ajax in another function ?
You can you the JavaScript Promise.
http://www.html5rocks.com/en/tutorials/es6/promises/
function get(url) {
// Return a new promise.
return new Promise(function(resolve, reject) {
// Do the usual XHR stuff
var req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
// This is called even on 404 etc
// so check the status
if (req.status == 200) {
// Resolve the promise with the response text
resolve(req.response);
}
else {
// Otherwise reject with the status text
// which will hopefully be a meaningful error
reject(Error(req.statusText));
}
};
// Handle network errors
req.onerror = function() {
reject(Error("Network Error"));
};
// Make the request
req.send();
});
}
function correct_date(raw_date, callback){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
return callback(result);
}
});
}
function showTheValue() {
correct_date(raw_date, function(correct_day_value) {
document.getElementsByTagName("INPUT")[1].value = correct_day_value;
});
}
You must use those two functions like:
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
correct_start_date(showTheValue(result));//***
}
});
}
var showTheValue = function(correct_day_value) {
console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
return correct_day_value;
};
function correct_start_date(correct_day_value) {
document.getElementsByTagName("INPUT")[1].value = correct_day_value;
}
Or if the "correct_start_date" is used according to a case:
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
var correct_day_value = showTheValue(result);
if (/* some case */) {
correct_start_date(correct_day_value);//***
}
}
});
}
Or wait until the value is set by the Ajax:
var globalVar = null;
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
globalVar = showTheValue(result);
//correct_start_date(globalVar);
}
});
}
var showTheValue = function(correct_day_value) {
console.log(new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE'));
return correct_day_value;
};
function getGlobalVar() {
if(globalVar == null) {
window.setTimeout(getGlobalVar, 50);
} else {
return globalVar;
}
}
function correct_start_date() {
if (
document.getElementsByTagName("INPUT")[1].value = getGlobalVar();
}
This code worked for me:
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json'
});
}
And then I can insert it wherever I want like this:
function parse_correct_day() {
.
.
.
.
var parse_correctday_value = correct_date("12.1.2016");
parse_correctday_value.success(function (data) {
var corrected_date = new Date(data.DATE_NEW);
document.getElementsByTagName("INPUT")[1].value = corrected_date.toLocaleDateString('de-DE');
});
}
Instead of calling 2 functions you should return the result from the function showTheValue and then show the response in the desired elements :
function correct_date(raw_date){
return $.ajax({
method: "GET",
url: "../date/correct.php",
data: {
method: 'correct_date',
date: raw_date
},
cache: false,
dataType: 'json',
success: function(result) {
console.log(result.DATE_NEW);
//You need to check the return value of your function and add the value accordingly
document.getElementsByTagName("INPUT")[1].value = showTheValue(result);
}
});
}
function showTheValue(correct_day_value) {
var localDate = new Date(correct_day_value.DATE_NEW).toLocaleDateString('de-DE');
console.log(localDate);
return localDate;
};

How to make a search with jquery and the wikipedia API

I have read a lot of posts, old, new and the wikipedia documentation.
I have this request that works itself and in the sanbox:
https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=einstein&format=json
https://www.mediawiki.org/wiki/Special:ApiSandbox#action=query&format=json&list=search&srsearch=einstein
but when I try to use it in a javascript script, I can not get the data:
I tried both ajax and Json:
here is the code I used:
a 'GET' request with ajax :
code markup sucks
function build_wiki_search_url(pattern) {
var base_url = "https://en.wikipedia.org/w/api.php";
var request_url = "?action=query&format=json&list=search&srsearch=";
var url = base_url + request_url + pattern;
return url;
}
$(document).ready(function() {
$("#doit").click(function() {
console.log("Submit button clicked");
var pattern = $("#search").val();
var url = build_wiki_search_url(pattern);
console.log(url);
$.ajax( {
type: "GET",
url: url,
dataType: 'jsonp',
success: function(data) {
console.log(data);
},
error: function(errorMessage) {
console.log("damnn");
}
});
console.log("end");
});
})
a 'POST' request with ajax following the wikipedia documentation
var base_url = "https://en.wikipedia.org/w/api.php";
$.ajax( {
contentType: "application/json; charset=utf-8",
url: base_url,
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: 'einstein',
origin: '*',
},
dataType: 'json',
type: 'POST',
success: function(data) {
console.log("ok");
// do something with data
},
error: function(errorMessage) {
console.log("damnn");
}
} );
and a getJSON try:
//getJSON atempt.
console.log(url + '&callback=?');
$.getJSON(url + '&callback=?', function(json) {
console.log("ok");
});
Here is the output in my console:
Submit button clicked
https://en.wikipedia.org/w/api.php?action=query&format=json&list=search&srsearch=einstein
script.js
end
The problem comes in fact from the html:
<form >
<input type="text" id="search"> <button id="doit"> Search!!</button>
</form>
Since the button is in a form, this button normal behavior is to generate a submit action. So the idea is to disable this normal behavior with:
$("#doit").click(function(e) {
e.preventDefault();
The full working code :
function build_wiki_search_url(pattern) {
var base_url = "https://en.wikipedia.org/w/api.php";
var format = "&format=json";
var request_url = "?action=query&format=json&list=search&srsearch=";
var url = base_url + request_url + pattern;
return url;
}
$(document).ready(function() {
$("#doit").click(function(e) {
e.preventDefault();
console.log("Submit button clicked");
var pattern = $("#search").val();
var url = build_wiki_search_url(pattern);
$.ajax( {
type: "GET",
url: url,
dataType: 'jsonp',
success: function(data) {
console.log(data.query.searchinfo.totalhits);
},
error: function(errorMessage) {
console.log("damnn");
}
});
});
})

jsCall return value to outside of jquery ajax post request

I want to get jquery ajax post request value to outside from the ajax function. my code is this and it return undefined as console output. How should fix it
function submit() {
var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');
console.log(outputFromAjax);
}
function submitViaPost(url) {
var formData = $('form').serializeArray();
var output;
$.post(urlForPhp + '/' + url, formData, function (outputData) {
output = outputData;
});
return output;
}
Edited
I changed my code to sync type ajax post request and check output. But it is not changed. here my code
function submit() {
var outputFromAjax = submitViaPost('administrator/validationForInputValuesOfAddRole');
console.log(outputFromAjax);
}
function submitViaPost(url) {
var formData = $('form').serializeArray();
var output;
$.ajax({
url: urlForPhp + '/' + url,
data: formData,
dataType: 'JSON',
async: false,
method: 'POST',
success: function (e) {
output = e;
}
});
return output;
}
You can use Deferred jQuery
function submit() {
submitViaPost('administrator/validationForInputValuesOfAddRole').then(function (outputFromAjax) {
console.log(outputFromAjax);
});
}
function submitViaPost(url) {
var dfd = jQuery.Deferred();
var formData = $('form').serializeArray();
$.post(urlForPhp + '/' + url, formData, function (outputData) {
dfd.resolve(outputData);;
});
return dfd;
}
Don't return , make it a callback as $.post is async
function submit() {
submitViaPost('administrator/validationForInputValuesOfAddRole', function(out){ //Result comes here
var outputFromAjax = out;
console.log(outputFromAjax);
});
}
function submitViaPost(url , callback) { //Added callback
var formData = $('form').serializeArray();
$.ajax({
url: urlForPhp + '/' + url,
data: formData,
dataType: 'JSON',
async: false,
method: 'POST',
success: function (e) {
callback(e);
}
});
}

Combining Jquery and Javascript function

This is a relatively novice question. I have the following jQuery function:
$(function ()
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
});
I'm looking to name and parameterize the function so that I can call it repeatedly (with the parameters queryType and divID which are already included in the code). I've tried unsuccessfully multiple times. Would anyone have any insight?
Just stick it in a function
function doAjax(queryType, divID) {
return $.ajax({
url: 'testapi.php',
data: {query : queryType},
dataType: 'json'
}).done(function(data) {
var id = data[0];
$('#'+divID).html(id);
});
}
and use it
$(function() {
element.on('click', function() {
var id = this.id
doAjax('get_content', id);
});
});
or
$(function() {
element.on('click', function() {
var id = this.id
doAjax('get_content', id).done(function(data) {
// do something more with the returned data
});
});
});
If you're just looking for a simple function to wrap the ajax call give this a try. Place this function above the document ready code.
function callAjax(queryType, divID) {
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data) {
var id = data[0];
$('#'+divID).html(id);
}
});
}
To call the function do this:
callAjax('YourQueryHere', 'YourDivIdHere');
function myFunction(queryType, divID)
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
}
and to call it simply use
myFunction("someQueryType", "myDiv");
function doThis(queryType, divID)
{
$.ajax({
url: 'testapi.php',
data: "query="+queryType,
dataType: 'json',
success: function(data)
{
var id = data[0];
$('#'+divID).html(id);
}
});
}

jQuery - get reference to this

function Request(params)
{
// Stuff stuff stuff
// And then
$.ajax(
{
type: 'GET',
url: 'someurl',
success: this.done
});
}
Request.prototype.done = function()
{
// "this" in this context will not refer to the Request instance.
// How to reach it?
}
You could capture "this" first:
function Request(params)
{
// Stuff stuff stuff
// And then
var $this = this;
$.ajax(
{
type: 'GET',
url: 'someurl',
success: function() { $this.done(); }
});
}
Apparently you can add the "context" parameter to the ajax request, like so:
$.ajax(
{
type: 'GET',
url: 'someurl',
success: this.done,
context: this
});
this is not reffering to the same thing!!!
try following:
function Request(params)
{
var that = this;
....
Request.prototype.done = function()
{
that...

Categories

Resources