not sure what im missing but im having a few issues with my code im trying to build.
The data is not passing from the form to the database (blank entries)
Its also going to repsonse.php and not staying on the forms page
How can i pass the response for success and error back from response.php to the form to display on the frontend form?
Lastly its adding the data twice (blank entries but twice all the same)
HTML
<form action="response.php" method="post" id="add_product">
<input type="hidden" name="action" value="add_product">
<div class="row">
<div id="response" class="alert alert-success" style="display:none;">
×
<div class="message"></div>
</div>
<div class="col-xs-4">
<input type="text" class="form-control" id="product_name" placeholder="Enter product name">
</div>
<div class="col-xs-4">
<input type="text" class="form-control" id="product_desc" placeholder="Enter product description">
</div>
<div class="col-xs-4">
<div class="input-group">
<span class="input-group-addon"><?php echo CURRENCY ?></span>
<input type="text" id="product_price" class="form-control" placeholder="0.00" aria-describedby="sizing-addon1">
</div>
</div>
</div>
<div class="row">
<div class="col-xs-12 margin-top btn-group">
<input type="submit" id="action_add_product" class="btn btn-success float-right" value="Add product" data-loading-text="Adding...">
</div>
</div>
RESPONSE.PHP
//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}
$action = isset($_POST['action']) ? $_POST['action'] : "";
// Adding new product
if($action == 'add_product') {
$data = $_POST['serialize']; // serialize the data
$product_name = $data['product_name'];
$product_desc = $data['product_desc'];
$product_price = $data['product_price'];
//our insert query query
$query = "INSERT INTO products SET
product_name = '".$product_name."',
product_desc = '".$product_desc."',
product_price = '".$product_price."'
";
//execute the query
if($mysqli -> query($query)) {
//if saving success
echo "User was created.";
} else {
//if unable to create new record
echo "Database Error: Unable to create record.";
}
//close database connection
$mysqli -> close();
}
SCRIPTS.JS
// add product
$('#action_add_product').click(function(){
var $btn = $(this).button('loading');
$.ajax({
url: 'response.php',
type: 'POST',
data: $('#add_product').serialize(),
success: function(result){
$('#response .message').html('Product has been added successfully!');
$('#response').fadeIn();
$btn.button('reset');
}
});
});
The data is not passing from the form to the database (blank entries)
You're missing name attributes on your form inputs. Debugging the output of $('#add_product').serialize() verifies this.
Its also going to repsonse.php and not staying on the forms page
You can set the form action to # (as Harigovind points out), I prefer to bind the submit event of the form instead, and prevent the default execution of the form. This also fixes the issue of people not pressing the button (firing your click event) but using the enter key instead:
$("#add_product").on("submit", function(e) {
e.preventDefault(); // prevent default POST of form
$.ajax({
// etc
});
});
JSFiddle: https://jsfiddle.net/trL5t80w/
Your form is submitting when you click on #action_add_product button. If you want use ajax, you can:
Change your #action_add_product element from button to a with href='#' - that prevent your form from being submitted
Change your js code $('#action_add_product').click(function(){ to something like this: $('#add_product').submit(function(e){
e.preventDefault();
Hi the issue you are facing is because your data is getting posted twice. Since you are using ajax you dont have to give form action. You can replace it by a '#' symbol.
You can also use the jquery prevent default function to prevent the default posting of the form.
Your echo in Response.php will act only as the response to athe ajax call so even if your database query is not executed the result will be you have successfully created the fields.
Also check if your serialized values are correct.
You can get the values of the serialized data just by replacing
$data = $_POST['serialize']; // serialize the data
$product_name = $data['product_name'];
$product_desc = $data['product_desc'];
$product_price = $data['product_price'];
these with
//$data = $_POST['serialize'];
$product_name = $_POST['product_name'];
$product_desc = $_POST['product_desc'];
$product_price = $_POST['product_price'];
You are missing the name attribute of your fields. Any ajax request equivalent to $_GET or $_POST needs the fields.
Related
I have created a chatbot using rivescript and javascript. I want to save the user's messages and chatbot responses to a database.
In html code I have made this form for the messages:
<div id="dialogue"></div>
<form onSubmit="return chatbot.sendMessage()">
<div class="text-box">
<input type="text" name="message" id="message" autocomplete="off" placeholder="Please wait... loading...">
<input class="send-button" type="submit" value=" " id="butsend">
</div>
</form>
</div>
I used a php file named connect.php to connect with the db.
I modified the command:
<form onSubmit = "return chatbot.sendMessage ()"> to
<form onSubmit = "return chatbot.sendMessage ()" method = "POST" "action =" connect.php>
resulting in the user's first message being entered in the database and then a new blank page appearing instead of the dialog.
Ιs there any way to continue the dialogue and at the same time store the data in the database when the send button is pressed?
I have solved the problem using this function:
function writetoDB(inputmessage, outputmessage){
$.ajax({
url: "save.php",
type: "POST",
data: {
user: inputmessage,
botreply: outputmessage,
},
cache: false,
success: function(dataResult){
}
})
}
that calls the php file:
<?php
include 'database.php';
$user=$_POST['user'];
$botreply=$_POST['botreply'];
$sql = "INSERT INTO `dialogs`( `user`, `bot`)
VALUES ('$user','$botreply')";
if (mysqli_query($conn, $sql)) {
echo json_encode(array("statusCode"=>200));
}
else {
echo json_encode(array("statusCode"=>201));
}
mysqli_close($conn);
?>
My problem now is that not all values are imported in database. For example, if there are 20 messages, only 10 are written to the db.
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 have built a simple search tool for my Web App to search through my client database. It returns form submit buttons in a dropdown so that, when a selection is made, the selected clients ID is passed in a POST to the following page. The following page receives this POST and populates with all of the stored information about that client. This works the way I need it to for the most part, but I have a couple questions.
1) most autocompletes/autosuggests that I have seen examples of return JSON data as the results. Is using JSON inherently a smoother or safer process for this?
2) my search results (form buttons) display in a dropdown but are not navigable via TAB or ARROW keys. What is needed to add this accessibility? I tried to add TabIndex to the buttons but that did nothing.
I arrived at this particular solution for my need of a search function after failing miserably to understand some of the pre-packaged Autocomplete solutions out there. They seemed much more complex than what I needed for this Web App.
Here is what I am using.
HTML:
<div class="row">
<div class="col-12">
<input onKeyUp="myFunction()" type="text" id="searchterm" placeholder="Search for existing client">
<div class="searchResults" id="results"></div>
<script>document.getElementById("results").style.visibility='hidden';</script>
<script type="text/javascript" src="js/watchdog.js"></script>
</div>
</div>
JAVASCRIPT:
function myFunction() {
var input = document.getElementById("searchterm").value;
if (input && input.length >= 2) {
$.ajax({
type: "POST",
url: "searchengine.php",
data: {input : input},
success: function(data) {
if (data) {
document.getElementById("results").style.visibility='visible';
document.getElementById("results").innerHTML = data;
}
else {
document.getElementById("results").style.visibility='hidden';
}
}
});
}
else {
document.getElementById("results").style.visibility='hidden';
return false;
}
}
PHP:
<?php
include ('connect.php');
$input = trim($_POST['input']);
$input = htmlspecialchars($input);
$equiv = '%' . $input . '%';
// prepare stmt, bind param, execute
$stmt = $conn->prepare("SELECT client_id, firstname, lastname, city, state FROM client WHERE firstname LIKE ? OR lastname LIKE ?");
$stmt->bind_param("ss", $equiv, $equiv);
$stmt->execute();
$stmt->bind_result($client_id, $firstname, $lastname, $city, $state);
while ($stmt->fetch()) {
echo "
<form name=\"clientSearchResults\" action=\"client.php\" method=\"post\">
<input name=\"client_id\" value=\"$client_id\" type=\"hidden\">
<div class=\"wrapper\">
<input style=\"height: 25px;\" type=\"submit\" value=\"$firstname $lastname - $city, $state\"></input>
</div>
</form>
";
}
// close statement
$stmt->close();
include ('disconnect.php');
?>
Re: TAB key access to submit buttons.
Looking into this further I found the answer to the accessability issue here:
submit-button-not-focused-even-though-tabindex-is-properly-set
This seems to be an issue I encountered because of my laptop being a Mac.
I'm working with Twitter Typeahead to search for users in a database. I want it to show the closest result to their query while they're typing it. I'm using PHP on the backend.
I have the results I want echoing to the page if I add the query to the end of the url manually, and I can see in the Chrome Editor Network tab, that when I'm typing it's sending a request with the query I'm typing. Unfortunately the typeahead search box is never being populated with the results.
Here's the html for the search box:
<div class="row margin-top">
<div class="small-12 large-2 columns">
<input type="text" name="typeahead" class="search typeahead tt-query" autocomplete="off" spellcheck="false" placeholder="Search Here">
<input type="submit" class="button">
</div>
</div>
<!-- JAVASCRIPTS -->
<script src="/js/typeahead.min.js"></script>
<script src="/js/search.js"></script>
Here's my search.js:
$(document).ready(function(){
$('input.typeahead').typeahead({
name: 'typeahead',
remote: {
url : '/admin?query=%QUERY'
},
limit: 1
});
});
And here's the search function in php:
function user_search($key)
{
$link = open_database_connection();
$array = array();
$sql = "SELECT name FROM users WHERE name LIKE '%{$key}%'";
$stmt = $link->prepare($sql);
//Execute
$stmt->execute();
foreach ($stmt->fetchAll(PDO::FETCH_COLUMN) as $row) {
$array[] = $row;
}
return json_encode($array);
}
If I change that last line from return json_encode($array); to echo json_encode($array); it echos the correct results to the page if I add the query to the url manually. But nothing happens when I return them.
The return statement in a function, returns the value to the caller. Obviously, echo sends it to the page. So echo or whatever it is you want to do, where user_search is called.
echo user_search()
I have a page which has a form table. It displays select option when an option is selected the user clicks button and it runs updatephp.php which has query for updating. I need the select to be dynamically updated and display the success/error message like "updated" or "no results" on the screen how can I achieve this. Im not very good at ajax could someone guide me please.
displaytable.php
<form method="POST" action="choosecake.php">
<select id="bakeryid" name="bakeryid">
<option value="">Select</option>
<?php
$sql = "SELECT bakeryid, datefrom FROM cakes";
$sqlresult = $link->query($sql);
$sqllist = array();
if(mysqli_num_rows($sqlresult) > 0) {
while($row = mysqli_fetch_array($sqlresult))
{
echo "<option value=".$row['bakeryid'].">".$row['datefrom']."</option>";
}
$sqlencode = json_encode($sqllist);
echo $sqlencode;
} else {
echo 'No Results were found';
}
?>
</select>
<input type="hidden" value="<?php echo $bakeryid;?>" name="bakeryid"/>
<input type="submit" value="Submit" name="submit"/>
</form>
change your displaytable.php and generate an array of your cakes with id as key and the name as the value. Then echo the json encoded array which can be used directly in js.
Just to get a feeling, didn't test it.
$(document).ready(function() {
window.setTimeout(function() {
$.ajax({
url: "/displaytable.php"
}).done(function(data) {
var select = $('#selectId');
select.empty();
$.each(data, function(val, key) {
select.append($("<option></option>").attr("value", key).text(val);
});
});
}, 10000); // 10 seconds update interval
});
If your page must refresh (no ajax), use displaytable.php to handle the form submission. Then define a variable to hold your success or error message and put this variable where you want the message to display, like
if(!empty($success_message)) {
echo "<h2>$success_message</h2>";
}
When the form is submitted, simply assign a value to $success_message, and since the script handling the form submission is the same script which contains the form, the echo statement in the code above will display your message when the page reloads.