This question already has answers here:
jQuery AJAX submit form
(20 answers)
Closed 8 years ago.
Good day im am trying to send or get data from a form and then using jquery and then ajax to send the data into a php page that should save it in the database how can i do it in jquery and use ajax to do it, any help will do and thanks!
HTML page 1 that will use jquery ajax to send data into the php page
<form>
Name:<input type='text' name='name'>
E-mail:<input type='text' name='email'>
Gender:<select name='gender'>
<option value='male'>male</option>
<option value='female'>female</option>
</select>
Message:<textarea name='about'></textarea>
</form>
PHP page 2 that would recieve the data from the page 1 form
<?php
echo "
$_POST['name'];
$_POST['email'];
$_POST['gender'];
$_POST['about'];
";
?>
any help with this project would help us greatly and thanks!
(update)
This is the jquery that i tried to use but it went to the url and i think that is not very safe
$(document).ready(function(){
$("#chat").click(function(){
$("#content").load("a.php");
});
$("#send").ajaxSubmit({url: 'a2.php', type: 'post'})
});
you can use following code :
var form = new FormData($('#form_step4')[0]);
form.append('view_type','addtemplate');
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
where savedata.php is the file name in which you can do the the DB things
Hi i would start by adding a id to the form. and then either go with a onclick on the button element, or just define a click-event-handler for the button.
<form id="my_form">
Name:<input type='text' name='name'>
E-mail:<input type='text' name='email'>
Gender:<select name='gender'>
<option value='male'>male</option>
<option value='female'>female</option>
</select>
Message:<textarea name='about'></textarea>
<input type="button" value="Send" onclick="sendForm()"/>
</form>
Then the jquery/ajax/js part.
function sendForm(){
$.ajax({
type: "POST",
url: "PAGE2.php",
data: jQuery("#my_form").serialize(),
cache: false,
success: function(data){
/* alert(data); if json obj. alert(JSON.stringify(data));*/
}
});
}
Try this one:
<form id="formId">
Name:<input type='text' name='name'>
E-mail:<input type='text' name='email'>
Gender:<select name='gender'>
<option value='male'>male</option>
<option value='female'>female</option>
</select>
Message:<textarea name='about'></textarea>
<input type="button" value="Send" onclick="save()"/>
</form>
<script type="javascript">
function save(){
var query = $('#formId').serialize();
var url = 'savedata.php';
$.post(url, query, function (response) {
alert (response);
});
}
</script>
assign Id to your form... for now in my code i have given ID formId.. you can change this one as per your form name.
Related
I am struggling to have multiple AJAX submitted forms on the same php page. I can get it to work with one, but when I add more, it just uses the first form all the time.
I have tried to make it unique but not sure exactly how to do this.
My code is below, if someone could please assist that would be fantastic.
I have looked at similar questions and answers on this site but can't seem to fathom how to make it work for mine.
The form should submit when the checkbox is checked or unchecked.
Thanks very much in advance for all your help.
Martyn.
HTML form
<form id="search_form" method="post">
<input readonly type="text" name="id" value=<?php echo $row1[0];?>>
<input readonly type="text" name="student" value=<?php echo $row1[1];?>>
<input readonly type="text" name="addedby" value=<?php echo $_SESSION['username'];?>>
<input readonly type="text" name="register" value="monday_morning">
<input <?php if($row1[4] == "Yes"){echo "checked";}?> type="checkbox" name="box" value="Yes">
</form>
Script
<script type="text/javascript">
$(document).on("change", '[type="checkbox"]', function () {
var url = "/register_update.php";
$.ajax({
dataType: "html",
type: "POST",
url: url,
data: $("#search_form").serialize(),
success: function (data) {
}
});
return false;
});
</script>
Try this
<script type="text/javascript">
$(document).on("change", '[type="checkbox"]', function (event) {
var url = "/register_update.php";
$.ajax({
dataType: "html",
type: "POST",
url: url,
data: $($(event.target).parent()).serialize(),
success: function (data) {
}
});
return false;
});
</script>
event.target returns the clicked checkbox.
parent() function returns the form you need to submit. This way you don't need to have unique form id.
I am trying to upload a file using jquery. Here's the form:
<form id="upload_data" class="project" enctype="multipart/form-data" method="POST">
<select id="project_id" name="project_id">
<option value="1">1</option>
<option value="2">2</option>
</select>
<input type="file" id="data" name="data" />
<input type="hidden" name="user_id" id="user_id" value="12" required>
<button type="submit" id="ajax" class="btn btn-primary">Submit</button>
</form>
Here's the jquery part:
$('#upload_data').submit( function( e ) {
var form = $('form');
var formData = new FormData();
$.each($(':input', form ), function(i, fileds){
formData.append($(fileds).attr('name'), $(fileds).val());
});
$.each($('input[type=file]',form )[0].files, function (i, file) {
formData.append(file.name, file);
});
$.ajax( {
url: '../controllers/process.php',
type: 'POST',
enctype: 'multipart/form-data',
data: formData,
processData: false,
contentType: false,
success: function(data)
{
alert(data);
},
error: function(data)
{
alert(data);
}
} );
});
The problem is that I am getting empty post values in process.php:
if (isset($_POST['project_id']) AND isset($_POST['user_id'])){
//process
}else{
echo 'No post data';
}
It always return 'No post data' (But in console, I can see that data has been posted but it's not the case in server.). What am I missing here?
You can use the ajaxForm/ajaxSubmit functions from Ajax Form Plugin or the jQuery serialize function.
jQuery AJAX submit form
and
How to send FormData objects with Ajax-requests in jQuery?
If you are appending a file to formData
formData.append(file.name, file);
You need to use this version of the method as per MDN docs
formData.append(name, value, filename);
That will allow you to present a fieldname, file data, and file name
Also you might consider just submiting the form itself without the need for using formData
Thank you for all your reply. The problem was about max_upload_filesize and post_max_size. I increased the values for these options and now it's working. Thanks.
I have some drop downs looks like this in my HTML form:
<form name="fee" method="POST" action="">
<p><span class="title">Number of artists:</span>
<select name="Number">
<option value="" rel="none" selected disabled>Please select an option..</option>
<option value="one" rel="one_art">One artist only</option>
<option value="more" rel="more_arts">More than one artists</option>
</p>
A table of summery will be generated after I click the submit button.
<input type="submit" value="Calculate">
My question is: Whenever I click the button, the previously selected option will be reset. And only the summery show up at the end of the page. Is there a way to output the summery on the same page without the previously selected option gets cleared?
Thanks in advance!!
I think your best option is to use AJAX POST to post the form data, and JQuery to keep the same option selected:
$(document).ready(function() {
$("#fee").on('submit',(function(e) {
e.preventDefault();
var selectedOption = $( "#Number option:selected" ).text();
$.ajax({
url: "here put the url to the php page handling your form data",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function ()
{
$("#Number").val(selectedOption);
}
});
}
});
I populate a list of <form> using a PHP while loop, and fill the fields with values from MySQL. Now I want to be able to update all forms with one submit- button.
The form looks something like this in HTML (note, on my actual page there are multiple like this. The only thing that differes is the <form id='X'>:
<form id='34' name='customercontact' method='post' action='customerUpdate.php'>
Förnamn: <br /><input type='text' name='contact_firstname' class='textbox' value='text....'>
Efternamn: <br /><input type='text' name='contact_lastname' class='textbox' value='text....'>
Telefonnummer: <br /><input type='text' name='contact_phone' class='textbox' value='text....'>
Mobiltelefon: <br /><input type='text' name='contact_cellphone' class='textbox' value='text....'>
E-mail: <br /><input type='text' name='contact_email' class='textbox' value='text....'>
<select name='isActive'>
<option value="0" selected>Inaktiv</option>
<option value="1">Aktiv</option>
</select>
</form>
How do I use jQuery serialize to send each form and all the values as a string? I don'r really know where to start.
You can select all forms on the page $('form') and then iterate through them and 'submit' values via AJAX.
UPDATE:
<script type="text/javascript">
$(document).ready(function() {
$('#customer_contact_save').live('click', function(e){
e.preventDefault(); // prevent form submit
$.each($('form'), function(index) {
var sData = $(this).serialize(); // get data from form for submit
$.ajax({
type: "POST",// path to php script that saves data to db
url: "some.php",
data: sData,
success: function(someMessageFromPhp) {
alert(someMessageFromPhp); // alert to user what some.php returned
}
});
});
});
});
</script>
I'm passing form data to a PHP script for processing via JS(jQuery.ajax()).
Problem is - I can't figure out a way to access individual form control values inside PHP( e.g. $_POST['zipcode'] ).
Instead I can only access the data with $_POST['form'], which is an entire form represented as one long string( e.g. string(89)"color=red&color=blue&zipcode=12345..." ).
How can I access individual values of form data inside PHP script passed from a HTML form via JS?
index.php(form)
<form id="myform">
<select name="color" id="color">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<input type="text" id="zipcode" name="zipcode" />
<input type="submit" id="submit" name="submit" value="Submit" />
</form>
index.php(JS)
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
dataType: 'html',
url : 'PHPscript.php',
data: {form : $('#myform').serialize()}
}).done(function(data) {
var myJSONresult = data;
alert(myJSONresult);
});
});
PHPscript
<?php
if(isset($_POST["form"])){
$form = $_POST["form"];
$myzipcode = $_POST['zipcode']; // won't work; will be null or empty
echo json_encode($form);
}
?>
EDIT: The zipcode field:
$("#zipcode").focus(function(){
if(this.value == "zipcode"){
$(this).val("");
}
}).blur(function(){
if(this.value == ""){
$(this).val("zipcode");
}
});
You need to use serializeArray() on the form data instead of serialize. That will submit as an array.
data: $('#myform').serializeArray()
HTML
<input type="hidden" name="action" value="submit" />
PHP
if(isset($_POST["action"]))
{
//code
}
Add dataType: 'json' to your ajax handler and further modify your code like this:
$.ajax({
type: 'POST',
dataType: 'json', // changed to json
url : 'PHPscript.php',
data: {form : $('#myform').serialize()},
success : function(data){ // added success handler
var myJSONresult = data;
alert(myJSONresult.yourFieldName);
}
});
set traditional to true like
$.ajax({
traditional:true,
//your rest of the ajax code
});
on the php end you are getting the value fine the problem is at the form serialization end