Ajax and php, result in a div - javascript

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..
}

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

It is not able to auto-post with JS & AJAX

I have a formA that posts and saves to the MYSQL DB
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <== first visable form ,Submitting the data into DB
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
I have a hidden form called PayForm that store some var with hidden input method and get the $input_amount as amount from FromA
It is noted that I haven't made the submit button .
This form is going to post to the EPayment Gateway .
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
...
</form>
Here is my idea workflow :
1)User press "Submit" button in FormA ==> info in FormA is going to store into DB .
2)JS is running . Force the PayForm to post automatically . Then, The user is directed to the Payment Gateway .
In short , the Submit button in FormA trigger both forms post
actions .
Here is my JS
<script type='text/javascript'>
var payFormDone = false;
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // THIS WILL TRIGGER THE NEXT CODE
$('#payForm').submit();
}
});
$("#payForm").submit(function(event) {
/* stop form from submitting normally */
//event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, {
merchantId: $('#merchantId').val(),
amount: $('#amount').val(),
orderRef: $('#orderRef').val(),
currCode: $('#currCode').val(),
mpsMode: $('#mpsMode').val(),
successUrl: $('#successUrl').val(),
failUrl: $('#failUrl').val(),
cancelUrl: $('#cancelUrl').val(),
payType: $('#payType').val(),
lang: $('#lang').val(),
payMethod: $('#payMethod').val(),
secureHash: $('#secureHash').val()
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#FormA').submit();
});
});
</script>
Now ,the idea is not working . It can only trigger second form action .
The first form action is not triggered .At least ,the data in FormA has not saved to the DB .
In short ,
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#payFormCcard').submit();
});
Is not working .I think !
update
This is how I post FormA to the server
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=big5");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Phone = $amount= $Purpose= $Ticket = "";
$CName_err = $Address_err = $Phone_err = $amount_err = $Purpose_err = $Ticket_err="";
// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
$input_CName = trim($_POST["CName"]);
if (empty($input_CName)) {
$CName_err = "Please enter a name.";
} elseif (!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => "/^[a-zA-Z'-.\s ]+$/")))) {
$CName_err = 'Please enter a valid name.';
} else {
$CName = $input_CName;
}
......
if (empty($CName_err) && empty($Address_err) && empty($amount_err) && empty($Phone_err)) {
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName, $Address, $Phone, $amount ,$Ticket ,$Purpose));
Database::disconnect();
}
}
?>
you should not comment event.preventDefault(); from the second form. Currently what happens is it submitting it as default action which is post to url.
Inside posting.done() please remove/detach the onSubmit handler for FormA just before calling the $('#FormA').submit();
posting.done(function( data ) {
alert('success');
$('#FormA').off('submit');
$('#FormA').submit();
});
EDIT:
Okay, why not send the formA fields with AJAX inside its onSubmit handler and submit formB from the posting.done() handler ?
<script type='text/javascript'>
$('#formA').on('submit', function(e){
e.preventDefault();
/* Send the data using post with element id name and name2*/
var posting = $.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>", {
field1: $('#field1').val(),
.....
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
$('#FormB').submit();
}
});
</script>
The submit handler for FormA actually prevents the submission of the form. That's why data is not saved to db.
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // => HERE you are preventing the form from submitting
$('#payForm').submit();
}
});
Here you are in the submit handler for the form, but the call to preventDefault stops the submit for FormA and instead triggers the submit of payForm.
See https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Also instead of having that you trigger via javascript I'd probably send the first one normally. Then as response of the POST in the first form You might print a message to the user with something like: "You are being redirected to the payment gateway.. " and an hidden form with all the fields that is triggered automatically after x seconds. IMHO this approach is easier and more reliable.
So in the first html page I'll remove all your javascript code and leave only:
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
When the user clicks on the button he submits the data to the php page in POST. On the server the data is saved to DB and the server prints a message to the user and redirect to the payment gateway (via javascript this time). Something like:
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') {
.... save data to db
?>
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
<p>You are being redirected to the payment gateway. If the redirect takes too long</p>
<input type="submit" value"click here">
</form>
<script>
// submits the form after 5 seconds
setTimeout(function(){ $('#payForm').submit(); }, 5000);
</script>
<?php } // this ends the POST block ?>
If I correctly understand the question:
<script type='text/javascript'>
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
var $payForm = $("#payForm");
$.post( $payForm.attr('action'), $payForm.serialize(), function(data) {
alert('success');
// redirect to whereever you want
});
});
});
</script>
UPDATE:
case 2) redirecting to payment gateway:
<script type='text/javascript'>
$("#payForm").submit(function(e) {
alert('redirecting to payment gateway');
});
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
$("#payForm").submit();
});
});
</script>
NOTE: replace all your script with just this one, and check in browser if requests are made in the data posted - F12 (Developer tools) - Network tab.
Keep in mind that this code is written on a scratch so it may have some errors, but it shows the way.

AJAX serialized data empty

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'])) {

Can't submit form without reloading page

I build a link shortener,just for fun!
Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;"but it didnt work.
<input class="submit" type="submit" value="Create!" />
$('#contactForm').submit(function () {
sendContactForm();
return false;
});
But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su
PHP
require("db_config.php");
$uid = 1;
$flink = $_POST['url'];
if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
$html = "Error: invalid URL";
} else {
$db = mysqli_connect($host, $username, $password);
$conn = new mysqli($host, $username, $password, $database);
$id = substr(md5(time().$flink), 0, 5);
if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
$html = 'Your short URL is <a class="test" href="https://viid.su/'.$id.'">https://viid.su/'.$id.'</a>';
} else {
$html = "Error: cannot find database";
}
mysqli_close($db);
}
You can submit a form without reloading the page by using something like an AJAX call.
JavaScript
$('#contactForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "path/to/your/script.php",
data: $('#contactForm').serialize(), // Packs the form's elements
success: function(data)
{
// Do something here if the call succeeded
alert(data);
}
});
}
HTML
<form id="contactForm">
<input type="text" name="username" />
<input type="text" name="email" />
<input type="submit" value="Submit form" />
</form>
PHP
<?php
echo $_POST['username'];
?>
Something along those lines should work, and you don't need anything else, as you are already using jQuery.
you need to use event object as parameter in function callback and call event.preventDefault()
Just change the <input type="submit" /> into something like <button onclick="return false;" id="shortenLinkButton">Send</button>
Then with jQuery you can catch the even like this:
// This code will be usable after the page has fully loaded
$(document).ready(function(){
// Catch the onclick event
$('#shortenLinkButton').on('click', function() {
// do something
alert('clicked the button, do your ajax stuff here after retrieving the data from the input');
});
});

Ajax Button to fetch data without refresh?

I would like to know how a button submit can interact with AJAX to SELECT FROM data as a MySQL query without refreshing the page . I already have a text box interacting with AJAX so that the page does not refresh when the user inputs the text and presses enter but have no idea how to make the button do it my code below shows how im getting the text box to insert data without refreshing
Here is my script for the textbox
<div id="container">
About me<input type="text" id="name" placeholder="Type here and press Enter">
</div>
<div id="result"></div>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {name: info},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
};
});
});
</script>
Here is the action
<?php
if (isset($_POST['name'])) {
echo '<h1>'.$_POST['name'];
include('..\db.php');
$con = mysqli_connect($dbsrvname, $dbusername, $dbpassword, $dbname);
$name = $_POST['name'];
$name= mysqli_real_escape_string($con, $name);
$q = mysqli_query($con,"SELECT * FROM tbl1 WHERE username = '".$_COOKIE[$cookie_name]."'");
while($row = mysqli_fetch_assoc($q)){
//echo $row['id'];
$id = $row['id'];
}
$result=$con ->query=("REPLACE INTO about_user (about_me,number) VALUES ('".$name."','".$id."')");
$insert = $con->query($result);
echo "About Me Updated";
}
?>
Now all I need to do is have the below example of a button do something similar but instead of INSERTING just SELECT , how can i change the above script to allow a button to handle the action please?
<form
action="action_mail_view.php" method="post">
<input type="submit" class="button" name='msubmit' value="View Mail"/>
</form>
function callServer() {
$('#mail-button').on('click', function() {
var info = $('#name').val();
$.ajax({
method: "POST",
url: "about_me_action.php",
data: {
name: info
},
success: function(status) {
$('#result').append(status);
$('#name').val('');
}
});
});
}
$(document).ready(function() {
$('#name').focus();
$('#name').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
$('#mail-button').trigger('click');
};
});
});
<form action="action_mail_view.php" method="post">
<input type="submit" class="button" id="mail-button" name='msubmit' value="View Mail" />
</form>
You haven't showed us how you tried to make your button work so how can we give you feedback? Basically you want a similar ajax call that calls action_mail_view.php using the GET method
Ajax
$.ajax({
method: "GET",
url: "action_mail_view.php",
data: {},
success: function(results) {
var userinfo = JSON.parse(results);
//Todo: do what you want with the user's info
}
});
On the PHP side, you should first authenticate the user (not shown here), then SELECT her info from the DB and return it
action_mail_view.php
//Todo: authenticate
//this works with your setup, but it's a bad idea to trust
//a cookie value or anything else coming from the
//browser without verification
$username= mysqli_real_escape_string($con, $_COOKIE[$cookie_name]);
//get the user's info from your DB. By using a JOIN, we can execute
//just one query instead of two.
$sql = "SELECT t2.* FROM tbl1 as t1 "
."LEFT JOIN about_user as t2 "
."ON t1.id = t2.number"
."WHERE t1.username = $username";
//Todo: execute query. see what results you get and refine
// the SELECT clause to get just what you want
if($q = mysqli_query($con,$sql)):
$userinfo = mysqli_fetch_assoc($q);
//tell the browser to expect JSON, and return result
header('Content-Type: application/json');
echo json_encode($userinfo);
else:
//Todo: error handling
endif;

Categories