I have this html example form that I need to submit to MySQL table without having to refresh the page. Basically the main idea is to keep the username value in the input field after the data is sent. I have been struggling for days trying to use Ajax and JQuery functions to achieve my goal but I cannot get it right, that's why I'm only posting this piece of html code, I'm open to ideas, if you can please provide some code. Thank you so much.
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" name="form">
name:<input id="name" name="name" type="text" />
<select id="gender" name="gender">
<option value="">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<input type="submit" value="Submit" class="submit"/>
</form>
</body>
</html>
Inside my php file:
<?php
$dbhost = 'localhost';
$dbuser = 'Myuser';
$dbpass = 'Mypass';
$db = 'Mydb';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
mysql_select_db($db);
$name = $_POST['name'];
$gender = $_POST['gender'];
mysql_query("INSERT INTO callWrapper ('user','data')
VALUES ('$name','$gender'") or die(mysql_error());
?>
Use event.preventDefault() in jQuery:
$("form").submit(e) {
e.preventDefault();
// the rest of your code
}
See here for more details.
If you do not want to use jQuery, you can do it like this:
<form onsubmit="myFormFunction();return false">
Bear in mind these do slightly different things as explained here
HTML:
<html>
<head>
<title>Test</title>
</head>
<body>
<form method="post" name="form" id="frm_data">
name:<input id="name" name="name" type="text" />
<select id="gender" name="gender">
<option value="">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<input type="button" value="Submit" class="submit" id="btn_submitForm"/>
</form>
</body>
</html>
JS:
// bind click event
$('#btn_submitForm').click(function(e){
e.preventDefault();
var url = 'Your PHP File URL';
var formData = $("#frm_data").serializeObject();
$.post(url, formData,
function(data) {
//alert(data);
}
);
});
<html>
<head>
<title>Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#frm_data").submit(function(){
$.ajax({
type: "POST", // data send format POST/GET
url: "./process_form.php", // file url for data processing
data: $("#frm_data").serialize(), // all form field are serialize
dataType: "json", // response type xml, json, script, text, htm
success: function(data) {
alert('hi');
}
});
});
});
</script>
</head>
<body>
<form method="post" name="form" id="frm_data" onsubmit="return false;">
name:<input id="name" name="name" type="text" />
<select id="gender" name="gender">
<option value="">Gender</option>
<option value="1">Male</option>
<option value="2">Female</option>
</select>
<input type="submit" value="Submit" class="submit" id="btn_submitForm"/>
</form>
</body>
</html>
for the reference check the url : http://api.jquery.com/jquery.post/
Related
I am using Ajax with form in Ajax I have used a if condition for validation if my form is empty it should display a message that all fields are required and if fields are fill it should add data in dB and display a success message although everything is working perfectly except one thing which is that my output only display for a second and then automatically disappears can anyone help me in this regard:
`
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<title>Document</title>
<script src="jquery.js"></script>
<link rel="stylesheet" type="text/css" href="stylesheet.css">
</head>
<body>
<h1>PHP & Ajax Seralize Form</h1>
<form id="form-data" method="post">
Name<br><input type="text" name="name" id="name" value=""><br><br>
Age<br><input type="number" name="number" id="age" value=""><br><br>
Gender<br>
<input type="radio" name="gender" value="Male">Male
<input type="radio" name="gender" value="Female">Fe-male<br><br>
<select name="country">
<option value="Kashmir">Kashmir</option>
<option value="Egypt">Egypt</option>
<option value="Norway">Norway</option>
<option value="Iceland">Iceland</option>
</select><br>
<br><input type="submit" id="submit" value="Save">
</form>
<div id="response">
</div>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var name = $('#name').val();
var age = $('#age').val();
if( name== "" || age== ""){
$('#response').fadeIn();
$('#response').removeClass('success-msg').addClass('error-msg').html("All fields are required");
}else{
$.ajax({
url: 'save-form.php',
type: 'POST',
data: $('#form-data').serialize(),
success: function(result){
$('#response').fadeIn();
$('#response').removeClass('error-msg').addClass('success-msg').html(result);
}
});
}
});
});
</script>
</body>
</html>
`
probably your page is refreshed, try to use preventDefault to prevent the refresh
$('#submit').click(function(event){
//your code here
event.preventDefault();
}
You have a button with type "submit".
<input type="submit" id="submit" value="Save">
As the click-event occurs on this button, your form will be send to the server. You have no action attribute defined on your form, so it redirects after submit to the same URL.
As Sterko stated, you could use a event-handler to prevent the submission of your form due to the submit button.
I need to submit the whole form when I change a select option and save it to mysql without reload page.
I have this code, but only POST the select option value and I need to POST the hidden values in the form too.
<form class="form-horizontal" method="POST" action='#' name="dateForm">
<input type='hidden' name='cond_acao' class='form-control' value="edit_seccao_formando">
<input type="hidden" name="id_formando" value="<?=$linha_formandos[id_formando];?>">
<select name="id_seccoes" class="form-control" onchange="return postSelection">
<option selected="selected" value="1">car</option>
<option value="2">boat</option>
<option value="3">plane</option>
</select>
<div id='response_seccoes'></div>
<script>
function postSelection(selectObject) {
var id_seccoes = window.dateForm.id_seccoes.value = selectObject.options[selectObject.selectedIndex].value;
var dataString = "id_seccoes=" + id_seccoes;
$.ajax({
type: "post",
url: "url.php",
data: dataString,
success: function(response) {
$('#response_seccoes').html("ok").fadeIn(100).delay(2000).fadeOut("slow");
//$("#list").html(response);
}
});
return false;
};
</script>
</form>
It's possible to serialize instead of especified the strings?
Can anyone help me please? Thank you
you are using Jquery, I suggest you monitor the select button for change using a jquery function like
$("id_seccoes").change(function(){
//call your post method here.
});
Replace your code with this.
<form class="form-horizontal" method="POST" action='#' name="dateForm">
<input type='hidden' name='cond_acao' class='form-control' value="edit_seccao_formando">
<input type="hidden" name="id_formando" value="<?=$linha_formandos[id_formando];?>">
<select name="id_seccoes" class="form-control">
<option value="1">car</option>
<option value="2">boat</option>
<option value="3">plane</option>
</select>
</form>
<div id='response_seccoes'></div>
<script>
$(document).ready(function(){
$('[name="id_seccoes"]').change(function(){
$.post('url.php',$('[name="dateForm"]').serialize(),function(response){
$('#response_seccoes').html("ok").fadeIn(100).delay(2000).fadeOut("slow");
});
});
});
</script>
I have below JSON data and HTML form, in which dynamically fields get created. This form work to send the data. But how to fill the fields by dynamically creating them
json data
$data = {"1":"a","3":"b","5":"c","2":"d","4":"e"}
index.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="http://code.jquery.com/jquery-compat-git.js"></script>
<title>Add/Remove Input Fields Dynamically with jQuery</title>
<script type="text/javascript">
$(function() {
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).click(function(e) {
$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
$('.multi-field .remove-field', $wrapper).click(function() {
if ($('.multi-field', $wrapper).length > 1)
$(this).parent('.multi-field').remove();
});
});
});
</script>
</head>
<body>
<form role="form" action="" method="POST">
<label>Stuff</label>
<div class="multi-field-wrapper">
<div class="multi-fields">
<div class="multi-field">
<select name="id[]">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<input type="text" name="stuff[]">
<button type="button" class="remove-field">Remove</button>
</div>
</div>
<button type="button" class="add-field">Add field</button>
</div>
<input type="submit">
</form>
</body>
</html>
Any help will be appreciated.
You need a loop. In javascript you do something like:
var $data = {"1":"a","3":"b","5":"c","2":"d","4":"e"};
var formHTML = "";
$.each($data, function(key, value) {
var inputHTML = "<input name='"+key+"' value='"+value+"' type="text"/>\n";
formHTML += inputHTML;
});
And then append formHTML inside your form.
I have a select box outside my form, When the users selects an option, the right form is being shown. But I want to send the value of the selected option together with the form.
<select id="selection" onchange="showForm()">
<option value="iphone">iPhone</option>
<option value="Android">Android</option>
</select>
<form action="iphone.php" method="post" id="form1">
<input type="text name="username" required>
</form>
<form action="android.php" method="post" id="form2">
<input type="text name="username" required>
</form>
Please note: This is a simple example, I want to know how you can send the value of the selectbox outside the form.
Add to each form a hidden input element:
<input type="hidden" name="selection" class="hiddenselection" />
Use javascript to copy the value on change. In jquery something like this:
$('#selection').on('change',function(){
$('.hiddenselection').val($('#selection').val());
})
function showForm(value) {
$.ajax({
type: "POST",
success: function(value){
if(value =='iphone'){
$("#form2").hide();
}else{
$("#form1").hide();
}
}
});
}
Keep the selected value in hidden field form1 and form2
<select id="selection" onchange="showForm(this)">
<option value="iphone">iPhone</option>
<option value="Android">Android</option>
</select>
<form action="iphone.php" method="post" id="form1">
<input type="text" name="username" required />
<input type="hidden" name="selection" id="iphone_selection" />
</form>
<form action="android.php" method="post" id="form2">
<input type="text" name="username" required />
<input type="hidden" name="selection" id="android_selection" />
</form>
<script>
function showForm(THIS){
var thisVal = $(THIS).val();
if(thisVal == 'iphone'){
$('#form2').hide();
$('#form1').show();
$('#iphone_selection').val(thisVal);
//$("#form1").submit();
}
if(thisVal == 'Android'){
$('#form1').hide();
$('#form2').show();
$('#android_selection').val(thisVal);
//$("#form2").submit();
}
}
</script>
<style>
#form1{
display:none;
}
#form2{
display:none;
}
</style>
https://jsfiddle.net/9tms99p5/
Try to include this script on your code.
<script type="text/javascript">
window.onload = function(){
document.getElementById("selection").onchange();
};
function showForm(){
if(document.getElementById("selection").value == "iphone"){
document.getElementById("form1").style.display = "block";
document.getElementById("form2").style.display = "none";
}else if(document.getElementById("selection").value == "Android"){
document.getElementById("form1").style.display = "none";
document.getElementById("form2").style.display = "block";
}
}
</script>
i want to implement a dynamic drop down which will select , batch of students from first drop down and then the corresponding subjects as the options for second drop down ..
this is the code for my Page :
<head>
<link rel="stylesheet" type="text/css" media="all" href="jsDatePick_ltr.min.css" />
<script type="text/javascript" src="jsDatePick.min.1.3.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function(){
new JsDatePick({
useMode:2,
target:"inputField",
dateFormat:"%d-%M-%Y"
});
};
</script>
</head>
<?php
$dept =$_COOKIE[dept];
include_once("../Include/connectdb.php");
include_once("../Include/data_menu.php");
include_once '../Include/pagemaker.php';
?>
<script type="text/javascript">
$(document).ready(function()
{
$(".batch").change(function()
{
var id=$(this).val();
var dataString = 'year_join='+ id;
$.ajax
({
type: "POST",
url: "ajax_subject.php",
data: dataString,
cache: false,
success: function(html)
{
$(".subject").html(html);
}
});
});
});
</script>
</head>
<body>
<br><br><br><br><br>
<fieldset class="cbox"><legend>Batch</legend>
<form name="frm" action=<?php print "edit_attendencePHP_NEW.php"; ?> method="GET"
id="content">
<br><br>
<div style="margin:80px">
<label>Batch :</label> <select name="batch">
<option selected="selected">--Select Batch--</option>
<?php
$result = mysql_query("select distinct year_joining from student_profile
order by year_joining ")or die(mysql_error());
while($year = mysql_fetch_assoc($result)){
if($year[year_joining]!="" && $year[year_joining]>"2008"){
print "<OPTION value='$year[year_joining]'>$dept $year[year_joining]</OPTION>";
} }
?>
</select>
<label>Subject :</label> <select name="subject" class="subject">
<option selected="selected">--Choose Subject--</option>
</select>
Date :<input type="text" size="12" id="inputField" name="date"/>
<input class="bluebutton" type="submit" value="Go">
</form><br>
<label class="comment">select a batch frm the list and press "Go"</label>
</fieldset>
the second ajax page works fine ... as i tested that with ($_GET)
this is wat with $_GET[year_join] ( view source code ) shows ...
ajax_subject.php
<option value="ENGG.MATHS-I">ENGG.MATHS-I</option><option value="COMPUTER PROGRAMMING
LAB">COMPUTER PROGRAMMING LAB</option><option value="WORKSHOPS">WORKSHOPS</option>
<option value="ENGG.PHYSICS">ENGG.PHYSICS</option><option
value="ENGG.CHEMISTRY">ENGG.CHEMISTRY</option><option ...........
Everything else seems fine ..
Right now it looks like no change event, which leads to the AJAX request, is being fired because your batch select element does not have a class of batch, only a name of batch. That is what you intended with $(".batch").change(function(){} right? Once you change, I would put an alert or console log in your callback function just to make sure it is even firing.