universal jquery ajax call function - javascript

wondering is there any kind of global (universal) one function for calling ajax function..
for example i have lots of similar call like this:
$.ajax({
url: some_url_address,
type: 'post',
data: $('#form').serialize(),
dataType: 'html',
success: function(data){
alert('success');
}
});
and i would like to make it something like
callAjax('my_url', 'post', {some_data}, 'alert("success")');
and in javascript file:
function callAjax(url, type, data, successFunction, errorFunction, beforeFunction){
$.ajax({
url: url,
type: type,
data: data,
dataType: 'html',
beforeSend: function(){
beforeFunction;
},
success: function(){
successFunction;
}
error: function(){
errorFunction;
}
});
}
that in my page from where i'm calling that function it would return results from before, error, success, etc.. :)

Just install webpack by npm install.
And in the input field write data-ajaxify='true'
Also include the npm js and css file.
<input type='test' data-ajaxify='true' data-url='/someurl' data-method='post'>

Related

Ajax redirect on error

I'm calling php file through ajax call and if it returns nothing i want to redirect user to another page (It's for error reports, if it doesn't return anything it means that user logged in). Tried to add error section but it doesn't work. Any suggestions will help. Thanks! Btw, I have small jQuery function at the top of the ajax function, why it breaks my whole ajax call?
ajax.js
function loginAjax() {
//$("#email_errors").empty(); //This function doesnt work and kills whole ajax call. Here is loginAjax function call line - <button type = "submit" id = "push_button" onclick = "loginAjax(); return false">PushMe</button>
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
}
});
}
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
success: function(data) {
$("#login_error").html(data.login_message);
},
error: function(){
window.location.replace("http://stackoverflow.com");
}
});
}
To redirect using javascript all you need to do is override the location.href attribute.
function loginAjax() {
$.ajax({
url: "Classes/call_methods_login.php",
type: "POST",
dataType: "json",
data: {
login_email: $("#login_email").val(),
login_password: $("#login_password").val(),
},
// the success method is deprecated in favor of done.
done: function(data) {
$("#login_error").html(data.login_message);
},
fail: function(data) {
location.href="path/to/error/page";
}
});
}

Running an javascript function before an ajax call

I want to run the first ajax call when it has completed run the function "saveToFile()" and after that has been completed run the second ajax call. Doesn't seem to work as coded. I'm fairly new to ajax so am struggling a little with this one.
// save composition to database
$.ajax({
type: "POST",
url: "_inc/save_to_db.php",
data: {jsonStr: canvasStr},
success: function(data) {
// this saves the comp to the _comps folder on the server as a jpeg file (firth.js)
saveToFile();
$.ajax({
type: "POST".
url: "_inc/generate_thumbnail.php",
data: {imgFile: "<?php echo $_SESSION['UserID'] ?>_<?php echo $_SESSION['CompID'] ?>.jpg"},
});
}
});
Works for me: http://jsbin.com/upujur/2/edit
The problem might be with the dot instead of comma in this line:
type: "POST".
Are you using a JavaScript console like FireBug or Developer Tools to debug your program?
You could make the saveToFile function take as parameter a callback which will be executed once the AJAX call it performs is finished. For example:
$.ajax({
type: "POST",
url: "_inc/save_to_db.php",
data: {jsonStr: canvasStr},
success: function(data) {
// this saves the comp to the _comps folder on the server as a jpeg file (firth.js)
saveToFile(function(result) {
$.ajax({
type: "POST",
url: "_inc/generate_thumbnail.php",
data: {imgFile: "<?php echo $_SESSION['UserID'] ?>_<?php echo $_SESSION['CompID'] ?>.jpg"},
});
});
}
});
and your saveToFile function may now look like that:
function saveToFile(successCallback) {
$.ajax({
url: ...,
type: ...,
data: ...,
success: successCallback
});
}

proper way to fill js variables via ajax request

At the moment i am using the follwing way to fill my global js variables with data which is obtained by json:
var tranlationJson =
$.ajax({
type: "GET",
url: "translation.xml",
contentType: "text/xml",
dataType: "xml",
success: function (dataSource) {
tranlationJson=ToJasonParser(dataSource);
}
});
Is there a more clever way? I need those variables filled because in the scrips which are loaded later i use their content.
You can make tranlationJson an object instead of variable like this:
var tranlationJson = {
init: function(){
$.ajax({
type: "GET",
url: "translation.xml",
contentType: "text/xml",
dataType: "xml",
success: function (dataSource) {
this.data = ToJasonParser(dataSource);
}
});
}
then call init function like this:
tranlationJson.init();
then you can access Json response data like this:
tranlationJson.data.something;
Demo

How to update js object type variable via ajax?

I have a javascript variable that is created in php
echo "var".$locallist."=".create_js_variable($locallist,$db2_list_all,'db2');
and it looks in html page source code like
var locallist={
'CARINYA':[['2011-08-24-09-22 - w','20110824092216w'],['2011-08-18-13-15','20110818131546']],
'COVERNAN':[['2011-03-02-12-28','20110302122831']],
'DAVID':[['2010-12-22-19-43','20101222194348'],['2010-12-08-14-10','20101208141035']]};
Now I want to update the variable on button click via ajax
jQuery.ajax({
type: 'get',
dataType: 'text',
url: url,
data: {
what: 'db2list',
t: Math.random()
},
success: function(data, textStatus){
locallist = data;
console.log(locallist);
}
});
and the ajax calls this php code (note that it's the same php function that is called)
if($what == 'db2list') {
$db2_list_all = get_db2_database_list();
echo create_js_variable($locallist,$db2_list_all,'db2');
}
Console.log reports that
before update the variable is an object
after update it is a text
How can I fix that? So my other javascript code works again?
Well, look at your ajax call:
jQuery.ajax({
type: 'get',
dataType: 'text',
url: url,
data: {
what: 'db2list',
t: Math.random()
},
success: function(data, textStatus){
locallist = data;
console.log(locallist);
}
});
Notice you've got the dataType as text? It's going to bring the data in and treat it as text. Try changing the dataType to 'json'. That will convert the data that was brought in to a regular 'ol object, just like what you already have.
Your AJAX-request has a type dataType: 'text',
Change it to JSON :)
Use dataType: 'json'.
jQuery.ajax({
type: 'get',
dataType: 'json',
url: url,
data: {
what: 'db2list',
t: Math.random()
},
success: function(data, textStatus){
locallist = data;
console.log(locallist);
}
});

Call another method onSuccess event of an Ajax call

I have an AJAX call on MVC3 it looks like this
save: function () {
$.ajax({
url: "#Url.Action("Save")",
type:"post",
data: ko.toJSON(this),
contentType:"application/json",
success: function(result){alert(result.message)}
});
}
The trouble is the line
success: function(result){alert(result.message)}
I want to pass all the messing things in a HtmlHelper, however, the success line prevents me from doing so, is there a way I can specify a function for that line
success: doSomeStuff(result)
and
function doSomeStuff(result){alert(result.message)}
Thanks in advance
Simply pass the function name to the success: method and it will pass the data onwards, as such:
save: function () {
$.ajax({
url: "#Url.Action("Save")",
type:"post",
data: ko.toJSON(this),
contentType:"application/json",
success: doSomeStuff
});
}

Categories