I have a form that currently after pressing the submit button it changes website to echo a success message. I want when the user clicks the submit button, a message will show him that he successfully added a record, without changing the page. I think the proper way is ajax .
OPEN TO ANY SUGGESTIONS
Below is the form and php file used to insert values into the database
form
<div id="addForm">
<div id="formHeading"><h2>Add Product</h2></div><p>
<form id = "additems" action="../cms/insert.php" enctype="multipart/form-data" method="post"/>
<label for="title">Title: </label><input type="text" name="title"/>
<label for="description">Desc: </label><input type="text" name="description"/>
<label for="price">Price: </label><input type="text" name="price" />
<label for="stock">Quan: </label><input type="text" name="stock" />
<p>
<small>Upload your image <input type="file" name="photoimg" id="photoimg" /></small>
<div id='preview'>
</div>
<select name="categories">
<option value="mens">Mens</option>
<option value="baby_books">Baby Books</option>
<option value="comics">Comics</option>
<option value="cooking">Cooking</option>
<option value="games">Games</option>
<option value="garden">Garden</option>
<option value="infants">Infants</option>
<option value="kids">Kids</option>
<option value="moviestv">Movies-TV</option>
<option value="music">Music</option>
<option value="women">Women</option>
</select>
<input type="submit" id="submit_form" name="Submit" value="Add new item">
</form>
insert.php (used in the form)
session_start();
$session_id='1'; //$session id
$path = "../cms/uploads/";
$valid_formats = array("jpg", "png", "gif", "bmp");
if(isset($_POST) and $_SERVER['REQUEST_METHOD'] == "POST")
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
if(strlen($name))
{
list($txt, $ext) = explode(".", $name);
if(in_array($ext,$valid_formats))
{
if($size<(1024*1024))
{
$actual_image_name = time().substr(str_replace(" ", "_", $txt), 5).".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
$table = $_POST['categories'];
$title = $_POST['title'];
$des = $_POST['description'];
$price = $_POST['price'];
$stock = $_POST['stock'];
$sql="INSERT INTO $table (title, description, price, image, stock)
VALUES
('$title','$des','$price','$path$actual_image_name','$stock')";
if (!mysqli_query($con,$sql))
{
die('Error: ' . mysqli_error($con));
}
die("1 record added into the $table table");
}
else
echo "failed";
}
else
echo "Image file size max 1 MB";
}
else
echo "Invalid file format..";
}
else
echo "Please select image..!";
exit;
}
I have this script but i cant get it to work
<script>
$(document).ready(function () {
$('input#submit_form').on('click', function() {
$.ajax({
url: '../insert.php',// TARGET PHP SCRIPT
type: 'post', // HTTP METHOD
data: {
'title' : $('input[name="title"]').val()
},
success: function(data){
alert(data); // WILL SHOW THE MESSAGE THAT YOU SHOWED IN YOUR PHP SCRIPT.
}
});
});
})
</script>
Your code is fine. The AJAX call is probably happening, but you haven't told he button to stop its default behavior (navigating away). Here is what needs to change. Notice that I've added an event parameter to your callback.
$('input#submit_form').on('click', function(event) {
event.preventDefault(); //Don't do your default behavior, button
$.ajax({
url: '../insert.php',
type: 'post',
data: {
'title' : $('input[name="title"]').val()
},
success: function(data){
alert(data);
},
//if it breaks, you want to be able to press F12 to see why
error: function(data){
window.console.log(data);
}
});
return false;
});
Even if this doesn't work and there is something else wrong with your code, you will at least be able to press F12 after submitting your form to see if there are other errors (500 errors from your php, 404 errors from a bad link, etc). It's not so easy to see what you did wrong when you are directed to the submission page immediately.
Related
I have this "register users" file in which I have a form, I'll simplify in here what I have:
<form action="" method="POST">
<label for="user" class="control-label">User </label>
<input type="text" name="user" class="form-control" id="user" value="" required=""/>
<label for="user" class="control-label">Password1 </label>
<input type="text" name="password1" class="form-control" id="password1" value="" required=""/>
<label for="user" class="control-label">Password2 </label>
<input type="text" name="password2" class="form-control" id="password2" value="" required=""/>
<button type="button" value="signUp" name="submit" class="btn btn-lg btn-primary btn-block" onClick="register()">Sign up!</button>
As you can see, there is an event in there, in a JS file. This file has all the vaidations of the inputs and it works just fine (I don't think it's relevant, so I won't post it). It also has the AJAX call to the PHP file that will insert the data into the database.
function register(){
if(validationRegister()){
$.ajax({
url: "http://localhost/myProject/extras/processSignUp.php",
type: "POST",
data: {"user": user,
"password": password,
"password2": password2,
},
dataType: "html",
cache: false,
beforeSend: function() {
console.log("Processing...");
},
success:
function(data){
if(data == "Registered"){
window.location.href = "http://localhost/myProject/index.php";
}else{
window.location.href = "http://localhost/myProject/signUp.php";
}
}
});
}else{
alert("Incorrect data");
}
}
And this is the PHP file:
<?php
include_once "connection.php"; --> this has all the data for the connection to the database
if($_POST['user'] == '' || $_POST['password'] == '' || $_POST['password2'] == ''){
echo 'Fill all the information';
}else{
$sql = 'SELECT * FROM `user`';
$rec = mysqli_query($con, $sql);
$verify_user = 0;
while($result = mysqli_fetch_object($rec)){
if($result->user == $_POST['user']){
$verify_user = 1;
}
}
if($verify_user == 0){
if($_POST['password'] == $_POST['password2']){
$user = $_POST['user'];
$password = $_POST['password'];
$sql = "INSERT INTO user (user,password) VALUES ('$user','$password')";
mysqli_query($con, $sql);
echo "Registered";
}else{
echo "Passwords do not match";
}
}else{
echo "This user has already been registered";
}
}
?>
The PHP code, works great when used on its own (it used to be at the beginning of the form file, surrounded by if($_POST['submit']){}) But now I want to use it in a separate file, and use AJAX, and I'm unable to register a user :/ the value of data is never "Registered"... Any ideas?
Thanks in advance! :)
Please never run this code in a live environment, your code is open to SQL injection and you NEED to hash passwords.
This line:
if($_POST['user'] == '' or $_POST['password']){
Looks to be your issue. You want to be testing $_POST['password'] somehow, like $_POST['password'] == '' or !isset($_POST['password']).
Your logic is also horribly constructed, you may want to go look at a few tutorials. e.g. why are you fetching ALL your users just to test if one exists, do that logic in the SQL code itself to avoid fetching an entire table for no reason.
Hi i am trying to update data in a database from a form on the same page as the php code without redirecting/reloading the page.
I tried this tutorial but that didn't work: http://www.formget.com/form-submit-without-page-refreshing-jquery-php/
Update code:
<?php
include "db.php";
session_start();
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
?>
Profilecomplete.js:
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {
value: name
}, function(data) {
alert(data);
$('#form')[0].reset(); // To reset form fields
});
}
});
});
The form:
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate">
<label for="name">Value</label>
</div>
<button type="submit" id="submit" class="btn-flat">Update</button>
</form>
Use this, it's working already.
index.php
<form method="post">
<input type="text" id="name">
<input type="submit" id="submit">
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#submit").click(function(e) {
e.preventDefault();
var nameInput = $("#name").val();
var name = {
'name' : nameInput
}
if (nameInput == '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {value: name}, function(data) {
alert(data);
//$('#form')[0].reset(); // To reset form fields
});
}
});
});
</script>
profilecomplete.php
<?php
$_POST = array_shift($_POST); // array_shift is very important, it lets you use the posted data.
echo $_POST['name'];
?>
if you want a more simple way.
try to use $.ajax()
It looks like the issue, or at least, one of the issues, is on this line;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='$_SESSION['user']'");
You are opening and closing the single quotes twice, here
WHERE username='$_SESSION['user']'
Try using this instead;
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='" . $_SESSION["user"] . "'");
How your click event can occur even if you are not preventing the default behavior of the form submit button. Make the submit input as a button or use event.preventDefault() to submit the form via ajax.
<?php
include "db.php";
session_start();
if(isset($_POST)) {
$value=$_POST['name'];
$query = mysqli_query($connection,"UPDATE users SET profiel='$value' WHERE username='{$_SESSION['user']}'");
echo ($query) ? "Updated" : "Not Updated";
exit;
} else {
?>
<form method="POST" id="form">
<div class="input-field col s6">
<input id="name" type="text" class="validate" name="name">
<label for="name">Value</label>
</div>
<button type="button" id="submit" class="btn-flat">Update</button>
</form>
<?php } ?>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var name = $("#name").val();
if (name === '') {
alert("Insertion Failed Some Fields are Blank....!!");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("config/profilecomplete.php", {name: name}, function(data) {
alert(data);
$('form')[0].reset(); // To reset form fields
});
}
});
});
</script>
Consider this image which is an iframe window when user clicks on a link.
My Problem
When user clicks deposit the form gets submitted and the window closes, thus the user does not know if deposit was successful or not.
What I want to do
I am looking for a way to keep the iframe window open after the form has been submitted, to display appropriate message
Form HTML
<form name="depForm" action="" id="register_form" method="post">
User Name<br /><input type="text" name="uname" value="" /><br />
Credit Card Nr<br /><input type="text" name="cc" value="" /><br />
CSV Nr<br /><input type="text" name="csv" value="" /><br />
Amount<br /> <input type="text" name="amount" value="" /><br />
<input type="submit" value="deposit" name="deposit" class="buttono" />
</form>
PHP Code
if(isset($_POST['deposit'])){
if(isset($_SESSION['FBID'])){
$uid=$_SESSION['FBID'];
$amount = $_POST['amount'];
$cc = $_POST['cc'];
$csv = $_POST['csv'];
//new bal
$bal = getBal($uid);
$newBal = $bal+$amount;
$sql="UPDATE members SET balance='$newBal' WHERE member_nr='$uid'";
$result = mysql_query($sql) or die("error please try again");
if($result){
}
}
if anyone can advise me how to keep iframe open after form has been submitted it will be greatly appreciated.
You would need to change the form submission to use AJAX. In the response you can include a state flag to indicate to the UI whether the request was successful or not and act appropriately. Something like this:
$('#register_form').submit(function(e) {
e.preventDefault(); // stop the standard form submission
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function(data) {
if (data.success) {
// show success message in UI and/or hide modal
} else {
// it didn't work
}
},
error: function(xhr, status, error) {
// something went wrong with the server. diagnose with the above properties
}
});
});
$success = false;
if (isset($_POST['deposit'])) {
if (isset($_SESSION['FBID'])) {
$uid = $_SESSION['FBID'];
$amount = $_POST['amount'];
$cc = $_POST['cc'];
$csv = $_POST['csv'];
$bal = getBal($uid);
$newBal = $bal + $amount;
$sql = "UPDATE members SET balance='$newBal' WHERE member_nr='$uid'";
$result = mysql_query($sql) or die("error please try again");
if ($result) {
$success = true;
}
}
}
echo json_encode(array('success' => $success));
I am simply trying to use the data submitted in a search form to query the database and bring back results similar to the search. My form looks like this:
<div id="searchform">
<form method="get">
<form id="submitsearch">
<input id="shop" name="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="submit" value="Go"/>
</form>
</form>
<div id="searchresults">
</div>
</div>
the Javascript I've got is:
$("#submitsearch").submit(function(event) {
event.preventDefault();
$("#searchresults").html('');
var values = $(this).serialize();
$.ajax({
url: "external-data/search.php",
type: "post",
data: values,
success: function (data) {
$("#searchresults").html(data);
}
});
});
return false;
I have also tried...
$("#submitbutton").click(function(){
var form_data = $("#submitsearch").serialize();
$.ajax({
url: "external-data/search.php",
type: 'POST',
data: form_data,
success: function (data) {
$("#searchresults").html(data);
}
});
return false;
});
And this seems to work slightly as it shows results, the first doesn't do anything. It's not sending the data to the PHP page but the PHP I've got is:
<?php
$str_shops = '';
$shop = $_POST['form_data'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE name LIKE '%$shop%'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<strong>" . $row['name'] . "</strong><br>" .
$row['address'] . "<br><br>";
}
mysqli_free_result($result);
echo $str_shops;
mysqli_close($db_server);
?>
Any help would be greatly appreciated! Thanks in advance.
You have two form tags. This won't work. You want one form tag with two attributes
<form method="get">
<form id="submitsearch">
to
<form method="get" id="submitsearch">
you can do it without using html form.
first you call the php page and then display a data within html.
this is what I do?!
<div>
<input id="shop" type="text" placeholder="Find a shop" />
<input id="submitbutton" type="button" value="Go"/>
</div>
<div id="searchresults">
</div>
<script type="text/javascript">
$(function() {
$("#submitbutton").click(function(){
try
{
$.post("root/example.php",
{
'shop':$("#shop").val().trim()
}, function(data){
data=data.trim();
$("#searchresults").html(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>
I'm new to ajax concept. Here i'm trying to insert the user details(signup form) into the database. it inserted the datas into the db succesfully. But, ajax is my problem.
1) i didn't get any error message if form fields are empty. you can see my below codes i've done validation on post.php page. but, it doesn't return the error values. 2) it stores the empty values into database. 3) if datas stored successfully i want to get the success message & if datas failed to store in db i want to get the error message. How should i do these all things?
Ajax.js
$(function () {
$('form').on('submit', function (e) {
$.ajax({
type: 'POST',
url: 'post.php',
data: $('form').serialize(),
success: function(msg) {
if(msg=='error_n')
{
$("#e_name").html('Name required');
}
if(msg=='error_m')
{
$("#e_mobile").html('Mobile required');
}
//success and error alert
if(data="inserted")
{
alert("insertion success");
}
else
{
alert("falid to insert into database");
}
}
});
e.preventDefault();
});
});
Post.php
<?php
include_once('config.php');
$name = trim($_POST["name"]);
$mobile = trim($_POST["mobile"]);
if($name == "")
{
echo 'error_n';
}
if($mobile == "")
{
echo 'error_m';
}
try
{
$stmt = $conn->prepare("INSERT INTO sample ( Name, Mobile ) VALUES ( ?, ? )");
$conn->errorInfo();
$stmt->bindParam('1', $name, PDO::PARAM_STR);
$stmt->bindParam('2', $mobile, PDO::PARAM_STR);
$stmt->execute();
}
catch(PDOException $e)
{
'Query failed to insert into database' .$e->getMEssage();
}
?>
Homepage.php
<p>register here</p>
<div id="light" class="white_content">
Close
<form>
<input type="hidden" name="form" value="values" />
name : <input name="name" id="name" type="text" /><span id="e_name"></span> <br />
mobile : <input name="mobile" id="mobile" type="text" /><span id="e_mobile"></span> <br />
<input type="submit" value="submit" />
</form>
</div>
<div id="fade" class="black_overlay"></div>
After your error messages are returned, you need to stop the script execution. Your current code still tries to add the values and hence overrides your custom error messages. Most probably then your PHP returns your exception message and which is not what your JavaScript is expecting.
if($name == "")
{
echo 'error_n';
die(); // Stop here
}
if($mobile == "")
{
echo 'error_m';
die(); // Stop here
}
Also add echo 'inserted'; when your database insert is successful.