I have a form that I am trying to submit with POST. When I go to catch the POST vars, nothing is being sent.
<?php require_once("../includes/initialize.php"); ?>
<html><head>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<script src="jquery-1.8.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form').submit(function (e) {
var $this = $(this);
e.preventDefault(); // This prevents the form submission.
$("#messageSent").show("slow");
$this.closest('#contactForm').slideUp('slow', function () {
$this[0].submit(); // Actual submission.
});
});
$("#contactLink").click(function(){
if ($("#contactForm").is(":hidden")){
$("#contactForm").slideDown("slow");
}else{
$("#contactForm").slideUp("slow");
}
});
});
</script></head><body>
<?php
if(isset($_POST['signupSubmit'])){
echo "Post is set";
echo $_POST['name'], "<br />";
echo $_POST['email'];
}else{
echo "post is not set";
}
if(isset($_POST['signupSubmit'])){
$signup = new Signup();
$signup->name = $_POST['name'];
$signup->email = $_POST['email'];
if($signup->save()) {
$session->message("We will contact you with details.");
} else {
$session->message("Failed", $signup->errors);
}
}
echo output_message($message);
?>
<div id="contactFormContainer">
<div id="contactLink"></div>
<div id="contactForm">
<form action="test2.php" enctype="multipart/form-data" method="post">
<fieldset>
<label for="name">Name *</label>
<input id="name" type="text" name="name" />
<label for="email">Email address *</label>
<input id="email" type="text" name="email" />
<input id="sendMail" type="submit" name="signupSubmit" />
<span id="messageSent"></span>
</fieldset>
</form>
</div>
</div>
</body>
</html>
Any help would be appreciated!
That's because when you submit the form with $this[0].submit(); it still runs the submit handler which unconditionally prevents the form from submitting. Set some flag so the form will submit after the animation.
$('form').submit(function (e) {
var $this = $(this);
if (!$this.data('afteranimation')){
$("#messageSent").show("slow");
$this.closest('#contactForm').slideUp('slow', function () {
$this.data('afteranimation', true);
$this.submit(); // Actual submission.
});
e.preventDefault(); // This prevents the form submission.
}
});
Related
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>";
}
?>
I want to know how can I convert a normal php coded cc validator to a bulk.I have basic code with stipe merchant API working perfectly,but I want to make in bulk so I can check as many as possible help me out and tell me also how can I separate the not working and not working ccs in different boxes.
<?php
require 'path-to-Stripe.php';
if ($_POST) {
Stripe::setApiKey("YOUR-API-KEY");
$error = '';
$success = '';
try {
if (!isset($_POST['stripeToken']))
throw new Exception("The Stripe Token was not generated correctly");
Stripe_Charge::create(array("1" => 1000,
"currency" => "usd",
"card" => $_POST['stripeToken']));
$success = 'Your payment was successful.';
}
catch (Exception $e) {
$error = $e->getMessage();
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Stripe Getting Started Form</title>
<script type="text/javascript" src="https://js.stripe.com/v1/"></script>
<!-- jQuery is used only for this example; it isn't required to use Stripe -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
<script type="text/javascript">
// this identifies your website in the createToken call below
Stripe.setPublishableKey('YOUR-PUBLISHABLE-API-KEY');
function stripeResponseHandler(status, response) {
if (response.error) {
// re-enable the submit button
$('.submit-button').removeAttr("disabled");
// show the errors on the form
$(".payment-errors").html(response.error.message);
} else {
var form$ = $("#payment-form");
// token contains id, last4, and card type
var token = response['id'];
// insert the token into the form so it gets submitted to the server
form$.append("<input type='hidden' name='stripeToken' value='" + token + "' />");
// and submit
form$.get(0).submit();
}
}
$(document).ready(function() {
$("#payment-form").submit(function(event) {
// disable the submit button to prevent repeated clicks
$('.submit-button').attr("disabled", "disabled");
// createToken returns immediately - the supplied callback submits the form if there are no errors
Stripe.createToken({
number: $('.card-number').val(),
cvc: $('.card-cvc').val(),
exp_month: $('.card-expiry-month').val(),
exp_year: $('.card-expiry-year').val()
}, stripeResponseHandler);
return false; // submit from callback
});
});
</script>
</head>
<body>
<h1>Charge $10 with Stripe</h1>
<!-- to display errors returned by createToken -->
<span class="payment-errors"><?= $error ?></span>
<span class="payment-success"><?= $success ?></span>
<form action="" method="POST" id="payment-form">
<div class="form-row">
<label>Card Number</label>
<input type="text" size="20" autocomplete="off" class="card-number" />
</div>
<div class="form-row">
<label>CVC</label>
<input type="text" size="4" autocomplete="off" class="card-cvc" />
</div>
<div class="form-row">
<label>Expiration (MM/YYYY)</label>
<input type="text" size="2" class="card-expiry-month"/>
<span> / </span>
<input type="text" size="4" class="card-expiry-year"/>
</div>
<button type="submit" class="submit-button">Submit Payment</button>
</form>
</body>
</html>
I'm doing a simple ajax update record.
Here's my code
index.php:
<script type="text/javascript">
$("#submit_button").click( function() {
$.post( $("#updateprofile").attr("action"),
$("#updateprofile :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
$("#updateprofile").submit( function() {
return false;
});
function clearInput() {
$("#updateprofile :input").each( function() {
$(this).val('');
});
}
</script>
<form class="form" id="updateprofile" action="edit-profile.php" method="POST">
<!-- form-horizontal -->
<div class="control-group">
<label class="control-label" for="inputName">Name</label>
<div class="controls">
<input type="text" class="input-block-level" name="fname"
value="<?php echo $fname; ?>">
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Password</label>
<div class="controls">
<input type="text" class="input-block-level"
value="<?php echo $password; ?>" name="password" >
<input type="hidden" name="id"
value="<?php echo $user; ?>" >
</div>
</div>
<div class="control-group">
<div class="controls">
<button class="btn btn-custom" type="submit" id="submit_button">Update</button>
<button class="btn btn-custom" type="reset" >Cancel</button>
</div>
</div>
</form>
<span id="result"></span>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js">
edit-profile.php:
<?php
include('../../db.php');
if( isset($_POST['id']) || isset($_POST['fname']) || isset($_POST['password']) ){
$id = $_POST['id'];
$fname = $_POST['fname'];
$password = $_POST['password'];
$update = $conn->prepare("UPDATE tblusers
SET fname = :fname,
password = :password
WHERE user_id = :id");
$update->execute(array(':fname' => $fname,
':password' => $password,
':id' => $id));
echo 'Successfully updated record!';
} else {
echo 'Required field/s is missing';
}
?>
But I'm not getting the update without refreshing the page or going to other page. Any ideas? Help is much appreciated. Thanks.
Try this, You have missed add ready handler and Added e.preventDefault(); When you trigger the submit button, it uses the default form action page
$(function(){
console.log("Jquery Loaded!!"); // alert("jquery loaded!");
$("#submit_button").click( function(e) {
e.preventDefault();
$.post( $("#updateprofile").attr("action"),
$("#updateprofile :input").serializeArray(),
function(info){ $("#result").html(info);
});
clearInput();
});
});
Use Lateset version of jquery library.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Bind your functions in $(document).ready() function
Your form is being submitted because your $("#submit_button") if of type submit, which means that when your ajax executes (it executes ok) but your form is also submitted.
To stop form from being submitted, you can add
<form onSubmit="return false;">
To your HTML. Or you can also use:
<form onSubmit="return func();">
If func() returns false, form will not be submitted.
First add you script file for including jQuery in starting and put the functions as stated below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#submit_button").click( function() {
$.post( $("#updateprofile").attr("action"), $("#updateprofile :input").serializeArray(),function(info){
$("#result").html(info);
});
clearInput();
});
$("#updateprofile").submit( function() {
return false;
});
});
function clearInput() {
$("#updateprofile :input").each( function() {
$(this).val('');
});
}
</script>
and you are sorted
I can't process the uploaded image file with php ajax requuest. It's process the text field but can't process uploaded file. Following is my form. can you tell me what is wrong in my simple code and how can i solve it ?
and without upload file i saw that it's not redirect after successfull.
html form
<link rel="stylesheet" href="http://jquery.bassistance.de/validate/demo/css/screen.css" />
<script src="http://jquery.bassistance.de/validate/lib/jquery.js"></script>
<script src="http://jquery.bassistance.de/validate/jquery.validate.js"></script>
<script>
// JQuery Script to submit Form
$(document).ready(function () {
$("#commentForm").validate({
submitHandler : function () {
// your function if, validate is success
$.ajax({
type : "POST",
url : "process.php",
data : $('#commentForm').serialize(),
success : function (data) {
$('#message').html(data);
}
});
return false;
}
});
});
</script>
<form class="cmxform" id="commentForm" method="get" action="" enctype="multipart/form-data">
<fieldset>
<p>
<input type="text" name="text"/>
</p>
<p>
<input type="file" name="img"/>
</p>
<p>
<input class="submit" type="submit" value="Submit" />
</p>
</fieldset>
</form>
<div id="message"></div>
php process page:
<?php
$text = $_POST['text'];
$file = $_FILES['img']['name'];
if(empty($text) && empty($file))
{
echo "Both field is empty ";
}
else
{
header("Refresh:3, url=ajax_form.php");
}
?>
I've searched through the StackOverFlow but didn't found what I was looking for so I'm posting what I want to ask you.
I'm a new comer to the world of PHP any how I've started to write a script which will get data and display on a WAP interface that part is ok my issue is in the part I'm writing for the data insert page or the Admin page. I've got every thing working but I love to know how to use AJAX to display a message with out going to the particular processing page.
The Process Page,
<?php
include ('connect.php');
$data = ("SELECT * FROM poiinfo");
$poiName = $_REQUEST['Name'];
$poiDes = $_REQUEST['Descrip'];
$poiCon = $_REQUEST['ConInfo'];
/*$poiImg = $_REQUEST['Image']; */
$dbData = "INSERT INTO poiinfo(`Name`, `Des.`, `Contact`) VALUES ('$poiName','$poiDes','$poiCon')";
$putData = mysql_query($dbData);
if ($putData){
echo "Data inserted";
}else {
echo "Not Done";
}
?>
Can I know how to use AJAX to get an message.
I've used the code examples that you guys gave me but I'm still not getting the job done please can you help me to find what I'm doing wrong.
My Form,
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#save_data").click(function(){
var name = document.getElementById("Name");
var desc = document.getElementById("Descrip");
var con = document.getElementById("ConInfo");
var dataString = 'Name='+name'&Descrip='+desc'&ConInfo='con;
$.ajax({
type:'POST',
data:dataString,
url:'addpoipro.php',
success:function(data){
if(data="Data inserted") {
alert("Insertion Success");
} else {
alert("Not Inserted");
}
}
});
});
});
</script>
<title>AddPOI</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" name="form1" id="form1">
<p>
<label for="poiid">ID :</label>
<input type="text" name="poiid" id="poiid" readonly="readonly" style="width:70px;" value="<?php echo $tId; ?>" />
</p>
<p>
<label for="Name">POI Name :</label>
<input type="text" name="Name" id="Name" />
</p>
<p>
<label for="Descrip" style="alignment-adjust:middle">POI Description :</label>
<textarea name="Descrip" id="Descrip" cols="45" rows="5"></textarea>
</p>
<p>
<label for="ConInfo">Contact Infomation :</label>
<textarea name="ConInfo" id="ConInfo" cols="45" rows="5"></textarea>
</p>
<p>
<label for="Img">POI Image :</label>
<!--<input type="file" name="Image" id="Image" /> -->
</p>
<p> </p>
<p>
<div align="center">
<input type="button" name="Submit" id="save_data" value="Submit" style="width:100px;" />
<input type="reset" name="reset" id="reset" value="Rest Data" style="width:100px;" />
</div>
</p>
</form>
</body>
</html>
Above4 is my form and the process.php is before that please help me thank you.
Example using jQuery's $.ajax:
$.ajax({
url: "process.php",
type: "POST",
data : { Name : 'John', Descrip : 'some description..', ConInfo : 'some info...' },
success : function(data){
if(data == "Data inserted")
{
console.log("Success!");
}
else
{
console.log("fail!");
}
}
});
Here is another solution without using jquery.
index.html
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<!-- reply from process.php is shown in this div -->
<div id=message></div>
<!-- click to send data -->
click here
</body>
</html>
test.js
function sendData(Name,description,info) {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer Browsers
try
{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function()
{
var ajaxDisplay = document.getElementById('message');
if(ajaxRequest.readyState == 4)
{ ajaxDisplay.innerHTML = ajaxRequest.responseText;}
else { document.getElementById('message').innerHTML="<span style=\"color:green;\">Loading..</span>"; }
}
var url="process.php?name="+Name+"&Descrip="+description+"&ConInfo="+info;
ajaxRequest.open("POST", url, true);
ajaxRequest.send(null);
}
You can do it like this also.
You HTML
<label>Name</labe><input type="text" id="name" name="full_name" value="" />
<label>Address</labe><input type="text" id="addr" name="addr" value="" />
<input type="button" name="save" id="save_data" value="Save" />
in the head section after adding jQuery do something like this
<script>
$(document).ready(function(){
$("#save_data").click(function(){
var name = $("#name").val();
var addr = $("#addr").val();
var dataString = 'name='+name'&address='+address;
$.ajax({
type:'POST',
data:dataString,
url:'process.php',
success:function(data){
if(data="inserted") {
alert("Insertion Success");
} else {
alert("Not Inserted");
}
}
});
});
});
</script>
"process.php page"
$name = $_POST['name'];
$address = $_POST['address'];
// DO YOUR INSERT QUERY
$insert_query = mysql_query("INSERT QUERY GOES HERE");
if(// CHECK FOR AFFECTED ROWS) {
echo "inserted";
} else {
echo "not";
}