I have a php file that has jquery ajax on it to submit a form and save its contents into a mysql without doing a page refresh.
My issue is if I load the file that the ajax call does the contents are saved into the database however if I try to use the form nothing gets saved to the database even though I get a success message.
Here is my code
The HTML file
<div id='backinstock-form'>
<form>
<input id='instockemailadr'>
<input id='instockpid' value='5' type='hidden'>
<input name='submit' class='submitbackinstock' type='button' value='Submit'>
</form>
<span class='error' style='display:none'> Please Enter A Valid Email</span>
<span class='success' style='display:none'> Email Submitted Success</span>
</div>
require(['jquery'], function($)
{
$(".submitbackinstock").click(function()
{
var instockemailadr = $("#instockemailadr").val();
var instockpid = $("#instockpid").val();
var dataString = 'usereaddr='+ instockemailadr + '&sku=' + instockpid;
if(instockemailadr =='' || instockpid =='')
{
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
}
else
{
//console.log(dataString);
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
$.ajax({
type: "POST",
url: "<?php echo $block->getBaseUrl(); ?>/pub/media/theme_customization/backin-stock-email-code/backinstock_process_email.php",
data: dataString,
success: function(){
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
The PHP File
<?php
// MySQL portion
$conn = mysqli_connect("localhost", "root", "root");
mysqli_select_db($conn,"multisitedb");
$usereaddr = mysqli_real_escape_string($conn, $_POST['usereaddr']);
$stockproductid = mysqli_real_escape_string($conn, $_POST['sku']);
$created_on = date('Y-m-d h:i:s');
$result = mysqli_query($conn, "INSERT INTO multisitedb.backinstock_email_addresses(email_addr, product_sku, created_on)
VALUES ('$usereaddr','$stockproductid','$created_on')");
if($result) {
echo $result; // or whatever you want
} else {
echo "Something went wrong.";
}
?>
First, you didn't specify a Database in your php script. The format is mysqli_connect(host, username, password, database);
Secondly, your ajax code seems wrong. You're making a post request. The data should be an instance of formData(). You can modify this way:
var dataString = new formData();
dataString.append('usereaddr', instockemailadr);
dataString.append('sku',instockpid);
//...
data: dataString,
success: function(){
Also, your PHP script is not doing security checks. You need to validate user inputs as well as use prepared statements to prevent against SQL injection attack.
Related
I would like some help with ajax. I would like to update a php file which will update a database. I have a form which send the selected check box to a php file which then updates the data base. I would like to do this with ajax but I am struggling with this. I know how to update <div> Html elements by ajax but cannot work this out.
HTML script
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
var boiler = document.getElementByName("boiler").value;
var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function() {
alert("ok");
}
});
}
</script>
</body>
</html>
PHP updateDB.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password="14Odiham"; // Mysql password
$db_name="heating"; // Database name
$tbl_name = "test";
// Connect to server and select database.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
// Insert data into mysql
$sql = "UPDATE $tbl_name SET boiler=$boiler WHERE id=1";
$result = mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Successful";
echo "<BR>";
}
else {
echo "ERROR";
}
?>
<?php
//close connection
mysql_close();
header ('location: /ajax.php');
?>
I would like this to update with out refreshing the page.
I just want some suggestion and first your html page code should like-
<html>
<head>
<script src="jquery-3.1.0.min.js"></script>
</head>
<body>
<form name="form" id="form_id">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
<script>
function myFunction() {
// it's like cumbersome while form becoming larger so comment following three lines
// var boiler = document.getElementByName("boiler").value;
// var niamh = document.getElementByName("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
//var dataString = 'boiler=' + boiler + 'niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
// instead of type use method
method: "POST",
url: "updateDB.php",
// instead dataString i just serialize the form like below this serialize function bind all data into a string so no need to worry about url endcoding
data: $('#form_id').serialize(),
cache: false,
success: function(responseText) {
// you can see the result here
console.log(responseText)
alert("ok");
}
});
}
</script>
</body>
</html>
Now i am turning to php code:
You used two line of code right in php
$boiler = (isset($_GET['boiler'])) ? 1 : 0;
$niamh = (isset($_GET['niamh'])) ? 1 : 0;
$_GET is used in get method and $_POST for post method, thus you are using post method in ajax and above line of code should be like
$boiler = (isset($_POST['boiler'])) ? 1 : 0;
$niamh = (isset($_POST['niamh'])) ? 1 : 0;
Update:
As well as fixing the dataString, stop the form from being submitted so that your function is used:
<form name="form" onsubmit="return false;">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<button onclick="myFunction()">Update</button>
</form>
The ajax call should handle returned data from updateDb.php.
Update the php file to send data back to the server, revert to $_POST instead of $_GET and remove the header call at the bottom:
if($result){
$data['success'=>true, 'result'=>$result];
} else {
$data['success'=>false];
}
echo json_encode($data);
// die(); // nothing needed after that
Update the ajax call to handle the response and fix your dataString with '&' between params (This is why you are not getting your params properly).
var dataString = 'boiler=' + boiler + '&niamh=' + niamh;
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: dataString,
cache: false,
success: function(data) {
var json = $.parseJSON(data);
if(json.success){
// update the page elements and do something with data.results
var results = data.results;
} else {
// alert("some error message")'
}
}
});
}
document.getElementByName not a javascript function, try document.getElementById() instead
You can do this
<form name="form" onsubmit="myfunction()">
<input type="checkbox" id="boiler" name="boiler">
<input type="checkbox" id="niamh" name="niamh">
<input type="submit" value="Update"/>
</form>
Javascript:
function myFunction() {
var boiler = document.getElementById("boiler").value;
var niamh = document.getElementById("niamh").value;
// Returns successful data submission message when the entered information is stored in database.
// i dont practice using url string in ajax data as it can be compromised with a quote (') string, instead i am using json
// AJAX code to submit form.
$.ajax({
type: "POST",
url: "updateDB.php",
data: {
boiler: boiler,
niamh: niamh
},
cache: false,
}).done(function() {
alert('success');
}); // i do this because some jquery versions will deprecate the use of success callback
}
And you are getting to a post so change the $_GET in you php file to $_POST
I'm trying to create a form for changing a users password. No errors are being generated in the console but nothing is being updated. The validation side is also working so it must be down to the Ajax part?
Disclaimer: I know I shouldn't be using mysql in PHP, but I'm trying to get the basics down and will learn mysqli at a later date :)
Also, config.php is used in multiple other functions so I know config.php is fine.
Any idea what is going wrong?
HTML:
<fieldset>
<form method="post" name="password-form" id="form-password">
<label>Password:</label> <br>
<input type="password" name="password" id="password" value="" size="32" />
<br>
<br>
<label>Re-Enter Password:</label> <br>
<input type="password" name="password-check" id="password-check" value="" size="32" />
<br>
<br>
<input type="submit" value="Submit" id="passsubmit">
</form>
</fieldset>
JQuery:
$(function(){
$("#passsubmit").click(function(){
$(".error").hide();
var hasError = false;
var newpass = $("#password").val();
var checkVal = $("#password-check").val();
if (newpass == '') {
$("#password").after('<span class="error">Please enter a password.</span>');
hasError = true;
} else if (checkVal == '') {
$("#password-check").after('<span class="error">Please re-enter your password.</span>');
hasError = true;
} else if (newpass != checkVal ) {
$("#password-check").after('<span class="error">Passwords do not match.</span>');
hasError = true;
}
if(hasError == true) {return false;}
if(hasError == false) {
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: {newpass:newpass},
success: function(){}
});
};
});
});
PHP:
<?php
session_start();
include('config.php');
$user_check=$_SESSION['login_user'];
$newpass=$_POST['newpass'];
$sql_rec = "select UserID from useradmin where username='$user_check' ";
$rs_rec = mysql_query($sql_rec);
$data_rec = mysql_fetch_object($rs_rec);
$userID = $data_rec->UserID;
$updatesql="UPDATE useradmin SET passcode='$newpass' WHERE UserID=$userID";
mysql_query($updatesql, $bd) or die(mysql_error());
?>
$bd is my MySQL connection details from config.php.
UPDATE:
I've added <div id="passsubmit2">123</div> to my page and changed the jquery to:
$(function(){
$("#passsubmit2").click(function(){
And it works perfectly, so it's only when using the form button that it doesn't work?
Figured it out eventually.
I needed to add event.preventDefault(); to prevent the normal form submit from firing.
Since you are sending form data to your server through an Ajax request, you dont need that input of submit type at first place, because this will try to submit the form on click and you will have to write additional code for stopping the default functionality of that submit button. So replace that submit button with simple html button or a link.
change your data inside ajax to
if(hasError == false) {
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: {
newpass : newpass,
},
success: function(){}
});
};
because you are not sent the data to server and info variable not declared
Make sure to pass all the required data to the PHP server. Right now, from what I can see, you are passing an empty variable.
info={
newpass : newpass,
checkVal: checkVal
};
$.ajax({
type: "POST",
url: "resource/changepassword.php",
data: info,
success: function(response){
console.log(response);
}
});
On the PHP side:
<?php
$newPassword=$_POST['newpass '];
EDIT: Going a bit further with this, you really want to store a user ID (unique numeric ID) in the session rather then the username. Referencing through-out your mysql DB using the username as a unique value is a very poor idea (trust me, I made the same mistake).
Also, you should require users to enter their old password whenever changing a current password (what if they left the website up on their computer).
I have a couple of scripts i have written below that work great seperately, but together they don't work as they should. Let me post the code and then explain the issue:
Autosave function:
<script>
function autosave() {
$('form').each(function() {
var string = $(this).closest('form').serialize();
var $this = $(this);
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
var saveIcon = $this.siblings('.saveIcon');
$this.siblings('[type=hidden]').val(data);
saveIcon.fadeIn(750);
saveIcon.delay(500).fadeOut(750);
$('#message').text('The id of the inserted information is ' + data);
}
});
});
}
setInterval(autosave, 10 * 1000);
</script>
AJAX post and return script:
<script>
$(document).ready(function() {
$('body').on('click', '.save', function(e) {
var string = $(this).closest('form').serialize();
var $this = $(this);
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
var saveIcon = $this.siblings('.saveIcon');
$this.siblings('[type=hidden]').val(data);
saveIcon.fadeIn(750);
saveIcon.delay(500).fadeOut(750);
$('#message').text('The id of the inserted information is ' + data);
}
});
});
});
$(document).ready(function(){
$('#addForm').on('click', function(){
$('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
});
});
</script>
Form:
<form method="post" action="add_room.php">
<label for="itemName[]">Item</label>
<input type="text" name="itemName[]">
<label for="itemPhoto[]">Item</label>
<input type="text" name="itemPhoto[]">
<input type="hidden" name="itemId[]" value="">
<input type="hidden" name="itemParent[]" value="<?=$_GET['room']?>">
<div class="saveIcon" style="display: none; color: green;">SAVED!</div>
<div class="save">Save Item</div>
</form>
PHP:
<?PHP
require_once('dbConfig.php');
$item = $_POST['itemName'];
$photo = $_POST['itemPhoto'];
$id = $_POST['itemId'];
$parentId = $_POST['itemParent'];
foreach($item as $key => $val) {
if(!$id[$key]) {
if ($stmt = $db->prepare("INSERT test (test_title, test_desc, test_parent) VALUES (?, ?, ?)"))
{
// Use an s per variable passed to the string, example - "ss", $firstname, $lastname
$stmt->bind_param("ssi", $val, $photo[$key], $parentId[$key]);
$stmt->execute();
$stmt->close();
echo $db->insert_id;
//echo "success";
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare Insert SQL statement.";
}
}
else
{
if ($stmt = $db->prepare("UPDATE test SET test_title = ?, test_desc = ? WHERE test_id = ?"))
{
// Use an s per variable passed to the string, example - "ss", $firstname, $lastname
$stmt->bind_param("ssi", $val, $photo[$key], $id[$key]);
$stmt->execute();
$stmt->close();
echo $id[$key];
//echo "success";
}
// show an error if the query has an error
else
{
echo "ERROR: Could not prepare Update SQL statement.";
}
}
}
?>
Now, what happens with the second script is, when used on its own without the autosave, when you fill out the form and click save it takes that forms data and saves it to the necessary rows in a database, and then returns the id of what was just saved and puts that data in a hidden field so that the php script can work out if an insert query is needed or an update query is needed(when the returned id is present). There is also a clickable div called addForm which then appends another form set below the one(s) present and again, when it's save button is clicked ONLY this form is saved/updated in the database. When i trigger the autosave like i have in my code, the autosave literally takes ALL the forms and saves them as new entries but doesn't return the id/update the hidden field to trigger the update sequence. Can you shed ANY light on this at all? It's really bugging me. Have tried explaining this as best i can, sorry it's so long. It's a bit of a complicated one! haha
I'd suggest a few changes to the organization of the code, which then leads to making it easier to identify the errors.
http://pastebin.com/0QTZzX6X
function postForm(form) {
var $this = $(form);
var string = $this.serialize();
$.ajax({
type: "POST",
url: "add_room.php",
data: string,
cache: false,
success: function(data){
var saveIcon = $this.find('.saveIcon');
$this.find('[type=hidden]').val(data);
saveIcon.fadeIn(750);
saveIcon.delay(500).fadeOut(750);
$('#message').text('The id of the inserted information is ' + data);
}
});
}
function autosave() {
$('form').each(function() {
postForm(this);
});
}
setInterval(autosave, 10 * 1000);
$(document).ready(function() {
$('body').on('click', '.save', function(e) {
postForm($(this).closest('form').get(0));
});
$('#addForm').on('click', function(){
$('<form method="post" action="add_room.php"><label for="itemName[]">Item</label><input type="text" name="itemName[]"><label for="itemPhoto[]">Photo</label><input type="text" name="itemPhoto[]"><input type="hidden" name="itemId[]" value=""><input type="hidden" name="itemParent[]" value="<?=$_GET["room"]?>"><div class="saveIcon" style="display: none; color: green;">SAVED!</div><div class="save">Save Item</div></form>').fadeIn(500).appendTo('.addItem');
});
});
Basically i took logic that was duplicated and placed it into a more generic function.
My problem right now:
No values are getting updated on a specific ID as specified (hardcoded) in the WHERE clause.
Anyone see what I'm doing wrong?
I have a form with about 7 fields to fill out. Currently, I am just trying to get the code to work with a hardcoded SQL query like WHERE fanID=2 then I will get it to work later with session variables.
I have (3) files:
HTML:
<form method="post" id="FanDetail">
<textarea id="bio" name="fan_bio" />
<input id="dob" name="fan_dob" />
<input id="actualZip" />
<input id="actualOccup" />
<input id="fbkurl" />
<input id="twiturl" />
<input id="phoNum" />
</form>
a JS file, linked to in the HTML file:
$(document).ready(function(){
$("form#FanDetail").submit(function() {
// store the values from the form input box, then send via ajax below
var bio = $('#bio').attr('value');
var dob = $('#dob').attr('value');
var zip = $('#actualZip').attr('value');
var occup = $('#actualOccup').attr('value');
var fbkurl = $('#fbkurl').attr('value');
var twiturl = $('#twiturl').attr('value');
var phoNum = $('#phoNum').attr('value');
$.ajax({
type: "POST",
url: "../../../php/registration/about/submitvalues_about_tab.php",
data: "bio="+ bio +"& dob="+ dob +"& zip="+ zip +"& occup="+ occup +"& fbkurl="+ fbkurl +"& twiturl="+ twiturl +"& phoNum="+ phoNum,
success: function(){
$('form#FanDetail').hide(function(){$('div.success').fadeIn();});
}
});
return false;
});
});
A PHP file, that is linked to by the above JS File:
///////////////////////////////////////////////
######## Get Input to Submit ############## //
///////////////////////////////////////////////
$fanBio = $_POST['fan_bio']; //////
$fanDob = $_POST['fan_dob']; //////
$zipval = $_POST['actualzipval']; //////
$occupval = $_POST['actualOccupval'];//////
$facebookurl = $_POST['fan_fbk']; //////
$twitterurl = $_POST['fan_twit']; //////
$phoneNum = $_POST['fan_pho']; //////
///////////////////////////////////////////////
try{
## Get current user and their session ID:
$sessionvar = session_id();
### DB Connection already established above.
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
// INSERT CLEAN DATA INTO TABLEā¦
$sth = $dbh->prepare("
UPDATE Fan
SET fanBio=?,fanDob=?,fanDetLocID=?,occupID=?,fanFbk=?,fanTwit=?,fanPho=?
WHERE fanID=2
");
$sth->bindParam(1,$fanBio);
$sth->bindParam(2,$fanDob);
$sth->bindParam(3,$zipval);
$sth->bindParam(4,$occupval);
$sth->bindParam(5,$facebookurl);
$sth->bindParam(6,$twitterurl);
$sth->bindParam(7,$phoneNum);
$sth->execute();
}
catch(PDOException $e){
file_put_contents('../../../../PDODBConnectionErrors.txt','ERROR: [submitvalues_about_tab.php] about '.$e->getMessage(), FILE_APPEND);
}
I'm quite new to jQuery .ajax(), so go easy on me.
However, I'ved trouble shooting:
Check error log in the catch{} above - was initialially getting errors with my query, but I had fixed them and NOTHING appears in it anymore.
Tested query itself by hardcoding values - inputs fine.
Checked to make sure jquery file/php file are linked properly -> they are.
Thanks
One suggestion - .post() and serialize() to minimize your code a little:
$(document).ready(function(){
$("form#FanDetail").submit(function() {
$.post(
"../../../php/registration/about/submitvalues_about_tab.php",
$("form#FanDetail").serialize(),
function(){
$('form#FanDetail').hide(function(){
$('div.success').fadeIn();
});
});
return false;
});
});
I have successfully used ajax to refresh in-line, via ajax, a contact form. I'm having a bit more difficulty getting it to work with data being sent to mysql. I appreciate that what I have so far is not intended to be refreshed via ajax so it might need some work. Here's what I've got... and any help is appreciated.
Form
<form name="email_list" action="">
<p><strong>Your Email Address:</strong><br/>
<input type="text" name="email" id="email" size="40">
<input type="hidden" name="sub" id="sub" value="sub">
<p><input type="submit" name="submit" value="Submit Form" class="email_submit"></p>
</form>
JQuery
$(function() {
$('.email_submit').submit(function() {
var email = $("input#email").val();
if (name == "") {
$("input#email").focus();
return false;
}
var sub = $("input#sub").val();
if (name == "") {
$("input#sub").focus();
return false;
}
var dataString = $(this).serialize();
//alert (dataString);return false;
/*$.ajax({
type: "POST",
url: "mailing_list_add2.php",
data: dataString,
success: function() {
$('#display_block')
.hide()
.fadeIn(2500, function() {
$('#display_block');
});
}
});
return false;
});*/
});
PHP
<?php
// connects the database access information this file
include("mailing_list_include.php");
// the following code relates to mailing list signups only
if (($_POST) && ($_POST["action"] == "sub")) {
if ($_POST["email"] == "") {
header("Location: mailing_list_add.php");
exit;
} else {
// connect to database
doDB();
// filtering out anything that isn't an email address
if ( filter_var(($_POST["email"]), FILTER_VALIDATE_EMAIL) == TRUE) {
echo '';
} else {
echo 'Invalid Email Address';
exit;
}
// check that the email is in the database
emailChecker($_POST["email"]);
// get number of results and do action
if (mysqli_num_rows($check_res) < 1) {
// free result
mysqli_free_result($check_res);
// cleans all input variables at once
$email = mysqli_real_escape_string($mysqli, $_POST['email']);
// add record
$add_sql = "INSERT INTO subscribers (email) VALUES('$email')";
$add_res = mysqli_query($mysqli, $add_sql)
or die(mysqli_error($mysqli));
$display_block = "<p>Thanks for signing up!</p>";
// close connection to mysql
mysqli_close($mysqli);
} else {
// print failure message
$display_block = "You're email address - ".$_POST["email"]." - is already subscribed.";
}
}
}
?>
<html>
<?php echo "$display_block";?>
</html>
**Updated above after making changes :)
There are a few problems, like:
You need to attach the javascript to an event (the form submit), so the first part would be something like:
$('form').submit(function() {
You need to send in all (correct...) form values, not just the email address for your php to work:
$('form').submit(function() {
var dataString = $(this).serialize();
you miss the data from the server (remove the HTML tags in your server skript):
$.ajax({
type: "POST",
url: "mailing_list_add.php",
data: dataString,
success: function(data) {
$('#email_add').html("<div id='response'></div>");
$('#response').html("<h2>Successfully added to the database.")
.hide()
.fadeIn(2500, function() {
$('#response').html(data);
});
}
});