I'm working on an HTML app in which there is a form. On clicking the submit button, I make a server-side call using jquery.ajax(). However, whenever an exception is returned from the server, like a Status Code 500, I need to display an error message on the same page. However, it automatically redirects when it encounters an error. I tried using the statusCode setting in jquery.ajax() like this:
$.ajax(
{
method: 'GET',
url: 'my url',
//...
successCode: {
500: function(response) {
alert(response.getResponseHeader("xyz"));
$('some_selector').show();
}
},
success: function(){},
error: function(){}
//...
})
But this does not seem to work. It redirects me to the action link and displays the JSON error and I cannot think of a way to prevent this redirect. Any help would be appreciated.
Thanks
It seems like your ajax options are outside of the ajax call put your parameters inside like
$.ajax(){options} => $.ajax({options})
Try this,
$.ajax({url: 'your url',
type: 'GET',
success: function (response) {
//succesfull request
}
}).fail(function (response) {
//failed request
});
You should be able to find the status code in the fail using response.status
I think your submit button is triggering the redirect. Try adding
$("#myform").submit(function(event){
event.preventDefault();
});
to prevent the redirect
Related
Issue:
The first ajax is working properly in the main.js, the second one is doing its job at first look but I think there might be a bug somewhere. I can reach the getProducts method after I click to the button.
The product_list.html file should appear on the browser screen, but it doesn't.
I get no error message on the front-end or the back-end.
This is what I noticed: After click to the button -> F12 -> Network -> products -> I can see here a status code: 200 and the product_list.html file content as response.
In case the POST ajax call succeeds and in the case I add: location.href = "/products";, the browser will load product_list.html
I use the get ajax call because i need to pass the jwt token in the req header. (I deleted the jwt authentication parts from the code below because I narrowed down the error to the $.ajax() and res.sendFile() relationship)
//routes.js
routes.get("/products", ProductController.getProducts);
//ProductController.js
var root = path.join(__dirname, '../../views');
module.exports = {
getProducts(req, res){
console.log("getProducts!"); //I can see in the console
res.sendFile("product_list.html", {root}) //It doesn't render the html
},
}
//main.js
$("#btn-login").click(function(){
$.ajax({
type: 'POST',
url: "http://localhost:8000/login",
dataType: "json",
contentType: "application/json",
data: JSON.stringify({
"username": $("#login-user").val(),
"password": $("#login-pwd").val(),
}),
success: function(data){
if ($("#login-chkbx").is(':checked')){
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
});
}
}else{
console.log("Checkbox is not checked");
}
}
});
});
What causes the issue and how to solve it?
Thanks!
file should appear on the browser screen
No it does not and it should not. The file should be returned to the ajax function call in the success callback:
$.ajax({
url: "http://localhost:8000/products",
type: 'GET',
beforeSend: function (xhr) {
xhr.setRequestHeader("user", localStorage.getItem("user"));
},
success: function (file) {
// The file is in the "file" variable above.
// Do whatever you want with it. For example you can replace
// the current page with the returned file:
document.body.innerHTML = file;
}
});
That is the whole point of AJAX - a mechanism for programmers to override the normal flow of HTTP requests that loads the response to the browser page. If it allows you to not load the response to the browser page it also means it will not automatically load the response to the browser page - because doing so will not allow you to not load the response.
If you want to automatically load the response then don't use ajax:
// Replace $.ajax(... with:
window.location.href = "http://localhost:8000/products";
However, this method does not allow you to set custom request header.
in your frontend code you do nothing with the GET /products response
the backend sendfile as the name says it just sends the file over to the requester. Being an ajax call, it must be rendered by the frontend code.
Add something like success: response => $('body').html(response)
I have create draft order using Shopify Draft order api in php via ajax call.
in ajax response I get one url and redirect on it www.mysite.com/17875421/invoices/280fa46bee5ca183da7e774457522428.
url is correct and all things goes well user able to see the checkout page with correct order data.
But sometime shopify show the 404 page rather than checkout page.
after showing the 404 page if I refresh the page by simple heating F5 Key than all works fine.
I can't understand why this happening.
would someone help me to solve and find the reason why this things happening ?
My ajax call function as below
jQuery.ajax({
url: AjaxUrl,
type: "post",
dataType: "json",
data: {
formData
},
beforeSend: function () {
showLoader();
},
complete: function () {
hideLoader();
},
success: function (response) {
if (response['result'] == 'success') {
window.location = response['invoice_url'];
}
}
});
I am quiet new to JQuery. I am sending an AJAX request (File Upload) to WEB API (ASP.NET MVC) but my responses are getting downloaded as JSON file rather than the loaded to success data.
Please find the code in the HTML below
$('#myForm1')[0].submit(function (event) {
alert("Hello2");
event.preventDefault();
//grab all form data
var formData = new FormData($(this)[0]);
alert("Hello2");
$.ajax({
url: 'http://localhost:102/webapi/api/values/All',
type: 'POST',
data: formData,
datatype : "json",
//async: false,
//cache: false,
contentType: true,
processData: false,
complete: function () {
alert("Complete");
},
success: function (returndata) {
// $("#productFormOutput").html(returndata);
alert("Executed");
},
error: function () {
alert("error in ajax form submission");
}
});
return false;
});
BTW no alert messages in success, error and complete is called after getting the response. But Fiddler shows the response is successful (HTTP 200). Is anything am I doing wrong while calling the request?
try using "done" method as the success handler instead of "success",
and instead of alert use console log(you can check the log on the browser, ctrl+shift+I on chrome, you can even put object to be logged).
after several times alert my be blocked by browser as it is annoying.
easy and complete reference: https://scotch.io/tutorials/submitting-ajax-forms-with-jquery
*what is the complete method doing in that post object ?
Removing [0] and changing the input to 'submit' in form solved my problem
$('#myForm1')[0].submit(function (event)
As Roland said, submit with button in input tag is not handling the event handler
I do a jQuery ajax POST which successfully delivers the correct data to the server.
After the POST is complete, the browser has redirected to the post url page... which I don't want. Neither of the alerts occur. The POST data has arrived at the server just fine.
i.e. after the ajax is performed within a page at http://myDomain/myPage.html as shown below, the browser address bar shows http://myDomain:39991/updateEnabled and no alerts have happened.
var enabledAjax = $.ajax({
url: 'http://myDomain:39991/updateEnabled',
method: 'POST',
data: $('#enabledForm').serialize(),
dataType: 'jsonp'
});
enabledAjax.done(function (msg) {
alert('done')
})
enabledStatus.fail(function (jqXHR, textStatus) {
alert('textStatus');
})
In express, i have router.post('/updateEnabled', urlEncodedParser, updEnab);
Within updEnab all I do at the moment is a console.log of req.body and res.end()
I've tried a 'success' method within the ajax params but that doesn't work either.
What am I doing wrong that is causing the redirect to the POST url?
hello when you submit form this is submitting normally so you need to use this.
event.preventDefault()
this will stop stop normal submitting of form.
To stop the redirection you can use the return statement like this:
enabledAjax.done(function (msg) {
return false;
})
The server is written in web2py, and hosted on google app engine. I can visit my index.html by entering domain.com/index and I can send form by entering domain.com/register where "register" is a function defined by default.py
However, in html, where I would like to send form to the server and get a response, I use ajax which has cross domain issues. So I use "register" as URL, and it does not work. Help?
$("#signup").click(function() {
$.ajax({
type: "POST",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
By typing domain.com/register, I can totally trigger the function. What is the problem here? And the form is sent to domain.com... In browser it appears as htt[://domain.com/?email=ada#ad.com&password=adsa
Its very possible register is looking for GET instead of POST
try changing the type in ajax
$("#signup").click(function() {
$.ajax({
type: "GET",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});