Unable to serialize both the forms at once using jquery ajax - php

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?

Related

Fetching JSON from form data

I am writing a code to fetch JSON parameter sent using form.
I have this html
<form action="jsonfile.php" method="POST" name="myForm" enctype="application/json">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>
<input value="Submit" type="submit" onclick="submitform()">
</form>
And json here
<script>
var formData = JSON.stringify($("#myForm").serializeArray());
$.ajax({
type: "POST",
url: "jsonfile.php",
data: formData,
dataType: "json",
contentType : "application/json",
success: function(result){
}
});
</script>
NOW, i want get the values of the above form sent as json in the other file called JSONFILE.PHP. I don't really know what should i use to decord the data into JSON DATA.
Thank you.
// HTML Code
<form method="POST" name="myForm" id="myForm" enctype="application/json" onsubmit="return false">
<p><label for="first_name">First Name:</label>
<input type="text" name="first_name" id="fname"></p>
<p><label for="last_name">Last Name:</label>
<input type="text" name="last_name" id="lname"></p>
<input value="Submit" type="submit" >
</form>
// JavaScript Code
<script>
$("#myForm").submit(function () {
var formData = JSON.stringify($("#myForm").serializeArray());
$.ajax({
type: "POST",
url: "jsonfile.php",
data: formData,
dataType: "json",
contentType: "application/json",
success: function (result) {
}
});
});
</script>
// PHP Code jsonfile.php
<?php
$data = json_decode(file_get_contents('php://input'), true);
if ($data) {
print_r($data);
}
?>

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

jQuery form validation with ajax submit in CodeIgniter

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>

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/

Form submit without refresh using jquery/ajax if page have more than one form

Hi all I know that its very easy to submit a form without refreshing if there is only one form on the page but what about if there are more than one form on the page. Im using the following code for form submission and it works ok if there is only one form on the page. How can I change it to make it work when there are multiple forms on the page. Thanks in advance.
function processForm() {
$.ajax( {
type: 'POST',
url: form_process.php,
data: 'user_name=' + encodeURIComponent(document.getElementById('user_name').value),
success: function(data) {
$('#message').html(data);
}
} );
}
<form action="" method="post" onsubmit="processForm();return false;">
<input type='text' name='user_name' id='user_name' value='' />
<input type='submit' name='submit' value='submit'/>
</form>
<div id='message'></div>
Just customize your function and add params like formid to get form data within the function to pass processForm("id of the form");
function processForm(formId) {
//your validation code
$.ajax( {
type: 'POST',
url: form_process.php,
data: $("#"+formId).serialize(),
success: function(data) {
$('#message').html(data);
}
} );
}
<form action="" id="form1" method="post" onsubmit="processForm('form1');return false;">
<input type='text' name='user_name' id='user_name' value='' />
<input type='submit' name='submit' value='submit'/>
</form>
<form action="" id="form2" method="post" onsubmit="processForm('form2');return false;">
<input type='text' name='user_name' id='user_name' value='' />
<input type='submit' name='submit' value='submit'/>
</form>
<form action="" id="form3" method="post" onsubmit="processForm('form3');return false;">
<input type='text' name='user_name' id='user_name' value='' />
<input type='submit' name='submit' value='submit'/>
</form>
<div id='message'></div>
What you have should work on multiple forms, however it would be better and a lot easier to debug if apply the event listener using jQuery instead:
$('form').submit(processForm); // listen to each form’s submit
function processForm(e) {
e.preventDefault(); // prevents default submit action
$.ajax( {
type: 'POST',
url: form_process.php,
data: 'user_name=' + encodeURIComponent(document.getElementById('user_name').value),
success: function(data) {
$('#message').html(data);
}
} );
}
HTML (without the ugly onsubmit attribute):
<form action="" method="post">
<input type='text' name='user_name' id='user_name' value='' />
<input type='submit' name='submit' value='submit'/>
</form>
Add form_id while calling processForm(form_id) and using the id serialize the form.
function processForm(form) {
$.ajax( {
type: 'POST',
url: form_process.php,
data: $(form).serialize(),
success: function(data) {
$('#message').html(data);
}
} );
return false;
}
<form action="" method="post" onsubmit="processForm(this)">
<input type="text" name="user_name" id="user_name1" value="">
<input type="submit" name="submit" value="submit" >
</form>
<form action="" method="post" onsubmit="processForm(this)">
<input type="text" name="user_name" id="user_name2" value="">
<input type="submit" name="submit" value="submit" >
</form>
<div id='message'></div>
jsFiddle
just thought I'd add to this, if you have multiple forms on one page, you can set a function to act on all forms independently by getting the form's action value. As follows (tested with jQuery 1.8.3):
$('form').submit(function(){
var action = $(this).attr("action")
$.ajax({
url: action,
type:'POST',
data: $(this).serialize(),
success: function(){
//alert message
}
})
return false
})
Hope this helps someone out!

Categories