Update 2: I found out what was wrong! There was a 301 redirect in the .htaccess file. I will post it as an answer once I am allowed to (users under 10 rep have to wait 8 hours).
Update: I have taken Barmar's suggestion and checked the network tab (a tab I'm not too familiar with) and noticed I am receiving a 301 from handle.php See screenshot. I am going to do some searching and post my results.
Original Post: I am using the JQuery validation plugin to validate and send form data via ajax. The problem isn't that the data is being sent, but the form handler is saying there are no elements in the $_POST array. I have tested a few different methods to send ajax, and the data sends, but the form handler does not see any $_POST[] values.
Note: I have to use the JQuery validation plugin so it has to be handled by .validate.submitHandler(). Any $(form).on() won't suffice.
html + js (index.php)
<form action="handle.php" class="sky-form sky-form-modal" id="sky-form-modal" method=
"post" name="sky-form-modal">
<label class="input">
<input name="name" placeholder="Name" type=
"text">
</label>
<label class="input"><input name="company" placeholder="Company" type=
"text">
</label>
<footer>
<button class="button" type="submit">Send request</button>
<div class="progress"></div>
</footer>
</form>
<script>
$("#sky-form-modal").validate({
submitHandler: function(form) {
var $form = $("#sky-form-modal"); //being explicit for testing
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
request = $.ajax({
url: "handle.php",
type: "POST",
data: serializedData
});
console.log('data: ' + serializedData);
request.done(function(response, textStatus, jqXHR) {
console.log("Response: " + response);
});
},
});
</script>
handle.php:
<?php
if(isset($_POST['name'])) {
echo 'we got it';
} else {
echo 'name not set';
}
?>
Okay, so it seems like everything works, check out the console.log after I fill in the username and leave the company blank:
data: name=testtest&company=
Response: name not set
As you can see, serialize works and grabs all the info, but when handled by handle.php it tells me that the $_POST[] is empty. Looping through it on handle.php proves it:
foreach($_POST as $key=>$value) {
echo "$key: $value
\n";
}
Which doesn't return at all.
I have also tried ajaxSubmit() and form.submit() but I get the same exact results.
This one looks right to me, because I have searched and searched stackoverflow and came across that most of the problems with this is including the 'name' attribute on the input tags, which is already done.
Thanks in advance!!
My issue was irrelevant to my code and ended being a few declarations in the .htaccess. It was redirecting me from a .php file to a directory (for prettier URLS). Now, this is a common technique so:
if you are working on someone else's project and your URL's aren't standard with a file extension, check the .htaccess!
Page.html or .php
<form action="/" id="sky-form-modal" method=
"post" name="sky-form-modal">
<input name="name" placeholder="Name" type="text">
<input name="company" placeholder="Company" type="text">
<button class="button" type="submit">Send request</button>
</form>
<div id="result"></div>
<script>
var request;
$("#sky-form-modal").submit(function(event){
// abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("input, input");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "handle.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
$("#result").html(response);
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
handle.php
<?php
foreach ($_POST as $key => $value) {
echo "POST Key: '$key', Value: '$value'<br>";
}
?>
I removed your labels and classes for the simple look of the form.
i Guess you missed '(' after validation
$("#sky-form-modal").validate {
$("#sky-form-modal").validate ({
Related
I have the following script which, prevents the form from being submitted and then uses ajax to make a call to a page
HERE is my form
<form method="post" action="makeBid.php" name="apply" id="makeBid">
<label for="amount">Bid Amount</label>
<input type="text" id="amount" name="amount" placeholder="Enter Bid Amount"/>
<label for="completionDate">Completion Date</label>
<input type="text" id="completionDate" name="completionDate" placeholder="Completion Date"/>
<label for="apply">Support Your Application</label>
<textarea name="msg" id="msg" class="application" placeholder="Enter A Message To Support Your Application"></textarea>
<button name="apply" id="apply" value="<?php echo $_POST['btnSubmit'] ?>" class="btn btndanger">Apply</button>
</form>
if(isset($_POST['apply'])) {
require_once('../controller/bids.php');
$bid = new Bid();
$bid->setAmount($_POST['amount']);
$amount = $bid->getAmount();
$bid->setDate($_POST['completionDate']);
$date = $bid->getDate();
$bid->setRemarks($_POST['msg']);
$msg = $bid->getRemarks();
echo $bid->processBid($_SESSION['userID'], $_POST['apply'],$amount, $date, $msg);
}
And then my Jquery and AJAX script which prevents default behavior.
$(function () {
var form = $('#makeBid');
var formMessages = $('#formResult');
// Set up an event listener for the contact form.
$(form).submit(function (e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
}).done(function (response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error').addClass('success');
// Set the message text.
$(formMessages).html(response); // < html();
// Clear the form.
$('').val('')
}).fail(function (data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success').addClass('error');
// Set the message text.
var messageHtml = data.responseText !== '' ? data.responseText : 'Oops! An error occured and your message could not be sent.';
$(formMessages).html(messageHtml); // < html()
});
});
});
</script>
The console error im getting is uncaught reference error function is not defined in the first line of my script. As far as I can tell everything looks alright. Would greatly appreciate a second pair of eyes / opinion to scan over my script.
Much appreciated
It looks ok!
Just check if you opened the <script> tag properly, because in the example there is not present.
If you can copy the error and post here could be more usefull !
Two things wrong here:
You PHP code needs to begin with <?php to separate from your HTML
Your ajax response won't be correct because the HTML form is also being sent in the response. You need to either place form action script at another file by itself. Or you need to exclude the HTML form by putting in the else statement of your if(isset($_POST['apply']))
I have form in 100.php with ajax call to 200.php.
<html>
<head>
<!-- include reCAPTCHA API JavaScript library given by Google -->
<script src='https://www.google.com/recaptcha/api.js'></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myaddress = $("#address").val();
var yourData ='name='+myname+'&address='+myaddress; // php is expecting name and age
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '200.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
$('#result').html(data); // here html()
//alert('Submitted');
}else{
return false;
}
}
});
});
});
</script>
</head>
<body>
<form method="post" id="testform">
Name: <input type="text" name="name" value="" id="name"/> <br />
Address: <input type="text" name="address" value="" id="address"/>
<!--
place for the reCAPTCHA widget div with your site key
data-theme="dark" attribute - gives dark version
-->
<div class="g-recaptcha" data-sitekey="6LeJ8h8TAAAAAMS9nQX89XccpsC-SDeSycipiaHN"></div>
<input type="submit" name="ok" value="Send" id="btn"/>
</form>
<div id='result'></div>
</body>
200.php does validate captcha and diaplay name and adddress user entered. But my problem is that when I entered name and address, click on captcha. Captha is also validated and shows as in my screenshot. but name and address is not shown on the page. You can also check yourself here: http://raveen.comlu.com/100.php
I am new to Ajax call by PHP. I googled and I can troubleshoot by firebug. Can you say what I am doing wrong here? and steps to troubleshoot by firebug like to check if my ajax call is done, etc? thanks for your help.
Note: when I put all these code in one page without using ajax call. it works fine!!!!! I want this happens without page reload....
output
200.php
<?php
require_once('recaptchalib.php');
if( isset($_POST['ok']) ){
if( isset($_POST['g-recaptcha-response']) && !empty($_POST['g-recaptcha-response']) ){
$secret = "6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1"; //your secret key
$response = null; //empty response
$reCaptcha = new ReCaptcha($secret); //check secret key is present
$response = $reCaptcha->verifyResponse( $_SERVER['REMOTE_ADDR'], $_POST['g-recaptcha-response'] );
//$response variable will report back with "success"
if( $response!=null && $response->success ){
echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
}
}
else{
echo "<h1>Please click on the reCAPTCHA box.</h1>";
}
}
?>
There are few errors in your code, such as:
Look at the following two statements,
if( isset($_POST['ok']) ){...
and
var yourData ='name='+myname+'&address='+myaddress;
You're not sending any variable named ok to 200.php page, so the control won't even enter the if block.
You're validating reCaptcha in the wrong way. From the documentation:
If your website performs server side validation using an AJAX request, you should only verify the user’s reCAPTCHA response token (g-recaptcha-response) once. If a verify attempt has been made with a particular token, it cannot be used again. You will need to call grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
So you have to use grecaptcha.getResponse() to get the user's response.
And as a sidenote use grecaptcha.reset() to ask the end user to verify with reCAPTCHA again.
Your jQuery/AJAX script should be like this:
<script>
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var recaptchaResponse = grecaptcha.getResponse();
var myname = $("#name").val();
var myaddress = $("#address").val();
var yourData = {name: myname, address: myaddress, recaptchaResponse: recaptchaResponse};
$.ajax({
type: 'POST',
data: yourData,
dataType: 'html',
url: '200.php',
success: function(data) {
// reset form
$('#testform')[0].reset();
// display data
$('#result').html(data);
// reset the reCaptcha
grecaptcha.reset();
},
error: function(jqXHR, textStatus, errorThrown){
// error
}
});
});
});
</script>
And on 200.php page, process your AJAX data like this:
<?php
//your site secret key
$secret = '6LeJ8h8TAAAAAB3IFQVQEaoApFe6lvq4Wxlktvn1';
if(isset($_POST['recaptchaResponse']) && !empty($_POST['recaptchaResponse'])){
//get verified response data
$param = "https://www.google.com/recaptcha/api/siteverify?secret=".$secret."&response=".$_POST['recaptchaResponse'];
$verifyResponse = file_get_contents($param);
$responseData = json_decode($verifyResponse);
if($responseData->success){
// success
echo "<h1>Hi ". $_POST['name']. " from ". $_POST['address']. ", thanks for submitting the form!</h1>";
}else{
// failure
echo "<h1>You have incorrect captcha. Please try again.</h1>";
}
}else{
echo "<h1>Please click on the reCAPTCHA box.</h1>";
}
?>
I have form that has one text input field and a button. On submit form, I take the value from the text field user and make an ajax call to ajax.php to then have the server return the userID. The server is indeed returning a value as shown in the console. But I am not sure why the ajax call is failing on each request after submitting the form. What can I correct or change to have a success?
index.php
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
var getUser = $.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
dataType:'text'
});
getUser.done(function( data ) {
alert(data);
});
getUser.fail(function( jqXHR, textStatus, data ) {
alert( "Request failed: " + textStatus );
});
});
<form id="search" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="GET">
<label for="user"> Username:</label><input type="text" name="user" id="user" value="<?php echo $user ?>"><br>
<button type="submit" id="search">Search</button>
</form>
ajax.php
if(!empty($_GET['user'])){
$user = $_GET['user'];
echo getInstaID($user); // this prints a numeric value like 2057821
}
Perhaps the data is being returned as json or jsonp? You have specified dataType: 'text'. If the return datatype is different it will error out. If you are using a fairly recent version (I think 2.0 or better) leaving out dataType or specifying dataType:"auto" will allow the call to succeed. Then you can debug to figure out how to handle the response.
You might try adding a success function like the following:
$('form').submit(function(e) {
var searchUser = $('input[name="user"]').val();
$.ajax({
type: "GET",
url: "ajax.php",
data: {user: searchUser},
success:function(data){//begin success function
//do something with the data returned from ajax.php file
alert(data);
}//end success function
});
I followed a tutorial to adapt the code. Here I am trying trying to auto-populate my form fields with AJAX when an 'ID' value is provided. I am new to Jquery and can't get to work this code.
Edit 1 : While testing the code, Jquery isn't preventing the form to submit and sending the AJAX request.
HTML form
<form id="form-ajax" action="form-ajax.php">
<label>ID:</label><input type="text" name="ID" /><br />
<label>Name:</label><input type="text" name="Name" /><br />
<label>Address:</label><input type="text" name="Address" /><br />
<label>Phone:</label><input type="text" name="Phone" /><br />
<label>Email:</label><input type="email" name="Email" /><br />
<input type="submit" value="fill from db" />
</form>
I tried changing Jquery code but still I couldn't get it to work. I think Jquery is creating a problem here. But I am unable to find the error or buggy code. Please it would be be very helpful if you put me in right direction.
Edit 2 : I tried using
return false;
instead of
event.preventDefault();
to prevent the form from submitting but still it isn't working. Any idea what I am doing wrong here ?
Jquery
jQuery(function($) {
// hook the submit action on the form
$("#form-ajax").submit(function(event) {
// stop the form submitting
event.preventDefault();
// grab the ID and send AJAX request if not (empty / only whitespace)
var IDval = this.elements.ID.value;
if (/\S/.test(IDval)) {
// using the ajax() method directly
$.ajax({
type : "GET",
url : ajax.php,
cache : false,
dataType : "json",
data : { ID : IDval },
success : process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
}
else {
alert("No ID supplied");
}
};
function process_response(response) {
var frm = $("#form-ajax");
var i;
console.dir(response); // for debug
for (i in response) {
frm.find('[name="' + i + '"]').val(response[i]);
}
}
});
Ajax.php
if (isset($_GET['action'])) {
if ($_GET['action'] == 'fetch') {
// tell the browser what's coming
header('Content-type: application/json');
// open database connection
$db = new PDO('mysql:dbname=test;host:localhost;', 'xyz', 'xyz');
// use prepared statements!
$query = $db->prepare('select * from form_ajax where ID = ?');
$query->execute(array($_GET['ID']));
$row = $query->fetch(PDO::FETCH_OBJ);
// send the data encoded as JSON
echo json_encode($row);
exit;
}
}
I don't see where you're parsing your json response into a javascript object (hash). This jQuery method should help. It also looks like you're not posting your form using jquery, but rather trying to make a get request. To properly submit the form using jquery, use something like this:
$.post( "form-ajax.php", $( "#form-ajax" ).serialize() );
Also, have you tried adding id attributes to your form elements?
<input type="text" id="name" name="name"/>
It would be easier to later reach them with
var element = $('#'+element_id);
If this is not a solution, can you post the json that is coming back from your request?
Replace the submit input with button:
<button type="button" id="submit">
Note the type="button".
It's mandatory to prevent form submition
Javascript:
$(document).ready(function() {
$("#submit").on("click", function(e) {
$.ajax({type:"get",
url: "ajax.php",
data: $("#form-ajax").serialize(),
dataType: "json",
success: process_response,
error: function(xhr) { alert("AJAX request failed: " + xhr.status); }
});
});
});
Im following this question trying to post to a php page and have it perform an action on the data the problem is it seems to just refresh the page and not sure what its doing. In the network tab in element inspector my php page never appears.
Here is my code:
js:
<script>
$(function () {
$("#foo").submit(function(event){
// variable to hold request
var request;
// bind to the submit event of our form
// abort any pending request
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/DormDumpster/session/login-exec.php",
type: "post",
data: json
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
alert("hello");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
alert("bye");
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
});
html:
<form id = "foo" method="post" >
<fieldset id="inputs">
<input id="email" type="email" name="login" placeholder="Your email address" required> <br>
<input id="password" type="password" name="password" placeholder="Password" required>
</fieldset>
<fieldset id="actions"">
<input type="submit" id="submit" name "Submit" value="Log in"">
<label><input type="checkbox" checked="checked"> Keep me signed in</label>
</fieldset>
</form>
php
$email = clean($_POST['login']);
$password = clean($_POST['password']);
Any Ideas to what I am doing wrong or how to figure out what im doing wrong.
You are probably trying to attach the event listener prior to the form being available in the DOM - thus your form won't be found and no event listener will be attached. Try wrapping your code in a DOM-ready callback, to make sure that your form is in the DOM before trying to select it.
$(function () {
$("#foo").submit(function(event){
// All your code...
});
});
More on why and when to use DOM-ready callbacks here.
i think you have to wrap your submit function inside doc ready:
$(function(){
// here your form submit
});
It is always good to note what arguments you are passing as parameters and to check if it is valid within that function or property.
$(function(ready) {
$.ajax({
type: "POST",
url: "/DormDumpster/session/login-exec.php",
data: { name: "John", location: "Boston" },
dataType: "JSON"
})
}
Data to be sent to the server. It is converted to a query string, if
not already a string. It's appended to the url for GET-requests.
- from http://api.jquery.com/jQuery.ajax/