My Ajax output is disappearing after one sec - php

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.

Related

Why is my ajax php file variables undefined

I am trying to learn jQuery ajax the function seems to be working properly so says browser web developer tools but the values aren't pulled through to the php file(url) that I have here's my simple code.
This is the HTML anf jQuery File
<!Doctype HTML>
<html>
<head>
<title>Working with PHP and jQuery</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
<script src="js/jquery-1.11.3.min.js"></script>
</head>
<body>
<form id="#myForm">
<p>
<label>Enter your name</label>
<input type="text" name="Name">
</p>
<p>
<label>Are you male
<input type="checkbox" name="IsMale">
</label>
</p>
<p>
<label>Enter your email address</label>
<input type="email" name="Email">
</p>
<p>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</p>
</form>
<div id="loadResult"></div>
<script>
$(function() {
$('#submitButton').on('click', function(e){
e.preventDefault();
$.ajax({
url: 'php/form1.php',
type: 'POST',
data: $('#myForm').serialize(),
success: function(result) {
console.log(result); $('#loadResult').html(result);
},
error: function(badresult){ alert("ajax error function hit"); console.log(badresult); }
});
});
});
</script>
</body>
</html>
And here's the php file
<?php
$name = $_POST['Name'];
$isMale = $_POST['IsMale'];
$email = $_POST['Email'];
echo "Name is $name, are you a male? $isMale. Your email address is $email";
?>
I am using the jquery serialize function but don't know where I am going wrong
Most likely what you're getting is this line blowing up
$isMale = $_POST['IsMale'];
And in your HTML we see
<input type="checkbox" name="IsMale">
Checkboxes, when they are not checked, are not successful, meaning they won't show up in $_POST. From the jQuery serialize manual
Note: Only "successful controls" are serialized to the string. No submit button value is serialized since the form was not submitted using a button. snip
Values from checkboxes and radio buttons (inputs of type "radio" or "checkbox") are included only if they are checked
So you need to check that it was submitted
$isMale = (isset($_POST['IsMale'])) ? 'Yes' : 'No';

Submit without refresh with 2 buttons

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;
}
?>

How can I submit a form without reloading the page

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/

ajax post javascript variable to php in same page

i write sample code to ajax post javaxcript varible to php in 2 page, test.php and validate.php.
test.php :
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script type="text/javascript" src="jquery.min.js" ></script>
</head>
<body>
<form>
<input type="text" id="name" placeholder="enter Your name...." /><br/>
<input type="text" id="age" placeholder="enter Your age...." /><br/>
<input type="button" value="submit" onclick="post();">
</form>
<div id="result" ></div>
<script type="text/javascript">
function post()
{
var name=$('#name').val();
var age=$('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data)
{
if (data=="1")
{
$('#result').html('you are over 18 !');
}
if (data=="0")
{
$('#result').html('you are under 18 !');
}
});
}
</script>
</body>
</html>
validate.php
<?php
$name=$_POST['postname'];
$age=$_POST['postage'];
if ($age>=18)
{
echo "1";
}
else
{
echo "0";
}
?>
how can i write/change above code in same page ?? and validate.php insert in test.php ??
added after first answer :
"but i dont have/use any button or in my page.
and where can i insert validate.php code in test.php. please help by insert complete correct code."
Try adding a submit() method to your <form> rather than attaching the event to the submit button.
$(document).on('submit', 'form', function(){
post();
return false;
});
At the moment I think your form is submitted no matter what, you have to either return false on submit or preventDefaults()
A good idea is also to add an ID to your form in case you have more than one on your page and use the relevant selector in the .on event handler such as
$(document).on('submit', $('#form-id'), function(){ ... });
ajax is use for exchanging data with a server. If you want write code in same page so reload page and write validate.php code above of test.php like this
<?php
//validate.php code
?>
<form action=test.php type=POST>
<input type="text" id="name" placeholder="enter Your name...." /><br/>
<input type="text" id="age" placeholder="enter Your age...." /><br/>
<input type="button" value="submit">
</form>

submit normally newly created ajax form

I want to submit my form. In my form using first button I create a textbox through ajax and after that I use second button to submit the form normally. When I want to get the value of newly created textbox using $_POST it gives error. How can i get value of ajax created button on submission. my php code is :
<?php`enter code here`
session_start();
ob_start();
require_once "config.php";
if ($_SERVER['REQUEST_METHOD']=="POST")
{
if (isset($_POST['subtest']))
{
print $_GET['tt'];
}
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery-ui-1.8.21.custom/js/jquery-ui-1.8.21.custom.min.js"> </script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#subt").click(function(){
jQuery("#divload").show();
jQuery.ajax({url:"adp.php", type:"post", success:function(result){
jQuery("#disp").html(result);
jQuery("#divload").hide();
}});
return false;
});
});
</script>
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery("#subtest").click( function() {
alert(jQuery("#tt").val());
});
});
</script>
</head>
<body id="#bdy">
<form id="FrmMain" method="post" action="">
<div id="Shd" style="font: 10%; margin: 50px; background-repeat:repeat-y; padding- left:120px;" >
<input type="text" id="txtFrom" name="txtFrom" />
<input type="text" id="txtUpto" name="txtUpto" />
<input type="text" id="txtOpt" name="txtOpt" />
<input type="submit" id="subt" name="subt" />
<input type="submit" id="subtest" name="subtest" />
<div id="RuBox" style="font-weight:bold;"><input type="checkbox" id="chkaccept" name="chkaccept" /> I accept terms and conditions.</div>
</div>
</form>
<div style="color:#F00; font-size:18px; display:none;" id="divload">Please wait loaidng... </div>
<div id="disp"></div>
</body>
</html>
Code of my adp.php file :
<?php
sleep(5);
?>
<div style="color:#30F; font-size:36px;">
Application testing............
<input type="text" id="tt" name="tt" />
</div>
I am not getting value of textbox named "tt" in temp form
Thanks
You're pretty much not posting anything from here:
jQuery(document).ready(function(){
jQuery("#subt").click(function(){
jQuery("#divload").show();
jQuery.ajax({url:"adp.php", type:"post", success:function(result){
jQuery("#disp").html(result);
jQuery("#divload").hide();
}});
return false;
});
});
So I would assume that you only want to generate a text field dynamically. And you can do it without the use of ajax:
var form = $('#FrmMain');
$('<input>').attr({'type' : 'text', 'id' : 'tt', 'name' : 'tt'}).appendTo(form);
Plus you're also trying to print out $_GET['tt'] while the form method is POST
if (isset($_POST['subtest']))
{
print $_GET['tt'];
}
This should also be:
echo $_POST['tt'];

Categories