When the user submits the form, the result should be displayed without page refreshing. The PHP script is also in the same HTML page.
What is wrong withe $.post jQuery?
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#btn").click(function(event) {
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $("#testform").serialize()
);
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform">
<!-- $_SERVER['PHP_SELF'] array -->
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
You need to use event.preventDefault in your javascript
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $( "#testform" ).serialize()
);
});
Yes, you need e.preventDefault. Also, I think these var myname and myage variables are unnecessary since you're serializing the entire form in $.post.
Try this:
$(document).ready(function() {
$("#btn").click(function(e) {
e.preventDefault();
$.post(
"23.php", $("#testform").serialize()
);
});
});
Hope this helps.
Peace! xD
This is my finalized complete code after following your all suggestions. But it is still refreshing when getting results. Let's see if I have made any further error in the code. Thanks for your all helps.
UPDATE! - All these HTML and PHP scripts resides in the same file called 23.php
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform"> <!-- $_SERVER['PHP_SELF'] array -->
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
<input type="submit" name="submit" id="btn"/>
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { //was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
Related
I am trying to put together a simple contact form with ajax, where users are not redirected to the contact.php file once the submission is done..
There is no errors.. I am always redirected..
Any idea please? Any suggestion is highly appreciated. Thanks!
contact.html
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="main.js"></script>
</head>
<body>
<form action="contact.php" method="post" class="ajax">
<div>
<input type="text" name="name" placeholder="Your Name">
</div>
<div>
<input type="email" name="email" placeholder="Your Email">
</div>
<div>
<textarea name="message" placeholder="Your Message"></textarea>
<div>
<input type="submit" value="Send">
</form>
</body>
</html>
contact.php
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
print_r($_POST);
}
?>
main.js
$('form.ajax').on('submit', function() {
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success:function(response) {
console.log(response);
}
});
return false;
});
You need to prevent the default form behavior.
$('form.ajax').on('submit', function(evt) {
evt.preventDefault();
You need to ouput json format so header need to be setting and you need to return json value to ajax success so need json_encode($object_or_array_form_php);
<?php
if(isset($_POST['name'], $_POST['email'], $_POST['message'], $_POST['name'])) {
header("Content-type:application/json");
$_POST['success'] = "You form is sending ...";
echo json_encode($_POST); //this is the "response" param form ajax
}
?>
Hacked! Here's a little bit different way ..
<script>
$(document).ready(function() {
$('form').submit(function (event) {
event.preventDefault();
var name = $("#mail-name").val();
var email = $("#mail-email").val();
var message = $("#mail-message").val();
var submit = $("#mail-submit").val();
$(".form-message").load("contact.php", {
name: name,
email: email,
message: message,
submit: submit
});
});
});
</script>
I am trying to submit a child-form, inside parent-form via ajax-jquery, so that it does not refresh entire page. Code is:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$(document).on('submit', '#form-2', function() {
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'a2.php',
data : data,
success : function(data) {
$("#form-2").fadeOut(500).hide(function() {
$(".result").fadeIn(500).show(function() {
$(".result").html(data);
});
});
}
});
return false;
});
}) // document ready ends here;
</script>
</head>
<body>
<form action="a1.php" method="post" name="form-1" id="form-1">
<input type="text" name="f1" />
<input type="text" name="f2" />
<input type="text" name="f3" />
<input type="text" name="f4" />
<!-----form 2 ajax starts----->
<form method="post" name="form-2" id="form-2">
<input type="text" name="g1" />
<input type="submit" id="sf2">
</form><!-----form-2 ends----->
</form><!-----form-1 ends----->
</body>
</html>
But its not working, it does simply nothing. I too used - preventdefault()
Any help ? I am trying to simply submit form-2 value in database, from which some dropdown of form-1 is getting all option values.
You could use:
$(document).on('click', '#sf2', function(event) {
var g1 = $('#g1').val();
$.ajax({
type : 'POST',
url : 'a2.php',
data : {
g1: g1
},
success : function(data) {
$("#form-2").fadeOut(500).hide(function() {
$(".result").fadeIn(500).show(function() {
$(".result").html(data);
});
});
}
});
});
and use a normal button:
<input type="text" name="g1" id="g1" />
<button type="button" id="sf2">Submit</button>
This is not good style though as forms should not be nested.
Hello so I have 2 submit buttons with different names (btn1, btn2) in my html form and what I am trying to do is to submit to another page without refreshing page. So what I wanted to do is if I click btn1 submit it will do something and if I click btn2 it will do another thing. My code in the html page is this
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#myForm').on('submit',function(e) {
$.ajax({
url:'update.php',
data:$(this).serialize(),
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1"> <input type="submit" name="btn2">
</form>
</body>
</html>
And the code in my update.php page
<?php
if(isset($_POST['btn1'])) {
//insert query
} else if(isset($_POST['btn2'])) {
//another insert query
}
?>
I actually got it working if I only have 1 submit button and no if(isset()) thing in the update.php page. What can I do to use 2 submits and with issets in another page without refreshing the main page?
$(this).serialize();
The above code statement doesn't include name of the submit button as a key value pair.
So, as people have suggested before me, you should use button instead of submit button. Something like this.
HTML and JS
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('#btn1, #btn2').on('click',function(e) {
var datastr = $(this).serialize() + "&button_id="+$(this).attr('id');
$.ajax({
url:'update.php',
data:datastr,
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
e.preventDefault();
});
});
</script>
</head>
<body>
<form method="POST" id="myForm" action="update.php">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<button id="btn1">Button1</button><button id="btn2">Button2</button>
</form>
</body>
</html>
AND PHP would be:
<?php
if($_POST['button_id'] == 'btn1') {
//do something
} else if($_POST['button_id'] == 'btn2') {
//do something else;
}
?>
Use this, may useful for you
try
$('#myForm').on('submit',function(e) {
e.preventDefault();
});
OR
<button type="button">
Use on click event on the button and add the value attribute to the submit button, the value of the click button will be pased to the php file
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Percentage</title>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$('input[type="submit"]').on('click',function(e) {
e.preventDefault();
$.ajax({
url:'update.php',
data:{'txt_amount':$('input[name="txt_amount"]').val(),'btn': $('input[type="submit"]').val()}
type:'POST',
success:function(data){
console.log(data);
$("#success").show().fadeOut(5000);
},
error:function(data){
$("#error").show().fadeOut(5000); //===Show Error Message====
}
});
});
</script>
</head>
<body>
<form method="POST" id="myForm">
Input Amount: <input type="text" name="txt_amount" required placeholder="Input number"> <br /> <br />
<span id="error" style="display:none; color:#F00">Some Error!Please Fill form Properly </span> <span id="success" style="display:none; color:#0C0">All the records are submitted!</span>
<input type="submit" name="btn1" value="btn1"> <input type="submit" name="btn2" value="btn2">
</form>
</body>
</html>
php:
<?php
if($_POST['btn'] == 'btn1') {
//do something
} else if($_POST['btn'] == 'btn2') {
//do something else;
}
?>
The html code:
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript"
src="js/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(msg) {
alert(msg);
$("#info1").html(data.msg);
}, "json");
});
});
</script>
</head>
<body>
<div id="info1">
Put the textbox input value into this block.
</div>
<br />
<form id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit"
id="submit" value="Submit Form" />
</form>
</body>
</html>
The php code:
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo json_encode($result);;
When I entered the text, it cannot display the same text above the input box. Maybe there have some wrong code, but I cannot find it, please help><
Reframed your code. Checkout,
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script>
$(function(){
$("form[id='form1']").on('submit', function(ev){
ev.preventDefault();
var th = $(this);
var data = th.serialize();
var action = th.attr('action');
$.post(action, data).done(function(response){
$("#info1").html(response.msg);
});
});
});
</script>
</head>
<body>
<div id="info1">
<!--Put the textbox input value into this block.-->
</div>
<br />
<form action="ex2_5.php" id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit" id="submit" value="Submit Form" />
</form>
</body>
</html>
ex2_5.php
<?php
$result = array();
if (!empty($_POST['form1']))
$result['msg'] = "<h1>".$_POST['form1']."</h1> is added";
else
$result['msg'] = "<h1>Field is empty!!</h1>";
header('Content-type: application/json');
echo json_encode($result);
Bugs:
1) ;; double semicolon
2) $_POST['form1'] in your PHP file
3) Wrong index using in JS while returning
Debugging:
Open console (Right click -> Inspect element -> Console tab) and checkout for errors
Solution 1:
Specify content type for ajax response as application/json. Otherwise the response will be a string not as json.
// Specify content type header as application/json
header('Content-type: application/json');
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo #json_encode($result);
Solution 2:
If header is not application/json then parse string into object using JSON.parse function.
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(data) {
var data = JSON.parse(data);
$("#info1").html(data.msg);
}, "json");
});
});
</script>
I want to send data using GET or POST to another php file on a button's(NOT Submit button) onClick() Event.
Please help me.
Let I give you simple HTML with post method using AJAX
Test.php
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
</head>
<body>
<form id="myform_new">
<input type="text" name="abc" value="abc" id="txt"/>
<input type="text" name="abc1" value="abc1" id="txt1"/>
<input type="button" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>
Test1.php(ajax calling file)
<?php
echo "<pre>";print_r($_POST);
?>
Let i give you some of the ajax posting method
(1)
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
(2)
<script type="text/javascript"> $(function() { $("#Submit").click(function()
{
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { txt: txt,txt1:txt1 }); return false; }); });
</script>
(3)
<script type="text/javascript"> $(function() { $("#Submit").click(function() {
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { data: "txt="+txt+"&txt1="+txt1}); return false; }); });
</script>
Hello in there i have explain both ajax and get/post method, Please have look below link for get/post method for submit a form in php.
http://www.tutorialspoint.com/php/php_get_post.htm
This below code is used for submit form using ajax
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { name: $('#name').val(), name2: $('#name2').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</body>
</html>