jQuery form validation with ajax submit in CodeIgniter - php

I am trying to create a contact form with CI and I am having problem with jQuery triggering HTML5 validation, my form is
<form id="contact_form" name="contact_form">
<INPUT id="name" class="medium user" name="name" type="text" required>
<input type="submit" name="submit_btn" id="submit_btn" value="Send Message">
</form>
with this html validation is working fine but when I try to submit form with Ajax using bellow code, validation stop working and form submitted without validation
$(document).ready(function($){
$("#submit_btn").click(function(){
var response = $.ajax({
type: "POST",
url: "send_email.php",
data: $(contact_form).serialize()
}).done(function( msg ) {
$('#commentForm').html('<h5>Thanks</h5>'+msg);
});
return false;
});
});
how to validate form with ajax form submission?
Thanks

Use submit method instead of click if you want to validate the form and submit ajax.
$(document).ready(function($) {
$("#contact_form").submit(function() {
alert('form submitted');
var response = $.ajax({
type: "POST",
url: "send_email.php",
data: $("#contact_form").serialize()
}).done(function(msg) {
$('#commentForm').html('<h5>Thanks</h5>' + msg);
});
return false;
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="contact_form" name="contact_form">
<INPUT id="name" class="medium user" name="name" type="text" required>
<input type="submit" name="submit_btn" id="submit_btn" value="Send Message">
</form>

Related

Submitting form and posting to php script without reloading

I am trying to submit a form to a my PHP script that uses phpmailer to send emails. I am using a. ajax call to run the PHP script without refreshing but when I click the submit button all it does is refresh the page. Thank you.
Below is my form script
<form method="POST" name="form" onsubmit="return chk()">
<fieldset>
<p><input type="text" name="name" placeholder="NAME" class="field"></p>
<p><input type="email" name="email" placeholder="EMAIL" class="field"></p>
<p><textarea cols="2" name="msg" rows="2" placeholder="MESSAGE"></textarea></p>
<p><input type="submit" class="button" onclick="return chk()"></p>
</fieldset>
</form>
Below is the ajax call. Its my first time using ajax so it may be wrong.
<script type="text/javascript">
function chk()
{
e.preventDefault();
var name=document.getElementById('name').value;
var email=document.getElementById('email').value;
var msg=document.getElementById('msg').value;
var dataString='name='+name+'&email='+email+'&msg='+msg;
$.ajax({
type:"post",
url:"mail.php",
data: dataString,
cache:false,
success: function(html) {
'Email Sent'
}
});
return false
}
</script>
To use .preventDefault() from a function you need to pass event as an argument
function chk(e){ //<<<<<<< here chk(e) while you're using e.preventDefault() if its somethingelse.preventDefault() so it should be chk(somethingelse)
e.preventDefault();
console.log('Not refreshed');
//return false; no need for it here.. return false here will work for a function not for the submit/click event so it will not prevent the default action in this case you've to use `preventDefault()`
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form onsubmit="chk(event)"> <!-- ck(event) -->
<input type="submit" value="submit"> <!-- No need for onclick here -->
</form>
You can forget about the function and use the submit event directly .. no need to use onsubmit/onclick
$(document).ready(function(){
$("form[name='form']").on('submit' , function(e){
e.preventDefault();
console.log('Not refreshed');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form method="POST" name="form">
<fieldset>
<p><input type="text" name="name" placeholder="NAME" class="field"></p>
<p><input type="email" name="email" placeholder="EMAIL" class="field"></p>
<p><textarea cols="2" name="msg" rows="2" placeholder="MESSAGE"></textarea></p>
<p><input type="submit" class="button"></p>
</fieldset>
</form>

Unable to serialize both the forms at once using jquery ajax

I have two form, first form input text, and file upload, the second form contains only text fields,
Here first is shown and the second form is hidden on the first and second form is shown and the first form is hidden, on submitting the second form, I want to combine two forms and submit the data by using ajax,
<form id="data" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<button>Submit</button>
</form>
<form action="conn.php" method="POST" id="request-form2" enctype="multipart/form-data">
<input type="text" name="full_name2">
<br/>
<input type="text" name="last_name2">
<br/>
<input type="submit" value="submit" name="submit">
</form>
Here is script, i have tried,
$('form#request-form2').click(function(event) {
event.preventDefault();
var formData2 = $('#data');
var formData = new FormData(formData2);
console.log(formData);
$.ajax({
url: 'conn.php',
type: 'POST',
data: formData,
success: function (data) {
// console.log(data)
},
cache: false,
contentType: false,
processData: false
});
});
Haven't tested this, but why couldn't you just:
var formData=$('#data').serializeArray();
var formData2=$('#request-form2').serializeArray();
formData.push(formData2);
and include formData in your data option of your ajax call?

PHP not getting $_POST from ajax post

I'm trying to post data to the same page.
I can see that the post from the ajax is working correctly but the $_POST in my index.php isn't finding the post after form submission.
<form method="post" id="classic_login" action="">
<input type="text" name="user" placeholder="Username" class="classic_field" id="user_field" />
<input type="text" name="pass" placeholder="Password" class="classic_field" id="pass_field" />
<input type="submit" name="login" value="Login" class="classic_button" id="login_button" />
<input type="submit" name="register" value="Register" class="classic_button" id="register_button" />
</form>
and I've tried both print_r($_POST) and isset both don't change after submission
print_r($_POST);
if(isset($_POST['user']) && isset($_POST['pass']))
echo "works";
printing formdata after a test submission i get: user=testuser&pass=testpass
$("#classic_login").submit(function(event) {
var formdata = $(this).serialize();
event.preventDefault();
$.ajax
({
url: "",
type: 'POST',
data: formdata,
//success: function(response) { alert(response); },
error: function() { alert("fail"); }
});
});
Alternatively, you could use document.URL to make a request on the same page. Then in PHP, include an exit; after the request:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo '<pre>';
print_r($_POST);
exit; // this is important!
}
?>
<form method="post" id="classic_login" action="">
<input type="text" name="user" placeholder="Username" class="classic_field" id="user_field" />
<input type="text" name="pass" placeholder="Password" class="classic_field" id="pass_field" />
<input type="submit" name="login" value="Login" class="classic_button" id="login_button" />
<input type="submit" name="register" value="Register" class="classic_button" id="register_button" />
</form>
<!-- this is no brainer, of course you need to load the library -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("#classic_login").submit(function(event) {
var formdata = $(this).serialize();
event.preventDefault();
$.ajax({
url: document.URL, // you can use this
type: 'POST',
data: formdata,
success: function(response) {
alert(response);
}
});
});
</script>
Sample Output

Modal form Submission to PHP using Jquery .ajax

I am trying to post a modal form to a table using php, jquery .ajax but it never works.. tried debugging using firebug and i don't see any errors. i tested the form by using form action="notes_functions.php" and it worked fine.
Profile.php
<div class="modal-body">
<form class="noteform" id="notesmodal" method="post">
<fieldset>
<label>Title</label>
<input type="text" class="form-control" name="note_title" placeholder="Enter a title for your note">
<label>Note</label>
<textarea rows="4" cols="50" class="form-control" name="note_content" placeholder="note"></textarea>
<label>Note type</label>
<div class="panel-body">
<input type="tagsinput" id="teetete" class="tagsinput" value="" />
</div>
<label for="exampleInputFile">Attach a document</label>
<input type="file" id="exampleInputFile3">
<p class="help-block">PDF, DOCX and image files are supported.</p>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
<input type="label" name="note_account" value="<?php echo $acctname ?>"/>
</label>
</div>
<input type="hidden" name="note_creator" value="<?php echo $_SESSION['username'];?>"/>
</fieldset>
<button class="btn btn-default" id="submitnote" >ADD</button>
</form>
</div>
this is my js code
$(function(){
$("button#submitnote").click(function(){
$.ajax ({
type:"POST",
url:"notes_functions.php",
data: $('form.noteform').serialize(),
success: function(msg){
$("#thanks").html(msg)
$("form.noteform").modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
notes_functions.php
<?php
include_once 'dbconnect.php';
if (isset($_POST['note_title'])) {
$notetitle = strip_tags($_POST['note_title']);
$noteContent = strip_tags($_POST['note_content']);
$noteAccount = strip_tags($_POST['note_account']);
$noteCreator = strip_tags($_POST['note_creator']);
mysql_query("INSERT INTO account_notes (note_title, note_contents, note_account, note_creator)
VALUES ('$notetitle','$noteContent', '$noteAccount', '$noteCreator') ");
echo "Name = ".$notetitle;
echo $noteCreator;
}
?>
You should really be using .submit() rather than click (for submit-by-enter, etc.) and returning false to block conventional submits. You also need to make sure the code to bind the events runs after the form element is created. The easiest way to do this is to put it in the document ready handler.
jQuery(document).ready(function ($) {
$("#notesmodal").submit(function () {
$.ajax({
type: "POST",
url: "notes_functions.php",
data: $('form.noteform').serialize(),
success: function (msg) {
$("#thanks").html(msg)
$("form.noteform").modal('hide');
},
error: function () {
alert("failure");
}
});
return false;
});
});
And change the ADD button to be:
<input type="submit" name="submit" class="btn btn-default" id="submitnote" value="ADD" />

Form Cross domain POST request using PHP

I am trying to send data from a form to a php file so I can store it in a database, but its not working...
The code for the form is not on the same server as the php file, because the form will be on a mobile app.
html
<div data-role="page" id="createclub">
<div data-role="content">
<form id="cname" align="left" action="post">
<label for="name">Enter Name:</label>
<input type="text" id="name" value="" />
<input type="submit" value="Submit" data-inline="true">
</form>
<div id="result"></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#cname").submit( function () {
$.post(
'http://www.clubbedin.isadcharity.org/createclub.php',
$("#cname").serialize(),
function(data){
$("#result").html(data);
alert("Data " + data);
}
);
return false;
});
});
</script>
php file
$name = $_POST['name'];
THANK YOU!!!
Add this at the beginning of your PHP file:
header("access-control-allow-origin: *");
More info on cross domain policy here.
I think you need to prevent the default function of the submit button using .preventDefault() because as I look on your code you want to submit your form using ajax
$("#cname").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.clubbedin.isadcharity.org/createclub.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#cname").serialize(),
success: function (data) {
$("#result").html(data);
alert("Data " + data);
},
});
});
and please use .ajax() so that you can set your ajax request to a cross-domain request
http://api.jquery.com/jQuery.ajax/
Your input element <input type="text" id="name" value="" /> must set up the name attribute as name="name".
form #cname after edited
<form id="cname" align="left" action="post">
<label for="name">Enter Name:</label>
<input type="text" id="name" name="name" value="" />
<input type="submit" value="Submit" data-inline="true">
</form>
You can gather more informations from the jQuery API Documention:
http://api.jquery.com/
http://api.jquery.com/serialize/

Categories