I have the following example form below where beforeSend function shows a message that is sending and once it is sent an other function is called .done(function (data) showing a message that message has been sent. All I want to do is to use another function where the message is not sent, to display the message "error, message is not sent"
var form = $('#main-contact-form');
form.submit(function (event) {
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Subject: $form.find("input[name='subject']").val(),
Email: email,
message: $form.find("textarea[name=message]").val(),
},
beforeSend: function () {
// message is sending...
}
}) //end ajax
.done(function (data) {
// message sent!
});
});//end contact form
You can use fail api to handle errors as shown below.
Also, in the $.ajax({constObj}) you can have apis like success and error to handle the same.
Refer here for more info
//1.
$.ajax({
type: 'POST',
url: '../sendemail.php',
data: {
Name: name,
Subject: $form.find("input[name='subject']").val(),
Email: email,
message: $form.find("textarea[name=message]").val(),
},
beforeSend: function () {
// message is sending...
}
}) //end ajax
.done(function (data) {
// message sent!
})
.fail(function(){
//handle error here
});
//2.
constObj.success(function(data){
});
constObj.error(function(error){
});
Instead of .done use ajax options success and error. Throw error on server when sending email fails.
$.ajax({
success: function () {
// message sent!
},
error: function () {
// message sent failed!
}
});
On server side:
if ($this->sendMessage()) {
echo "ok";
} else {
throw new Exception('Email failed to send.', 500);
}
You can't tell if user actually receives email (I guess there is some complicated ways to figure it out).
You use done(), which is executed after a SUCCESSFUL ajax request (usually returns HTTP 200). If you read http://api.jquery.com/jquery.ajax/, there is fail(), which is executed after a FAILED ajax request.
It also depends the output of sendemail.php. If your PHP returns other than HTTP 200 when error, you can utilize fail() promise method, for example...
$.ajax({
beforeSend: function() {
$('msg').text('Sending email...');
}
}).done(function() {
$('#msg').text('Success!');
}).fail(function() {
$('#msg').text('Failed!');
});
But, if your PHP also returns HTTP 200 when error, you can do something like the following...
PHP:
$response = array(
'status' => null,
'error' => null
);
if ($mailer->send()) {
$response['status'] = true;
} else {
$response['status'] = false;
$response['error'] = 'Unable to send email';
}
jQuery:
$.ajax({
beforeSend: function() {
$('msg').text('Sending email...');
}
}).done(function(data) {
if (data.status === true) {
$('#msg').text('Success!');
} else {
$('#msg').text('Failed: ' + data.error);
}
});
Related
I'm trying to check if same email exist in server db, but ajax is returning code 0 even my server is opened.
I checked it by using URL in browser.
if (input == email.find(".form_input").val()) {
emailChecking = true;
$.ajax({
url: "https://localhost:8888/check?target=" + input,
async: true,
type: "GET",
dataType: "text",
success: (data) => {
console.log(data);
if (emailChecking == true) {
emailChecking = false;
inputField(email, error);
}
},
error: (request, status, errorLine) => {
if (emailChecking == true) {
emailChecking = false;
error = "cannot check email - code " + request.status;
inputField(email, error);
}
}
});
}
I want to call this function on button click after login and wait for result, to get token value. This function cannot be changed, it is async and supplied from other currently unavailable team.
I already tried something like this, but with no success. I get web service results, but I can't write appropriate sync call to wait to return token.
function getToken() {
param1 = "123456";
ajax_oauth(param1, function (success, response) {
success: return response.token;
});
}
function ajax_oauth(param1, callback) {
APP.debug("oauth login with param1 " + param1);
try {
APP.blockUI();
var DeviceID = APP.readRegistry(APP_CONFIG.REGISTRY.DeviceID);
//---------------------------------------------------------------
$.ajax(
auth_token_url,
{
method: "GET",
accept: 'application/json',
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: JSON.stringify({
'param1': param1,
'deviceId': DeviceID
}),
xhrFields: {
withCredentials: false
},
statusCode: {
201: function (response) {
APP_STATE.hasOauth = true;
APP.debug('got response 200 from oauth');
auth.login(response.token); //TODO read expiration from token
try {
var decoded = jwt_decode(response.token);
APP_STATE.uid = decoded.uid;
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
},
401: function () {
},
500: function () {
},
503: function () {
}
},
success: function (response) {
APP.unblockUI();
APP_STATE.restAvailable = true;
},
error: function (jqXHR, textStatus, errorThrown) {
APP.unblockUI();
APP_STATE.restAvailable = false;
APP.restError(auth_token_url, jqXHR, errorThrown, textStatus);
APP.callback(callback, false);
}
}
);
} catch (err) {
APP.error("unable to do oauth login, " + err);
}
};
After user clicks on login button, I want to call function ajax_oauth and to return token if params ok. If not, to return login error. Login can't be async, as far as I can see.
For whatever reason you can't tap into the original ajax response, you could intercept the request using $.ajaxPrefilter.
From your code it looks like auth_token_url has a global reference. You could use this to intercept the call by matching the outgoing request on the resource URL.
$.ajaxPrefilter('json', function(options, originalOptions, jqXHR) {
if (options.url === auth_token_url) {
jqXHR.done(function(response) {
try {
var decoded = jwt_decode(response.token);
console.log(decoded);
} catch (err) {
APP.error("unable to decode token " + JSON.stringify(err));
}
});
}
});
Note that this needs to be declared well before the request is made preferably after jQuery is loaded.
I need to re render my homepage.ejs with new data on the server side after an ajax request. I know you can (somehow) re render the elements in the ajax callback but I was wondering if I could just re render my homapage.ejs since I have if statements that look for vacations, and current_user variables to set the right partialview.ejs
my ajax method:
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
}
});
my server side (inside of a query callback)
get_all_vacations(function (error, vacations) {
if (error) {
console.log("error when getting vacations " + error);
response.json({ success: false });
} else {
request.session.vacations = vacations;
response.render('the_vacation.ejs', { vacations : vacations, current_user : new_current_user }, function() {
response.json({success : true});
console.log("in render method");
});
}
});
i tried this but it does not work.
response.render('the_vacation.ejs', { vacations: vacations, current_user: new_current_user });
I think the simplest way, based on how your code is written would be to use window.location.reload(); when the login is successful.
function user_login(email, password) {
var data = {};
data.email_login = email;
data.password_login = password;
var message_header = $("#message_header");
$.ajax({
url: "/sign_in",
method: 'POST',
data: data
}).done(function (res) {
if (!res.success) {
message_header.text("Incorrect email of password. Please try again.").css("color", "red");
$("#username_textfield").val("");
$("#password_textfield").val("");
}
if (res.success) {
console.log("user logged");
window.location.reload(); // <--- Cause the browser to reload the EJS
}
});
Okay so I have a node js server running on my local machine and I'm trying to make an Ajax call to my server, the server is accepting the request and the request is executing successfully on the server side but on the client side I'm always getting the error response,
{"readyState":0,"responseText":"","status":0,"statusText":"error"}
My code to make Ajax request is as below,
$(document).ready(function() {
$("#button").click(function(e) {
e.preventDefault();
$.ajax({
crossDomain: true,
type: 'GET',
url: 'http://192.168.1.3:8080/insertintoplaylist?videoid=' + $("#videoid").val(),
async: true,
dataType: 'json',
success: function(res) {
alert("response"+res);
},
error: function(error) {
alert("error!" + JSON.stringify(error));
}
});
});
});
Here is the code snippet which will be executed when client makes a request to the path as mention in the url parameter of ajax call,
var req = youtube.videos.list({
id: video,
part: 'snippet,id'
},function(err,data,response){
if(err){
console.error('Error: ' + err);
}
if(data){
console.log(data.items);
var dataItem = data.items[0];
writeUserData(dataItem.id,dataItem.snippet.title,dataItem.snippet.thumbnails.medium.url,function(){
res.json({msg:'Saved'});
});
}
if(response){
console.log('Status code: ' + response.statusCode);
}
});
function writeUserData(videoId, title, thumbnail,cb) {
console.log("\nWriting data for video ");
firebase.database().ref('kidspoemTesting/' + videoId).set({
title: title,
thumbnail: thumbnail,
},function(err){
if(err){
console.log("Failed to save data"+err);
console.log("\nWriting data failed for video ");
}
else {
console.log("Data saved");
console.log("\nWriting data succeed for video ");
cb();
}
});
}
I'm using the following code to delete a collection in my db:
Client:
$('.destroy').click(function() {
if(confirm("Are u sure?")) {
$.ajax({
type: 'DELETE',
url: '/destroy/' + dataId,
success: function(response) {
console.log('Success');
}
});
} else {
alert('Cancelled');
}
});
Server:
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
console.log(err)
}
else {
console.log('Collection removed!');
}
});
});
Is working, if i click in the destroy button and reload the page, the collection will not be there, but the success callback function with the: [console.log('Success');] is not running..
I need send a callback from the server to the client ir order to make the success function run???
How make the console.log('Success'); run??
Thanks.
The ajax call probably just times out, as it's never getting a response back from the server.
Send a response from the server
app.get('/destroy/:id', function(req, res) {
var id = req.param("id");
MyModel.remove({
_id: id
}, function(err){
if (err) {
res.end('error');
}
else {
res.end('success');
}
});
});
Then catch it
$.ajax({
type : 'DELETE',
url : '/destroy/' + dataId,
success : function(response) {
if ( response === 'error' ) {
alert('crap!');
} else if (response === 'success' ) {
alert('worked fine!');
}
}
});
This is a simplified example, you can return whatever you like, send statusCodes or whatever.