My .ajax call isn't working - ajax

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" />

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/

Jquery Mobile - search input has no value on post after AJAX loaded content

I am having an issue where when a page is loaded via Ajax, I don't have a value in my search input. Here is my HTML:
<form id="searchForm" action="javascript:;" method="post">
<div>
<input type="search" name="search-mini" id="search-mini" value="" data-mini="true" />
<input type="submit" data-mini="true" value="Search" />
</div>
</form>
The reason we have an input button is because of a request from the client as they found people having scenarios where they would click "Done" on the IOS keyboard rather than "Search" which wouldn't submit the form. here is my Javascript that handles the submit:
$(document).on('submit', '#searchForm', function () {
var text = $("#search-mini").val();
text = encodeURIComponent(text);
window.location.href = "/Mobile/Browse/Text?text=" + text;
return true;
});
This all runs fine if I refresh the page so the content is not loaded via AJAX. It only fails when linking between pages and they are loaded by AJAX. Alerting out "text" has a blank value in this scenario.
I have read about using JQM initialization events such as 'PageInit' instead of DOM ready() I just need an example implementing this with my code if this is the correct approach?
Regards,
Danny

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

Make form use ajax

I am having issue making a form be sent using ajax.
Here is my code:
<form id="form" method="get">
<input type="text" name="name" id="name"><br>
<input type="text" name="email" name="email"><br>
<input type="submit" id="submit" value="submit">
</form>
$('#submit').click(function(event){
alert('ajax');
});
The "ajax" alert shows, but then the page gets reloaded! How can I stop this behaviour?
You have to use preventDefault
$('#submit').click(function(event){
event.preventDefault();
alert('ajax');
});
use $.submit() instead of click :)
$('#form').submit(function(event){
alert('ajax');
// here some ajax functions for sending via get or post ;)
return false; // this stops loading the action site.. its something like e.preventDefault() on links
});

AJAX call then page redirect

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;
});

Resources