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;
});
});
Related
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.
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 simple form before:
<form method="post" action="firstbillsubmitbal.php?id=#COL1#">
<input name="currentbal" type="text" id="currentbal" class="input-mini" />
<input type="submit" id="submit" value="Save" class="btn btn-success" />
</form>
Which calls this page for processing firstbillsubmitbal.php
$dealID = $_GET["id"];
$currentbal = mysql_real_escape_string(stripslashes($_POST['currentbal']));
$sql = mysql_query("UPDATE deals SET
currentbal = '$currentbal',
currentbalDone = 'Yes'
WHERE deals.dealID = '$dealID'") or die (mysql_error());
It was working fine for single transactions. But I need to edit it a bit since I am displaying my data in a table now. I now have this js code when I click on a btn on my table per row, passes my row_id and currentbal calue, I got it working but I would like to know from this js code how do I process my form?
function funcEdit(row_id){
var currentbal = document.getElementById('currentbal' + row_id).value;
var r=confirm("Are You Sure You Want To Proceed?");
if(r==true) {
alert("Record is saved");
} else {
alert("Cancelling Transaction");
}
}
The js code has two variables only at the moment which is
row_id = this is basically the ID of the db row and
currentbal = which is the value I want to upload to my db
My question basically is how do I call my firstbillsubmitbal.php file and what/how do I edit on my php file so that my row_id and currentbal are uploaded on my db since I am no long using POST.
Thank you for the replies. So I went thru some SO answers and some tutorials I found on google and this is what happened to my js code.
function funcEdit(row_id){
var currentbal = document.getElementById('currentbal' + row_id).value;
var dealID = row_id;
//organize the data properly
var data = 'currentbal=' + currentbal.val() + '&dealID=' + dealID.val();
//start the ajax
$.ajax({
url: "firstbillsubmitbal.php",
type: "GET",
data: data,
cache: false,
success: function() {
$('#message').html("<h2>Current balance has been updated!</h2>")
}
});
}
And this is what happened to my firstbillsubmitbal.php page
$dealID = $_GET['dealID']
$currentbal = $_GET['currentbal']
$sql = mysql_query("UPDATE deals SET
currentbal = '$currentbal',
currentbalDone = 'Yes'
WHERE deals.dealID = '$dealID' LIMIT 1") or die (mysql_error());
But nothing happens when I click on the button to call my function. What am I missing?
Also, here is how I call my function. #COL1# is my row ID value.
Update
Are your function getting called correctly with row_id data ?
if so then might be this will give you a trick,
function funcEdit(row_id){
var currentbal = document.getElementById('currentbal' + row_id).value;
var dealID = row_id;
//start the ajax
$.ajax({
url: "firstbillsubmitbal.php",
type: "GET",
//pass data like this
data: {currentbal:currentbal.val(),dealID: dealID.val()},
cache: false,
success: function(data) {
if (data=="1")
$('#message').html("<h2>Current balance has been updated!</h2>")
}
});
}
and in php file
$dealID = $_GET['dealID']
$currentbal = $_GET['currentbal']
$sql = mysql_query("UPDATE deals SET
currentbal = '$currentbal',
currentbalDone = 'Yes'
WHERE deals.dealID = '$dealID' LIMIT 1") or die (mysql_error());
echo "1" ; // if update successful
else echo "0" // if update unsuccessful
HTML :
<form method="post" action="firstbillsubmitbal.php">
<input name="currentbal" type="text" id="currentbal" class="input-mini" />
Update
</form>
JS :
function funcEdit(row_id){
var currentbal = $("#currentbal").val();
//organize the data properly
var data = 'currentbal=' + currentbal + '&dealID=' + row_id;
//start the ajax
$.ajax({
url: "firstbillsubmitbal.php",
type: "GET",
data: data,
cache: false,
success: function() {
$('#message').html("<h2>Current balance has been updated!</h2>")
}
});
}
Hope it works for you!
I'm trying to implement password change functionality into my website. I've got all the password changing script, validation, etc done. But now I need to prevent the page from going to the script page or refreshing. When the user clicks the submit button, I want nothing to change except a message displaying successfully changed or error. So here's my html:
<form id="change_Pass" action="" method="post">
Current Password<input type="password" id="change_password" name="change_password"><br>
New Password<input type="password" id="new_password" name="new_password"><br>
Verify Password<input type="password" id="verify_password" name="verify_password"><br>
<input type="submit" value="Submit" id="change_pass_submit">
</form>
And my jquery:
$('#change_pass_submit').click(function(){
var $this = $(this);
$.ajax({
data: $this.serialize(), // get the form data
type: "POST", // GET or POST
url: "/Private/change_password.php", // the file to call
success: function() { // on success..
//$('#success_div).html(response); // update the DIV
alert("good");
},
error: function() { // on error..
//$('#error_div).html(e); // update the DIV
alert("bad");
}
});
return false; //so it doesn't refresh when submitting the page
});
And my php:
<?php
session_start();
require_once '../classes/Bcrypt.php';
ini_set('display_errors', 'On');
error_reporting(E_ALL | E_STRICT);
$usr = $_SESSION["username"];
$old_pwd = $_POST["change_password"];
$new_pwd = $_POST["new_password"];
$new_pwd = Bcrypt::hash($new_pwd);
try {
$link = new PDO('mysql:host=*;dbname=*;charset=UTF-8','*','*');
$query = "SELECT *
FROM Conference
WHERE Username = :un";
$stmt = $link->prepare($query);
$stmt->bindParam(':un', $usr);
$stmt->execute();
$row = $stmt->fetchAll();
$hash = $row[0]["Password"];
$is_correct = Bcrypt::check($old_pwd, $hash);
if($is_correct) {
$query = "UPDATE Conference
SET `Password`=:new_pwd
WHERE Username = :usr";
$stmt = $link->prepare($query);
$stmt->bindParam(':new_pwd', $new_pwd);
$stmt->bindParam(':usr', $usr);
$stmt->execute();
return true;
} else return false;
} catch(PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
But for some reason, when I hit the submit button, the page STILL goes to change_password.php. I have no idea why, i've looked at so many tutorials and my code matches theirs but for some reason mine won't stay on the same page. Where did I go wrong?
Instead of using $('#change_pass_submit').click(function(), use $('#change_Pass').submit(function().
.click will only work if the submit button is actually clicked where .submit will work even if the user presses enter.
This should fix your error but it is untested.
Bind your handler to the form's submit event:
$(document).on('click', '#change_Pass', function() {
var $this = $(this);
$.ajax({
data: $this.serialize(), // get the form data
type: "POST", // GET or POST
url: "/Private/change_password.php", // the file to call
success: function() { // on success..
//$('#success_div).html(response); // update the DIV
alert("good");
},
error: function() { // on error..
//$('#error_div).html(e); // update the DIV
alert("bad");
}
});
return false; //so it doesn't refresh when submitting the page
});
Try putting preventDefault(); in the last line of the function performed by .submit
$(document).ready(function(){
$( "#cambiar_pass_form" ).submit(function() {
$.ajax({
...
...
});
event.preventDefault();
});
});