AJAX serialized data empty - javascript

I'm trying to post form data via AJAX.
When I remove the AJAX function and do a standard form POST method the data is being inserted into DB fine. When I console.log the serialized data of the form on submit it shows fine.
It's when the AJAX function is fired that the data seemingly disappears. The function fires as a success but no data is inserted and the formdata variable is seemingly empty. Can anyone shine any light on this?
Here's the code so far -
jQuery/AJAX -
$('#calendar-form').submit(function() {
var formdata = $(this).serialize();
console.log(formdata);
$.ajax({
url: "insert.php",
type: "POST",
data: formdata,
success: function() {
alert('success')
},
error: function() {
alert('ERROR');
}
});
return false;
});
HTML
<form id="calendar-form" action="" method="" accept-charset="utf-8">
<input type="text" name="name" id="name">
<input type="text" name="email" id="email">
<input type="hidden" name="site" id="site" value="<? echo $_SERVER['HTTP_HOST'] ?>">
<input class="submit" type="submit" name="submit" value="Submit">
</form>
PHP
try {
$bd = new PDO("mysql:host=localhost;dbname=;charset=utf8", "", "");
// $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Theres been an error while attempting to connect to the database';
}
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$site = $_POST['site'];
$sql = "INSERT INTO `users`(`name`, `email`, `site`) VALUES ('$name', '$email', '$site')";
try {
$query = $bd->prepare($sql);
$query->bindValue(':name', $name, PDO::PARAM_STR);
$query->bindValue(':email', $email, PDO::PARAM_STR);
$query->bindValue(':site', $site, PDO::PARAM_STR);
if($query->execute()){
echo "Success";
}else{
echo "Failure";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
Note: I've removed DB details for this post but they're there in code.
Console
name=Benji&email=email%40email.com&site=localhost%3A8888 - scripts.min.js:9:117
Network

This is because jQuery's .serialize() does not include the submit button:
No submit button value is serialized since the form was not submitted using a button.
Check the console for the output of your console.log(formdata) - you'll see submit is missing. And since it is missing, the test you do on that value on the back end will fail:
if(isset($_POST['submit'])){
Exactly how to do solve this depends on what you're trying to do. If you just want to make sure the request was a POST (not a GET) you could use:
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
If you want to do basic validation, you could explicitly check each of the expected values are present:
if (isset($_POST['name']) && isset($_POST['email']) && isset($_POST['site'])) {

Related

Page reload and redirect using PHP and Ajax

I have a registration form using php, I'm checking the inputs with a validations and control the submitting form using ajax.
Everything works fine, except, after clicking submit button, Ajax loads the success result, in same registration form, and also not reload the page and redirect.
I want to reload and redirect register.php page to register.php?action=joined using Ajax form submit.
Before Ajax register.php have its own statement, if the registration succsessful ($_GET['action'] == 'joined')* its redirect and destroy the registration form and show success form.*
Please refer on the codes. Can someone help me how to figure this out.
registercontrol.php
<?php
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn = 'Your name must be alphabetical characters';
echo '<p>'.$infofn.'</p>';
}
}
// If form has been submitted process it
if(isset($_POST['submit']) && $_POST['submit'] == 'register')
{
// Create the activasion code
$activasion = md5(uniqid(rand(),true));
try
{
// Insert into database with a prepared statement
$stmt = $db->prepare('INSERT INTO members (fullname) VALUES (:fullname, :email, :active)');
$stmt->execute(array(
':fullname' => $fullname,
':email' => $email,
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
// Send email
$to = $_POST['email'];
$subject = "Verify Your Account";
$body = "<p>Thank you for registering on the demo site.</p>
<p>Hello ".$fullname.", Please click this link to activate your account: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>";
$mail = new Mail();
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
// Redirect to index page
header('Location: register.php?action=joined');
exit;
// Else catch the exception and show the error.
}
catch(PDOException $e)
{
$error[] = $e->getMessage();
}
}
?>
register.php and ajax validations
<script type="text/javascript">
$(document).ready(function() {
$("#fullname").keyup(function(event) {
event.preventDefault();
var fullname = $(this).val().trim();
if(fullname.length >= 1) {
$.ajax({
url: 'registercontrol.php',
type: 'POST',
data: {fullname:fullname},
success: function(response) {
// Show response
$("#vfullname").html(response);
}
});
} else {
$("#vfullname").html("");
}
});
$('#submit').click(function(event) {
event.preventDefault();
var formData = $('#register-form').serialize();
console.log(formData);
$.ajax({
url: 'registercontrol.php',
method: 'post',
data: formData + '&submit=register'
}).done(function(result) {
$('.hidden').show();
$('#result').html(result);
})
});
});
</script>
<?php
// If action is joined show sucesss
if(isset($_GET['action']) && $_GET['action'] == 'joined')
{
echo '<div>
<p>Registration is successful, please check your email to activate your account.</p>
</div>';
}
else
{ ?>
<div>
<h1>Create an Account!</h1>
</div>
<form id="register-form" role="form" method="post"
action="registercontrol.php" autocomplete="off">
<input type="text" name="fullname" id="fullname" placeholder="Your name" value="" required>
<div id="vfullname"></div>
<input type="email" name="email" id="email" placeholder="Your Email" value="" required>
<input id="submit" type="submit" name="submit" value="Create Account">
<p class="hidden">Please check everything.</p>
<div id="result"></div>
</form>
<?php } ?>
Thank you.
Check the done block and perform your redirect with JavaScript:
$('#submit').click(function(event){
event.preventDefault();
var formData = $('#register-form').serialize();
console.log(formData);
$.ajax({
url: 'registercontrol.php',
method: 'post',
data: formData + '&submit=register'
}).done(function(result){
var url_to_redirect = "register.php?action=joined";
window.location.href = url_to_redirect;
})
});

Submit and fetch data without refreshing the page

I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with

Textbox not clearing after ajax call

I have this chat room on my website, where the user types their message into a textbox and when they press enter (or the send button), jQuery takes the data from the textbox, disables the textbox, sends the data to the file send.php where it is then processed and put into the database, and then it should clear and undisable the textbox once it successfully runs through the PHP script. What is happening is the data is being submitted and it runs through the script (sends the data to the database successfully) but the jQuery is not clearing and undisabling the textbox.
Can someone explain to me what is wrong?
jQuery:
$('#formSend').on('submit', function (e) {
e.preventDefault();
var textArea = document.getElementById('styled');
if( textArea.value != "" ) {
var formData = $('form').serialize();
$('.expand').prop("disabled", true)
$.ajax({
type: 'post',
url: 'send.php',
data: formData,
dataType: "json",
success: function (formData) { //put data in parentheses when coming back
alert("Success");
$(".expand").val('');
$('.expand').prop("disabled", false);
if( formData["banned"] == 1 ) {
var rel = confirm("You have been banned.");
if (rel) {
location.reload();
}
else {
location.reload();
}
}
}
});
}
else {
alert("Your message must be longer than 1 (one) character.");
$('#styled').focus();
}
});
send.php:
<?php
include("../config.php");
session_start();
$msg = strip_tags( $_POST['msg'], '<b></b>' );
if( $msg == "" ) {
exit("There is no message.");
}
$username = $_SESSION['USER'];
$date = new DateTime();
$formattedDate = $date->format('Y-m-d H:i:s');
$stmt = $db->prepare("SELECT id, username FROM users WHERE username = :username");
$stmt->execute(array(":username" => $username));
$row = $stmt->fetch();
$userID = $row['id'];
$checkBanned = $db->prepare('SELECT banned FROM users WHERE username = :username');
$checkBanned->execute(array(
':username' => $username
));
$banned = $checkBanned->fetch();
if( $banned['banned'] == "yes" ) {
$return = array('banned' => 1);
echo json_encode($return);
exit;
}
try {
$stmt = $db->prepare('INSERT INTO `chat-messages` (userID,msg,date) VALUES (:userID, :msg, :date)');
$stmt->execute(array(
':userID' => $userID,
':msg' => $msg,
':date' => $formattedDate
));
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Here is the form too, if needed.
<form action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="hidden" name="banned" value="no" />
<input type="submit" name="submit" value="Send" class="send" />
</form>
I think the problem is you have not sent any responce if user is not banned and message is stored successfully.
If "success" is not being alerted then that is the problem.
Try this,
try { $stmt = $db->prepare('INSERT INTO `chat-messages` (userID,msg,date) VALUES (:userID, :msg, :date)'); $stmt->execute(array( ':userID' => $userID, ':msg' => $msg, ':date' => $formattedDate ));
$output = "success";
} catch(PDOException $e) { $output = $e->getMessage(); }
finally{
echo json_encode($output);
}
I see you are refreshing the page afterwards, that could make the form to autocomplete to the previous value, try this:
<form autocomplete="off" action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="hidden" name="banned" value="no" />
<input type="submit" name="submit" value="Send" class="send" />
</form>
If you dont want to reload the page (which should actually happen, if you dont prevent the submit event from beeing triggered in the ajax callback by event.preventDefault()) you have to reset the form by doing something like $('#formSend').reset();
Furthermore, there is no disabled='false', you need to remove the attribute: $('.expand').removeAttr('disabled');.
By the way, it is good habit to save selector you need more than one time ;)
Have you tried something like:
$('.expand').removeAttr("disabled");

Ajax and php, result in a div

I want show the result of my server page in the "result" div.
This is my scheme:
home.php
<script src="myscripts.js"></script>
<div id="loginform">
<div id="result"></div>
<?php include_once 'core.login.php'; ?>
</div>
myscripts.js
$(document).ready(function() {
$('#login').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#result').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
core.login.php
<?php
// stuff about $db variable e other stupid things like $tool = new Tools etc...
$email = $_POST["email"];
$password = $_POST["password"];
// Initializing login process
if (isset($email) or isset($password)) {
$tool->decode($email, $password, $db);
}
?>
<form action="core.login.php" method="POST" id="login">
<fieldset>
<legend>Data login:</legend>
Email:<input id="email" type="email" name="email" placeholder="someone#example.com" required>
<br>
Password:<input id="password" type="password" name="password" required>
<br>
<input type="submit" value="Submit">
</fieldset>
</form>
class.php
public function decode($email, $password, $db) {
if ($stmt = $db->prepare("SELECT password FROM users WHERE email = ?")) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($password_db);
$stmt->fetch();
if ($stmt->num_rows == 1) {
if ($password == $password_db) {
echo "Success";
} else {
echo "Error";
}
} else {
echo "Email didn't found!";
}
}
}
Without AJAX if i start the code normally it work, it give me the correct echo result ( success or error ) but when i use AJAX, nothing happen.
UPDATE
Ok guys the problem was the action url, my core file is in the folder core/core.login.php, now it display the page in the result div, but the page core show me this now:
Fatal error: Call to a member function decode() on a non-object in website on line 9
Maybe ajax don't pass the variables like object?
Try this js
$(document).ready(function() {
$('#login').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $("#login").serialize(), // get the form data
type: $(#login).attr('method'), // GET or POST
url: $(#login).attr('action'), // the file to call
success: function(response) { // on success..
$('#result').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
Try with that in your js file:
(Or Document)
$('#loginform').on('submit', '#login', function() {
//AJAX etc..
})
instead of :
$('#login').submit(function() {
//AJAX etc..
}

Problems getting data from AJAX to PHP (and back)

The idea is that this script POSTs the value of the text input in my html form to emailform.php, which takes that data and adds it to a .txt file. I think what I'm having trouble with is setting the value of $email in the PHP to that of the html text input. As a result, currently when the script is triggered I get two alerts (first 'error' then 'complete', from the .fail and .complete functions) and then the page reloads. That's why I think the problem is with the information being returned from the PHP but maybe I'm wrong.
<form method="post">
<input type="text" name="email" value="" class="emailSubmitSidebar" placeholder=" Your Email">
<input type="submit" name="submit" value="Add" class="submitButton" id="subscribeButton">
</form>
<script type='text/javascript'>
$(document).ready(function() {
var subscribeButton = $('#subscribeButton');
subscribeButton.click(function() {
$.ajax({
url: 'emailform.php',
type: 'POST',
dataType: 'text',
data: {email: $("input[name=email]").val()},
})
.done(function(data) {
alert("Added!");
})
.fail(function() {
alert("error");
})
.always(function() {
alert("complete");
})
})
})
</script>
And below is the PHP, I've added the first two lines to check for any errors, of which there are none anymore. What's strange is that when I run the PHP separately, the echo line prints the number 3 on the page without any apparent cause. I commented out the variable $email because I was led to believe it was better/necessary to first check if it isset.
<?php
ini_set('display_errors', 'On');
error_reporting(E_ALL);
$fileHandle = fopen('emailList.txt', 'a') OR die ("Can't open file\n");
$email= isset($_POST['email']) ? $_POST['email'] : "";
// $email=$_POST['email'];
$result = fwrite ($fileHandle, "$email; \n");
fclose($fileHandle);
echo (!$result) ? "error" : $result;
die;
?>
I think there is something wrong with your data, try to serialize it into a json data array:
var data = $(form).serialize();
$.ajax({
url: 'emailform.php',
type: 'POST',
dataType: 'text',
data: data,
})
The values will be sent as a normal post request, so the email address will be in $_POST['email'];
Updated from here
The jquery .done() and .fail() functions require http status codes to work, so your php file should return these codes. When a request is made and succeeded anything in the 200 range will be ok. While on an error, something from the 400 or 500 range should be returned. There is a full list here: http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html
So the ajax .success function is fired when 2xx is returned (replace .done with .success) and the .error is called when status code 4xx or 5xx is returned. See php below how to implement this.
The number 3 you are getting is the $return value of the fwrite function, according to: http://nl3.php.net/fwrite
fwrite() returns the number of bytes written, or FALSE on error.
Make your php like this:
<?php
//ini_set('display_errors', 'On');
//error_reporting(E_ALL);
if($fileHandle = fopen('emailList.txt', 'a')) {
if(isset($_POST['email']) && !empty($_POST['email'])) {
$email = $_POST['email'];
$result = fwrite ($fileHandle, "$email; \n");
fclose($fileHandle);
if(isset($result) && !empty($result)) { // Something was written
http_response_code(200);
echo "File written";
} else { // Writing failed
http_response_code(500);
echo "Writing of file failed";
}
} else { // Empty email
http_response_code(500);
echo "Email was empty";
}
} else { // File could not be opened
http_response_code(500);
echo "File could not be opened for writing";
}
?>
(Simple)
Change HTML to:
<input type="text" name="email" value="" class="emailSubmitSidebar" placeholder=" Your Email">
Change JS to :
$.ajax({
url: 'emailform.php',
type: 'POST',
dataType: 'text',
data: {email: $("input[name=email]").val()}
})
.done(function(data) {
// there checking
alert("success!")
})
Change PHP to:
$fileHandle = fopen('emailList.txt', 'a') OR die ("Can't open file\n");
$email=$_POST["email"];
$result = fwrite ($fileHandle, "$email; <br/>");
fclose($fileHandle);
echo (!$result)? "error" : $result;
die;

Categories