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');
});
});
Related
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.
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'])) {
I am trying to implement a simple form which will eventually connect to a database and make entries in it. In the tag,I am calling the php file which will connect me to the database in the back-end.
index.html
<html>
<head>
<script>
function submitForm(formId){
//var formData= $.(formId).serialize();
$.ajax({
url:'new-user.php',
type:'POST',
data:{
user_name=$("#user_name").val(),
password=$("#password").val();
}
success:function(response){
alert(response);
}
});
}
</script>
</head>
<body>
<form onsubmit="submitForm('#myForm');" id='myForm'>
User Name: <input type="text" name="user_name" id="user_name" />
Password: <input type="text" name="password" id="password" />
<input type="submit"/>
</form>
</body>
</html>
new-user.php
<?php include 'database.php';?>
<?php
mysqli_query($connect,"create table login(User_name varchar(50) NOT NULL,Password varchar(50) NOT NULL)");
$user_name=$_POST['user_name'];
$password=$_POST['password'];
if(empty($user_name)){
$name_error="name is required";
}
mysqli_query($connect,"Insert into login(User_name,Password) values('$user_name','$password')");
if(mysqli_affected_rows($connect)>0){
echo "<p>Credentials added</p>";
echo "<a href='index.html'>Go back</a>";
}else{
echo "<p>Error</p>";
echo mysqli_error($connect);
}
?>
database.php
<?php
$connect=mysqli_connect('localhost','root','','testdb');
if(mysqli_connect_errno($connect)){
echo 'failed to connect';
}
?>
The above is not creating any table in the testdb database.Neither,it is generating any alert messages.The Url however changes after clicking the submit button as http://localhost/try2/?user_name=aayushi&password=ded but after that nothing happens. This is my first php code, so I don't really know what's the meaning of this exactly.
Okay, since no one seems to actually be reading your code, there's a couple of syntax errors that I missed until I threw it into PhpStorm
Change your function to this:
function submitForm(formId){
$.ajax({
url:'/new-user.php',
type:'POST',
data:{
user_name: $("#user_name").val(),
password: $("#password").val()
}
})
.complete(function (response) {
alert(response)
})
return false; // Prevents the form from submitting the standard way
}
EDIT: Change the form to this:
<form onsubmit="return submitForm('#myForm');" id='myForm'>
In your ajax method, the success property is wrong
It is written as suceess, when it was supposed to be success
Also, to avoid refreshing the page, insert return false; at the end of the function submitForm
I take no credit for the JS or AJAX code and I don't understand it. (Thank you Alon Alexander)
I have no AJAX knowledge and I would rather use PHP/JS with no JQuery, but I don't understand how to make it work.
I have a form that uses OnUpdate to fire a JS code that then uses AJAX to perform a SQLi query that should return the search data.
Problem is the return is alway the same even if I use data I KNOW should be returned true (file already exists), but Always returns 'New Entry' in my "Notice" Paragraph
Further, if record found I will then use JS to update form fields with record data. But that is for the next step in this. First need this to work.
i.e. "Record Exists" and form populates with that record info
or "New Entry" and forms stays blank.
index.php //reduced to needed info only
<?php include("process.php"); ?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/phone.js"></script>
<script type="text/javascript" src="js/entrynum.js"></script>
</head>
<body>
<?php
if (isset($_POST['reg-submit'])) {
echo "<p id='notice' style='padding: .5em; border: 2px solid red;'>Entry $entrynum Saved!<br>$timenow on $datenow</p>";
} else {
echo "<p id='notice' style='display: none; padding: .5em; border: 2px solid red;'></p>";
}
?>
<main>
<div class="Container">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<fieldset>
<legend><h1>Registration</h1></legend>
<label for="entrynum">Entry Number</label>
<input type="number" pattern="\d*" name="entrynum" id="entrynum" value="" required="true" placeholder="" autofocus onchange="entry_check()" />
<label for="fname">First Name</label>
<input type="text" name="fname" id="fname" value="" required="true" placeholder="" list="" style="text-transform:capitalize" onkeyup="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />
<label for="lname">Last Name</label>
<input type="text" name="lname" id="lname" value="" required="true" placeholder="" list="" style="text-transform:capitalize" onkeyup="javascript:this.value=this.value.charAt(0).toUpperCase() + this.value.substr(1);" />
<input type="submit" name="reg-submit" id="reg-submit" value="Submit" />
</fieldset> <!-- Registration Form-->
</form>
</div>
</main>
</body>
</html>
entrynum.js
function entry_check() {
var entrynum = $("#entrynum").val();
// Send the AJAX call
$.post(
'entrysearch.php', // TO search.php page
{entrynum: entrynum}, // the DATA sent with the request
function(data) { // a CALLBACK function
if (data == 'none') { // no rows were found or an error occurred
document.getElementById("notice").innerHTML = "New Entry!";
document.getElementById("notice").style.display = "block";
return;
} else {
document.getElementById("notice").innerHTML = "Already Exists!";
document.getElementById("notice").style.display = "block";
}
}
);
}
entrysearch.php
<?php
include("includes/connect.php");
if (!isset($_POST['entrynum'])) {
echo 'none';
die();
}
$sql = $db->prepare("SELECT * FROM HeatWaveData WHERE entrynum=%d", $_POST['entrynum']);
$results = $db->query($sql);
$result = $results[0];
if (!$result) {
echo 'none';
die();
}
echo json_encode($result);
?>
I suggest you to use $.ajax function instead of post.
You can try by adding an id to the form by adding id="myform", then change entrynum.js as it follows:
// Change onSubmit behaviour for the form
$("#myform").on("submit", function(e) {
// Prevent page reload
e.preventDefault();
$.ajax({
// Get form action or uses current page.
url : $(this).attr('action') || window.location.pathname,
type: "POST",
// Get all input to submit and serialize on array (this will become $_POST)
data: $(this).serialize(),
success: function (data) {
//Here you have server response
},
error: function (jXHR, textStatus, errorThrown) {
// If error thrown jXHR contains XMLHttpRequest stuff like status
console.log(jXHR);
// You will see on an alert the real error thrown
alert(errorThrown);
}
});
});
FINALLY! It seems the sql needed a var ($entry) instead of using $_POST['entrynum']... Not sure why.
Then if no records found the ajax would not return anything (not even NULL). So I had to add some if statements and return '0' if no records found.
Further, it helped to add datatype "json' so object was parsed.
Javascript:
function entry_check() {
var entrynum = $("#entrynum").val();
$.post(
'entrysearch.php',
{entrynum: entrynum},
function(data) {
if (!data) {
document.getElementById("notice").innerHTML = "New Entry!";
document.getElementById("notice").style.display = "block";
} else {
document.getElementById("notice").innerHTML = "Already Exists!";
document.getElementById("notice").style.display = "block";
}
}, "json"
);
}
entrysearch.php
<?php
if (isset($_POST['entrynum'])) {
$entry = $_POST['entrynum'];
include("connect.php");
$sql = ("SELECT * FROM HeatWaveData WHERE entrynum = $entry");
if ($results=mysqli_query($db,$sql)) {
if ($rowcount=mysqli_num_rows($results)) {
$result = $results->fetch_object();
echo json_encode($result);
} else {
echo $rowcount;
}
}
}
?>
It works! Took me all night of research reading examples and docs.
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..
}