I am trying to submit a form and send the data to my php function with Ajax. The problem is that, When I send data without ajax call and just using form action, My form validation works, but when I want to use Ajax, Form will be submitted without being validated. Here is my code:
html:
<form novalidate="" class="form-horizontal">
<div class="control-group">
<label for="email" class="control-label">Email address</label>
<div class="controls">
<input type="email" required="" id="email" name="email">
<p class="help-block">Email address we can contact you on</p>
</div>
</div>
<div class="control-group">
<label for="emailAgain" class="control-label">Email again</label>
<div class="controls">
<input type="email" name="emailAgain" id="emailAgain" data-validation-matches-message="Must match email address entered above" data-validation-matches-match="email">
<p class="help-block">And again, to check for speeling miskates</p>
</div>
</div>
<button id="button" class="button" type="submit" name="submit">Check your
</form>
Ajax:
$(document).ready(function () {
$(function () {
$("#button").click(function () {
$('.error').hide();
// Process form
var email = $("input#email").val();
var emailagain= $("input#emailagain").val();
var dataString = 'email=' + email + '&emailagain=' + emailagain;
$.ajax({
type: "POST",
url: "send_email.php",
data: dataString,
success: function (data) {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("Thank you ")
});
}
});
return false;
});
});
});
I also tried submitHandler: function(form){} with Ajax call, but in that case, my success function in Ajax call won't work and it seems that the data will be sent through GET method instead of POST! weird!!! Thanks in advanced!
Ok you have a submit button and on clicking this you are doing some ajax, so you need to use event.preventDefault()
Here how the code should be and it should work, also check for any syntax error in your code. Below is the code I just tested and worked on my linux box.
<script>
$(document).ready(function () {
$(function () {
$("#button").click(function (x) {
x.preventDefault(); // lets stop the default behaviour which is submit
$('.error').hide();
// Process form
var email = $("input#email").val();
var emailagain= $("input#emailagain").val();
var dataString = 'email=' + email + '&emailagain=' + emailagain;
$.ajax({
type: "POST",
url: "send_email.php",
data: dataString,
success: function (data) {
$('#contact_form').html("<div id='message'></div>");
$('#message').html("Thank you ");
}
});
});
return false;
});
});
</script>
Related
I'm new to ajax/jquery. I want to use sweetalert on my website, i set it up as in tutorial, but when i open modal form and click send button, it goes to another page, page send.php.
Here my form:
<form id="contactForm1" action="send.php" method="post">
<div class="field-block">
<label for="text">Message1</label>
<textarea id="message1" class="field" required name="message1" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message2</label>
<textarea id="message2" class="field" required name="message2" rows="4" placeholder=""></textarea>
</div>
<div class="field-block">
<label for="text">Message3</label>
<textarea id="message3" class="field" required name="message3" rows="4" placeholder=""></textarea>
</div>
<button id="button" class="button" type="submit">Отправить</button>
<div class="result">
<span id="answer"></span>
<span id="loader"><img src="images/loader.gif" alt=""></span>
</div>
</form>
inside this form sweetalert doesn't work, but outside of form it's working.
Here sweetalert jquery and ajax request:
<script>
$("#contactForm1").on('submit',function(event) {
event.preventDefault(); // to prevent default page reloading
var dataString = $(this).serialize(); // to get the form data
$.ajax({
type: "POST",
url: "send.php",
data: dataString,
success: function(data){
$('#contactForm1')[0].reset(); // to reset form data
}
}).done(function(data){
setTimeout(function () {
Swal.fire(
'Thank you!',
'Your request has been accepted!',
)
}, 2000);
});
});
</script>
what could be the problem? Please help
The problem is you're not sending request with AJAX.
Solution:
First remove action="send.php" from your form
then add this to your script.
<script>
$('.button').click(function(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
}).then((value) => {
<!-- When the user click submit send Ajax request -->
$.ajax({
url: "send.php",
method: "POST",
data:{
message1: $(#message1).val(),
message2: $(#message2).val(),
message3: $(#message3).val()
},
success: function(data)
{
// some actions
}
});
});
});
</script>
You can send it without ajax request also try this change
$('.button').click(function(){
to
function submitForm(){
your function will look like this:
function submitForm(){
swal({
title:"Red Stapler",
text: "Are You Sure?",
buttons: {
cancel: true,
confirm: "Submit"
}
});
}
Now in the form add
onsubmit="return submitForm()"
swal({ title: "Done", text: "Record updated successfully!", type: "success" }, function () {location.reload();});
Simply use this line code, it will automatically hide alert and reload the page when click "OK".
Please I am new to jQuery so i just copied the code:
<div id="container">
<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
And here is the php code:
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
}
?>
Its Working perfectly but now i want to have more than one input field like this:
<input type="text" id="name" >
<input type="text" id="job">
but i don't know how to run the jQuery code for the 2 input fields so that it can transfer them to the php page. Please i need help
You can pass multiple values using data param of ajax request like this.
$.ajax({
method: "POST",
url: "action.php",
data: {
name: $('#name').val(),
job: $('#job').val()
},
success: function(status) {
$('#result').append(status);
$('#name, #job').val(''); // Reset value of both fields
}
});
You need to change your code with some addition in html and JS.
Wrap your inputs in form tag. and add a preventDefault on submit.
Use jQuery .serialize() method
and event.preventDefault()
event.preventDefault() : If this method is called, the default
action of the event will not be triggered. (it will prevent page
reload / redirection) to any page.
.serialize() : Encode a set of form elements as a string for
submission.
serialized string output will be like key=value pair with & separated. :
name=john&job=developer.....
HTML
<form id="myform">
<input type="text" id="name" placeholder="Type here and press submit">
<input type="text" id="job" placeholder="Type here and press submit">
<input type="submit" name="submit" value="Submit Form">
</form>
JS
$(document).ready(function() {
$('#myform').submit(function(event) {
event.preventDefault();
var serialized = $('#myform').serialize();
$.ajax({
method: "POST",
url: "action.php",
data: serialized,
success: function(status) {
$('#result').append(status);
$('#myform').reset();
}
});
});
});
I've been scanning my code over and over again but I can't seem to find the problem.
When I click the link #add-user-btn the file actions.php is called twice (and hence the PHP script is executed twice).
Here's the script: I suppose it has something to do with the javascript in front of the ajax request?
$(function () {
$("#add-user-btn").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var name = $("#name").val();
var action = "adduser";
$.ajax({
url: '../actions.php',
type: 'POST',
data: {
action: action,
email: email,
name: name,
},
dataType: 'json',
success: function (data) {
$(".close-reveal-modal").click();
}
});
});
});
The HTML:
<div id="adduser" class="reveal-modal">
<h1>Add new user</h1>
<p><label for="email">E-mail:</label> <input id="email" name="email" type="text" placeholder="name#example.com" /></p>
<p><label for="name">Name:</label> <input id="name" name="name" type="text" placeholder="Adam Smith"/></p>
<p><label for="password">Password:</label> <input id="password" name="password" type="password" placeholder="123456" /></p>
<p>
<label for="authorization">Authorization:</label>
<select id="authorization" name="authorization">
<option value="0">Administrator</option>
<option value="1">Superuser</option>
<option value="2">User</option>
</select>
</p>
<button id="add-user-btn">Submit</button>
<a class="close-reveal-modal">×</a>
</div>
Try
$("#add-user-btn").unbind('click').bind('click', function () { });
This will ensure the click event only gets called once.
This problem also occurs when you include multiple times the same JavaScript file in your HTML file.
<html>
<head>
<script src="utility.js"></script>
<script src="utility.js"></script>
</head>
When I worked with an specific website that I only had access to my javascript, I got this kind of error too. The problem was that there was lots of $(function() and $(document).ready in other codes.
what you can do to prevent this, if you can't correct the core problem is:
var preventRunDefault;
$(function () {
if(!preventRunDefault) {
preventRunDefault = true;
$("#add-user-btn").click(function (e) {
e.preventDefault();
var email = $("#email").val();
var name = $("#name").val();
var action = "adduser";
$.ajax({
url: '../actions.php',
type: 'POST',
data: {
action: action,
email: email,
name: name,
},
dataType: 'json',
success: function (data) {
$(".close-reveal-modal").click();
}
});
});
}
});
But the right way is to search the cause and don't do workarounds.
I am trying to save data submitted from a form into my mysql database and and then update the div element with the last posted item prepended to the list in the div.
Right now I am only trying to get a response back, I'm not worried about having the formatting correct at the moment.
My problem is the form won't submit with e.preventDefault(); in place, but without it the form does the normal method of posting to the db then refreshing the page.
Here is my AJAX call:
$(document).ready(function() {
$('form#feedInput').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $('.feed-input').val(),
dataType: "html",
success: function(data){
debugger;
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
});
I don't think it's necessary for me to post my controller code, seeing as how my issue is the form won't make it past the e.preventDefault(); function.
How can I get this form to submit via AJAX if the e.preventDefault() function is stopping it before it can reach the $.ajax() function?
The data attribute of the ajax call is invalid. It should be either in JSON format { key: $('.feed-input').val() } or in query format 'key='+$('.feed-input').val().
Also there is an unnecessary debugger variable in the success method.
A working code could be:
$('form#feedInput').submit(function(e) {
var form = $(this);
e.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: form.serialize(), // <--- THIS IS THE CHANGE
dataType: "html",
success: function(data){
$('#feed-container').prepend(data);
},
error: function() { alert("Error posting feed."); }
});
});
Html part in view
<form id="comment" method="post">
<h2>Enter Your Details</h2>
<center><div id="result"></div></center>
<div class="form_fld">
<label>Name</label>
<input type="text" placeholder="Enter Your Full Name" name="name" required="">
</div>
<div class="form_fld">
<label>Email ID</label>
<input type="text" placeholder="Enter Email ID" name="email" required="">
</div>
<div class="form_fld">
<label>Contact Number</label>
<input type="text" placeholder="Enter Contact Number" name="contact" required="">
</div>
<div class="form_fld">
<label>Developer</label>
<select name="developer">
<option>Lotus</option>
<option>Ekta</option>
<option>Proviso</option>
<option>Dosti</option>
<option>All</option>
</select>
</div>
<div class="form_fld">
<button type="submit" id="send">Submit</button>
</div>
</form>
After Html Part Just put ajax request
<script type="text/javascript" src="<?php echo base_url('assets/'); ?>js/jquery.js"></script>
<script>
$(function(){
$("#comment").submit(function(){
dataString = $("#comment").serialize();
$.ajax({
type: "POST",
url: "home/contact",
data: dataString,
success: function(data){
// alert('Successful!');
$("#result").html('Successfully updated record!');
$("#result").addClass("alert alert-success");
}
});
return false; //stop the actual form post !important!
});
});
</script>
Within Controller
public function contact()
{
$ip = $_SERVER['REMOTE_ADDR'];
$data = array('name' => $this->input->post('name'),
'email' => $this->input->post('email'),
'number' => $this->input->post('contact'),
'developer' => $this->input->post('developer'),
'ip' => $ip,
'date' => date("d/m/Y"));
$result = $this->User_model->contact($data);
print_r($result);
}
You don't have to use preventDefault(); you can use return false; in the end of function submit() but I doubt this is the problem.
You should also use url encoding on $('.feed-input').val() use encodeURIComponent for this.
You should also check if you have errors in your console.
To determine if default action is prevented you can use e.isDefaultPrevented(). By default action in this case I mean submit action of the form with id feedInput.
You didn't name your param in data. Check jquery ajax examples.
You are probably getting an error e.preventDefault(); is not stopping the ajax.
$.ajax({
type: "POST",
url: "<?php echo site_url('dashboard/post_feed_item'); ?>",
data: $("#form").serializeArray(),
success: function(resp){
$('#container').html(resp);
},
error: function(resp) { alert(JSON.stringify(resp)); }
});
Please I am trying to simultaneously submit and validate my form to my database through the use of Ajax, but it is not working for me.
Here is my jquery
$(document).ready(function(){
$(".button").click(function(){
$("#myform").validate();
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: { firstname: $("#firstname").val()},
success: function(){
$('#message').html(data);
}
});
return false;
});
});
The problem is when I submit the form,the Ajax form submit to itself.
Please What is the right way to use the jquery validate and $.ajax together?
Pass data as a parameter in your success function:
success: function(data){
Your success function won't do anything because you haven't defined data
Try this (working for me as expected):
HTML Form:
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script>
// JQuery Script to submit Form
$(document).ready(function () {
$("#commentForm").validate({
submitHandler : function () {
// your function if, validate is success
$.ajax({
type : "POST",
url : "process.php",
data : $('#commentForm').serialize(),
success : function (data) {
$('#message').html(data);
}
});
}
});
});
</script>
<form class="cmxform" id="commentForm" method="get" action="">
<fieldset>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required />
<p>
<label for="cemail">E-Mail (required)</label>
<input id="cemail" type="email" name="email" required />
</p>
<p>
<label for="curl">URL (optional)</label>
<input id="curl" type="url" name="url" />
</p>
<p>
<label for="ccomment">Your comment (required)</label>
<textarea id="ccomment" name="comment" required></textarea>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
<div id="message"></div>
PHP Code:
<?php
echo $_POST['email'];
?>
You forget to pass the response
$(document).ready(function() {
$(".button").click(function() {
//check the validation like this
if ($("#myform").valid()) {
//Ajax to process the form
$.ajax({
type: "POST",
url: "process.php",
data: {
firstname: $("#firstname").val()
},
//you forget to passs the response
success: function(response) {
$('#message').html(response);
}
});
return false;
}
});
});
First of all, why would you submit form if validation is not passed?
Try this, if validate really validates:
$(function(){
$(".button").click(function(){
var myform = $("#myform");
if (myform.validate()) {
$.post("process.php", myform.serialize(), function(data){
$('#message').html(data);
});
}
return false;
});
});