AJAX call then page redirect - ajax

I can call an AJAX request when a form submit button is clicked, but if the page reloads/redirects due to the form submission, will the AJAX request still complete? I'm asking this so I could do something like upload a file via AJAX as the form is submitted.
I'm pretty sure I can't get the output of the AJAX call, but could I be wrong?

It's possible, but there's no guarantee that the request would have completed by the time you leave the page. If you're submitting a form via AJAX and also want to submit a file, you might consider placing the file upload in a completely separate form tag, then trigger the form submission after the AJAX call is successful. For example:
<!-- First form with your data -->
<form action="/your/url/here" method="post" id="form1">
<input type="text" name="title" />
<input type="submit" value="Save" />
</form>
<!-- Second form with your file -->
<form action="/uploadfile" method="post" id="form2" enctype="multipart/form-data">
<input type="file" name="fileupload" />
</form>
Then in Javascript (using jQuery example for brevity, note I haven't tested this code at all):
$('#form1').bind('submit', function() {
$.ajax({
url: $(this).attr('action'),
data: $(this).serialize(),
type: 'post',
success: function() {
$('#form2').submit();
}
});
return false;
});

Related

POST form data using AJAX and return object

I have created a form which has two inputs and a submit button. The form will post to a RESTful service which is all set up.
I want to use AJAX in order to POST to this RESTful service and then return the object so I can then validate the form.
The object will return something like this for an error and one similar for success
{"status":"error","message":"Incorrect username or password."}
My code is below. When i test I am using XAMPP on localhost:81. When I submit the form I receive this error.
No 'Access-Control-Allow-Origin' header is present on the requested resource.
<form name="login-form" id="login-form" method="post" action="SERVICEHERE">
<label id="error">Sorry it seems your credentials are incorrect</label>
<div class="inputBlock">
<label for="username">Username</label>
<input type="text" id="username" name="username"/>
</div>
<div class="inputBlock">
<label for="password">Password</label>
<input type="password" id="password" name="password"/>
</div>
<input type="submit" value="Login" id="submit" />
</form>
$(document).ready(function () {
$("#login-form").submit(function (e) {
e.preventDefault();
var formData = $("#login-form").serialize();
console.log(formData);
$.ajax({
type: "GET",
url: $("#login-form").attr('action'),
data: formData,
success: function(data) {
alert(data);
}
});
});
});
You can't post content to a different domain from javascript. It's not allowed for security reasons, and it is blocked by your browser.
When you execute an XmlHttpRequest by your webpage's javascript to another domain, your browser sets your domain name in the Origin header in your request. That target domain has to respond with a header called Access-Control-Allow-Origin containing your domain as well, meaning it allows your domain's clients to call it. Otherwise the browser will block the call.
Reference : https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
EDIT: There are ways to bypass the browser security and allow CORS all the time : https://www.thepolyglotdeveloper.com/2014/08/bypass-cors-errors-testing-apis-locally/

My .ajax call isn't working

I have a form on my website that pushes to my e-mail address. Previously before I wrote an ajax function the form would successfully push to my e-mail address. Only problem is when the user fills out the form it takes them to another page upon submitting the form. The HTML for my form is below.
<form id="contact" method="post" action="E-mail-form.php" name="EmailFromMyWebsite">
<label for="name">Name</label> <br>
<input type="text" name="name" class="required" placeholder="Your Name" title=" (Your name is required)"> <br />
<label for="email">E-mail</label> <br>
<input type="email" name="email" class="required email" placeholder="Name#email.com" title=" (Your email is required)"> <br />
<label for="message">Message/Comment</label> <br>
<textarea name="message" class="required" placeholder="Leave a brief message" title=" (Please leave me a brief message)"></textarea> <br />
<input type="submit" name="submit" id="submit" value="Send Message" />
</form>
</div><!-- /end #contact-form -->
The ajax call I wrote is...
$("#submit").on('click', function(){
var formData = $('#contact').serialize();
$.ajax({
type:"POST",
data:"formData",
url:"Email-form.php",
success: function(data){
$('#contact').html('<p>Your message has been sent</p>');
}
});
});
My javaScript console shows no errors so I think the problem is with my jQuery logic. On Chrome when I click submit I am redirected to my homepage. On Firefox the form submits but I am redirected to another page, therefore it is completely ignoring my AJAX call. Can someone with AJAX experience tell me what I'm doing wrong? Also I would love to attach a message if the call fails. Can I add 'failure:' and for the value put a function just like I did for success?
You have two issues
your form is submitting normally
you're attempting to post the wrong data
To prevent the form from submitting you can return false from the jQuery click handler or call preventDefault from the event object.
You are sending a string "formData" as the form data instead of the string in the formData variable
$("#submit").on('click', function(event){
var formData = $('#contact').serialize();
$.ajax({
type:"POST",
data:formData,
url:"Email-form.php",
success: function(data){
$('#contact').html('<p>Your message has been sent</p>');
}
});
event.preventDefault();
// or
return false;
});
There's a good chance that the normal form submit action is still taking place, even though you have an AJAX call as well. An easy fix for this may be to simply change the button type from submit to button. That way your click handler will still work, but it won't perform the default action of submitting the form on its own.
<input type="button" name="submit" id="submit" value="Send Message" />

How can Prevent Cross site request forgery via Ajax post?

I have a Form with AntiforgeryToken() value in Mvc project. while submiting the form, it validated with their corresponding controller Post action ValidateAntiforgeryToken in MvC project.
It goes to confirmation page. In the confirmation having two button which having hidden Form , this will go to same Post action in previous above.I have added Html.Antiforgerytoken() in that two hidden forms. while clicking the button, we don't need to Form Post[page reload], instead of this Using Ajax post.
I have tried using Ajax post (using Antiforgerytoken) but it does not hit Post action. Shows 404 error.
Can you please suggest how to enable AntiforgryToken using Ajax post? For that what type of code handle and where do it add?
Form details:
<form method="post" action="">
#Html.AntiForgeryToken()
<input type="hidden" name="Name" value="#downloadInfo.Name" />
<input type="hidden" name="Company" value="#downloadInfo.Company" />
<input type="hidden" name="Email" value="#downloadInfo.Email" />
<input type="hidden" name="Phone" value="#downloadInfo.Phone" />
</form>
Ajax Post:
$.ajax({
url: url,
type: 'POST',
data: JSON.stringify(Formdatas),
contentType: 'application/json; charset=utf-8',
beforeSend: showLoadingGraphic(id),
success: onSuccessfulPost
});
If you've received a 404 it's not from the token, you had an invalid URL or method.
You are including your token in your ajax form post, so look by using the tool Fiddler what URL is being requested and fix that first.
I'm guessing your Ajax call using 'URL' is incorrect
Try generating your form as it should (using the Html.BeginForm helper):
#using (Html.BeginForm("SomeAction", "SomeController", FormMethod.Post, new { id = "myForm" }))
{
#Html.AntiForgeryToken()
<input type="hidden" name="Name" value="#downloadInfo.Name" />
<input type="hidden" name="Company" value="#downloadInfo.Company" />
<input type="hidden" name="Email" value="#downloadInfo.Email" />
<input type="hidden" name="Phone" value="#downloadInfo.Phone" />
}
and then:
var myForm = $('#myForm');
$.ajax({
url: myForm.attr('action'),
type: myForm.attr('method'),
data: myForm.serialize(),
beforeSend: showLoadingGraphic(id),
success: onSuccessfulPost
});
Now the antiforgery token and the hidden fields will be properly sent to the server.

jQuery Mobile avoid changePage() in ajax form submit

I have a post form, I want the submit to be done in an AJAX way but I don't want the page URL to change.
For example:
<form action="/countries/change_country" data-ajax="true" method="post">
<select name="country_code">
<option value="FR" selected="selected">France</option>
<option value="DE">Germany</option>
</select>
<input type="submit" value="change country" />
</form>
When I click in the change country button the form is sent through AJAX what is nice but the page URL is changed to /countries/change_country what is not nice because this URL doesn't exist in my server which is very picky with HTTP verbs.
I know it is possible to change this default behavior for the whole application but I would like to deactivate the changePage() only for this form.
Submit the form through Javascript/jQuery instead.
First: Disable the default submit-behaviour
$('#form').on('submit', function (e) {
if (e.preventDefault) e.preventDefault();
return false;
});
Second: Serialize the form data with jQuery
var serializedFormData = $('#form').serialize();
Third: Post your form with $.ajax();
$.ajax({
url: '/countries/change_country',
type: 'POST',
data: serializedFormData
});

jQuery mobile, login page reload needed for ajax to work

I have a simple "login" form and ajax is working. But every time I load the page freshly in new tab, and "login" page loads, I input the username and password, press "login" button and for some reason page just reloads, but on the reloaded page when I press "login" button, ajax works just fine. Anyone know what does this mean?
Here is simple login form:
<form id="login_form" name="login_form" data-ajax="false">
<label for="basic">Username:</label>
<input type="text" name="usr" id="usr" value=""/>
<label for="basic">Password:</label>
<input type="password" name="psw" id="psw" value=""/>
<input type="submit" value="Login" id="login" name="login"/>
<label><input type="checkbox" name="remember_me" id="remember_me" value="checked_remember"/>Remember me!</label>
</form>
<div id="login_message"></div>
And here is my ajax script:
$(document).ready(function(){
$("#login").click(function(){
username=$("#usr").val();
password=$("#psw").val();
$.ajax({
type: "POST",
url: "http://imes.jzpersonal.com/php/login_check.php",
data: "name="+username+"&pwd="+password,
success: function(html){
if(html=='true')
{
$("#login_message").html("Logged in, congratulation.");
}
else
{
$("#login_message").html("Wrong username or password");
}
},
beforeSend:function()
{
$("#login_message").html("Loading...")
}
});
return false;
});
});
Also I'm using POST method but I still get address in address bar like this:
http://imes.**********.com/login_page.php?usr=Jakub&psw=********&login=Login
Is this an jQueryMobile thing?
Reason for this is you cant use $(document).ready(function(){ with jQuery Mobile. You should use :
$(document).on('pageinit'){
});
or if your page has an id then use it like this:
$('#page_id').on('pageinit'){
});
More info about this problem can be found here: http://jquerymobile.com/test/docs/api/events.html
Read this article to find more about this and jQM page events: https://stackoverflow.com/a/14010308/1848600

Resources