I am making a function to change the user's email, this call will be made via AJAX on a button click. The form code is below, which is in a file named profile.php:
<form id="changeEmail" method="post">
<div class="form-group">
<label for="changeEmail">Update Email Address</label>
<input type="email" id="email" class="form-control" name="email" value="<?php echo $currentEmail; ?>">
</div>
<button type="submit" id="updateEmail" class="btn btn-success">Update</button>
</form>
I have also created a script in this file as well to perform some basic functionality such as call the ajax function and hide the button until changed. See it below:
<script>
$("#updateEmail").hide();
var id = "<?php echo $id ?>";
$("#email").change(function(){
$("#updateEmail").slideDown();
});
var email = $("#email").val();
console.log("id: " + id);
updateEmail("<?php echo $id; ?>", email);
</script>
The AJAX function which I created is saved in a file named profileAjax.js, this file will hold all my profile ajax functions passing through the users id and new email address.
function updateEmail(id, email) {
$("#updateEmail").click(function(e) {
e.preventDefault(); // Prevent HREF
$("#spinner").show(); // Show spinner
setTimeout(function() {
$.ajax({ // Perform Ajax function
url: "../ajax/admin/updateEmail.php",
dataType: "HTML",
type: "POST",
data: {id: id, email: email},
success: function (result) {
$("#spinner").hide();
$(".dashContent").html(result);
console.log("This worked");
}
});
}, 1500); // Delay this for 1.5secs
});
}
The final file which is called by the AJAX function is updateEmail.php which can be seen below:
include '../../functions/linkAll.inc.php';
$id = filter_input(INPUT_POST, "id");
$email = filter_input(INPUT_POST, "email");
updateEmail($id, $email);
The function which is called updateEmail is saved in an external file and works fully on its own.
function updateEmail($id, $email) {
$connect = db();
$stmt = $connect->prepare("UPDATE `Account` SET `email` = ? WHERE `id` = ?");
$stmt->bind_param("si", $email, $id);
if ($stmt->execute()) {
successMessage("Successfully updated your email address.");
} else {
errorMessage($stmt->error());
}
$stmt->close();
}
However, when the update button is shown and clicked upon, it runs and gives a success message with nothing being updated in the database table itself.
The jQuery AJAX success function is called when the requested source returns HTTP status 200. You should return something from PHP to the AJAX call to tell it if the database action was successfull.
Example PHP (called by AJAX request):
if($stmt->execute()) {
echo "1";
}
else {
echo "0";
}
Example JavaScript:
success: function(data) {
if(data == "1") {
//code if database action is successfull
}
else {
//code if database action failed
}
}
Related
I am trying to access a database and delete a review of a user, I have a method that I pass the user's ID and the ID of the review. This method functions properly using both the SQL command as well as when I call hard-coded variables, however, when I pass the code via AJAX my code says it completed successfully but does not actually do anything. Is there something special about the variables that are passed via AJAX?
This is my method:
public function deleteRating($userid, $reviewID)
{
echo "this is idUsers(IdUsers) = ".$userid." this is reviewID (ID)".$reviewID;
$conn = $this->connect("ratings");
$sql = "DELETE FROM ratedmovies WHERE IdUsers=? AND ID=?";
if(!$stmt = $conn->prepare($sql))
{
echo "False";
}
else
{
$stmt->bind_param("ss", $userid, $reviewId);
if(!$stmt->execute())
{
echo "Failed to delete";
}
else
{
echo "Sucessfull Deletion";
}
}
}
This is the code that calls the method:
<?php
session_start();
include "../Model/Includes/autoLoadCont.inc.php";
$reviews = new Review;
$ratingID = json_decode($_POST['ratingID']);
$user = $_SESSION['userId'];
$reviews->deleteRating($user, $ratingID);
?>
and this is the ajax that calls that function:
var deleteBtns = document.querySelectorAll(".deleteRating");
deleteBtns.forEach(function(button)
{
button.addEventListener("click" , function()
{
$.ajax({
type: "POST",
url: "Controller/deleteReview.php",
data: {ratingID:button.id},
success: function(result)
{
alert(result);
}
});
});
button.id;
});
I have a login form, where I want to pass data from it by Ajax, into a PHP function in another file. The purpose of this is that I want the page not to reload when the user is logging in.
Right now nothing happens when user tries to log in. Seems like access.php is not proccessing the data sent from Ajax.
Can someone tell me why this is not working? What are the possible causes?
index.html:
<div class="login-form">
<form method="post" action="index.php">
<input id="username" type="text" placeholder="Username...">
<input id="password" type="password" placeholder="Password...">
<button id="button" type="submit">Login</button>
</form>
<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>
<script type="text/javascript">
$('#button').click(function(e) {
e.preventDefault();
var username = $('#username').val();
var password = $('#password').val();
$.ajax({
type: 'POST',
url: 'resources/includes/access.php',
data: {
func: 'loginSubmit',
usernamePHP: username,
passwordPHP: password
},
success: function(response) {
$('#result').html(response);
}
});
});
</script>
</div>
access.php:
function loginSubmit(){
require '../dbh.inc.php';
$mailuid = $_POST['usernamePHP'];
$password = $_POST['passwordPHP'];
if(empty($mailuid) || empty($password)){
header("Location: ../../index.php?error=emptyfields");
exit();
}
else{
$sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt, $sql)){
header("Location: ../../index.php?error=sqlerror");
exit();
}
else{
mysqli_stmt_bind_param($stmt, "ss", $mailuid, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if($row = mysqli_fetch_assoc($result)){
$pwdcheck = password_verify($password, $row['pwdUsers']);
if($pwdcheck == false) {
header("Location: ../../index.php");
exit();
}
else if($pwdcheck == true) {
session_start();
$_SESSION['userId'] = $row['idUsers'];
$_SESSION['userUid'] = $row['uidUsers'];
header("Location: ../../index.php?login=success");
exit();
}
else{
header("Location: ../../index.php");
exit();
}
}
}
}
}
From what I can see from the documentation, adding the function name as a data property as you are, doesn't call that function;
data
Type: PlainObject or String or Array
When you call access.php, the file simply contains a function definition, you're not actually calling it.
So you have two options. Either call the function by adding loginSubmit() after the function (at the end of access.php), or remove the code on access.php from a function entirely.
This is the ajax function
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {suburb_id: $('#suburb_id').val()},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
this is the php file need to receive data, it worked perfect.
<?php
//Check the form if submit by post
if (isset($_POST["searchBtn"])) {
$strInputSuburb = "";
$strInputSuburb = $_POST["suburb_id"];
//Check if the input box is empty or not
//if BOTH "Suburb" AND "Street" is empty, it will display the error message.
if(!empty($strInputSuburb))
{
//Connect to database server and table
include("connection.php");
#mysqli_select_db($conn, "db")
or die ("Database not available");
$querySql1 = "select * from Infringement
where suburb like '%".mysqli_real_escape_string($conn, $strInputSuburb)."%' and Street1 like '%".mysqli_real_escape_string($conn, $strInputStreet)."%'
order by Suburb, Fines DESC";
$result1 = mysqli_query($conn, $querySql1)
or die ("No information return...");
$count = mysqli_num_rows($result1);
$i=1;
if(!$count==0){
//do stuff, like echo
}
else {
//do stuff
}
//Release the SQL clause
mysqli_free_result($result1);
//Close the connection to database
mysqli_close($conn);
}
else {
//do stuff
}
}
?>
i want load to this div
<div id="tableContent"></div>
the css style is
#tableContent {
width:100%;
height:400px;
}
The input box is below
<input type="textbox" class="form-control" name="suburb" placeholder="Suburb" id="suburb_id" >
<input type="submit"class="btn" name="searchBtn" id='submit' value="Search" />
I used php to get data from form before. after using Ajax, I deleted "form" tag.
Thank you so much.
You're not sending the searchBtn parameter, which the PHP script is checking for. Add it to the data: option.
$(document).ready(function() {
$('#submit').click(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'searchphp.php',
data: {
suburb_id: $('#suburb_id').val(),
searchBtn: 'Search'
},
success: function(data)
{
$("#tableContent").html(data);
}
});
});
});
Or remove that check from the PHP script, and test if (isset($_POST['suburb_id'])) instead.
I'm using jQuery AJAX to process form data, the PHP side of it should delete two files on the server and then the SQL row in the database (for the id that was sent to it). The element containing the SQL row should then change color, move up, delete and the next SQL rows move into its place. The animation stuff occurs in the beforeSend and success functions of the ajax callback.
This script is not working, when user clicks button, the page url changes to that of the php script but the item and files do not get deleted either on the server or in the database. Nor does any of the animation occur.
This is my first time using jQuery ajax, I think there is a problem with how I define the element during the call back. Any help would be great:
js
$("document").ready(function(){
$(".delform").submit(function(){
data = $(this).serialize() + "&" + $.param(data);
if (confirm("Are you sure you want to delete this listing?")) {
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function() {
$( "#" + data["idc"] ).slideUp(600,function() {
$( "#" + data["idc"] ).remove();
});
}
});
return false;
}
});
});
php
if (isset($_POST["id"]))
{
$idc = $_POST["id"];
if (isset($_POST["ad_link"]) && !empty($_POST["ad_link"]))
{
$ad_linkd=$_POST["ad_link"];
unlink($ad_linkd);
}
if (isset($_POST["listing_img"]) && !empty($_POST["listing_img"]))
{
$listing_imgd=$_POST["listing_img"];
unlink($listing_imgd);
}
try {
require('../dbcon2.php');
$conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "DELETE FROM listings WHERE id = $idc";
$conn->exec($sql);
}
catch (PDOException $e) {
echo $sql . "<br>" . $e->getMessage();
}
echo json_encode($idc);
}
html
<div id="record-<?php echo $id; ?>">
*bunch of stuff*
<form method="post" class="delform">
<input name="id" type="hidden" id="id" value="<?php echo $id; ?>" />
<input name="ad_link" type="hidden" id="ad_link" value="<?php echo $ad_link; ?>" />
<input name="listing_img" type="hidden" id="listing_img" value="<?php echo $listing_img; ?>" />
<button type="submit">Delete</button>
</form>
</div>
You should fix your php code like this
try {
require('../dbcon2.php');
// It's better, if you will going to use MySQL DB, use the class designed to connect with it.
$conn = mysqli_connect("Servername", "usernameDB", "PasswordDB", "NameDB");
$sql = "DELETE FROM listings WHERE id = $idc";
mysqli_query($conn, $sql);
// you have to create a asociative array for a better control
$data = array("success" => true, "idc" => $idc);
// and you have to encode the data and also exit the code.
exit(json_encode($data));
} catch (Exception $e) {
// you have to create a asociative array for a better control
$data = array("success" => false, "sentence" => $sql, "error" => $e.getMessage());
// and you have to encode the data and also exit the code.
exit(json_encode($data));
}
Now in you JS code Ajax change to this.
$.ajax({
type: "POST",
dataType: "json",
url: "delete_list.php",
data: data,
beforeSend: function() {
$( "#" + data["idc"] ).animate({'backgroundColor':'#fb6c6c'},600);
},
success: function(response) {
// the variable response is the data returned from 'delete_list.php' the JSON
// now validate if the data returned run well
if (response.success) {
$( "#" + response.idc ).slideUp(600,function() {
$( "#" + response.idc ).remove();
});
} else {
console.log("An error has ocurred: sentence: " + response.sentence + "error: " + response.error);
}
},
// add a handler to error cases.
error: function() {
alert("An Error has ocurred contacting with the server. Sorry");
}
});
I have looked at everything on here that I can find and I just can't figure out why I cannot perfect this code. What I am trying to do is allow users to delete something that they posted on my site without doing a page refresh. The form is going to be passed to a php file that will modify my MySQL DB. I am new to ajax and have only messed around with PHP for a short time as well.
form:
<form class='status_feedback' id='delete_status' onsubmit='delete_status()' action=''>
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='submit' value='X'/>
</form>
delete_status()
function delete_status(){
$.ajax({
type: "POST",
url: "/scripts/home/php/delete_status.php/",
data: status_id,
success: function() {
//display message back to user here
}
});
return false;
}
delete_status.php
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status_id = $_POST['status_id'];
mysqli_query($con,"UPDATE status SET visibility = 'hidden' WHERE id = $status_id");
?>
at this point, all that happens when I strike the delete_status() function is my page refreshes and adds ?status_id=194 (when I click on status #194) to the end or my url.
Any help would be awesome. I have been researching for several days.
Change your HTML, Ajax and php a little.
HTML
Add this code:
<body>
<form class='status_feedback' id='delete_status' >
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='button' id='x_submit' value='X' />
</form>
<script>
$('#x_submit').on("click",function(){
var status_id= $('#status_id').val();
//Delete the alert message if you want.
alert("Check your status id :"+status_id);
$.ajax({
type: "GET",
url: "/scripts/home/php/delete_status.php?",
data: {status_id:status_id},
dataType:'JSON',
success: function(json) {
//display message back to user here
alert(json[0].response);
}
});
});
</script>
PHP:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Content-type: application/json');
$con=mysql_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$status_id = $_GET['status_id'];
$result = mysql_query("UPDATE status SET visibility = 'hidden'
WHERE id = '$status_id'");
if(! $result )
{
$data[]=array('response'=>"Unable to insert!");
}
else
{
$data[]=array('response'=>"Data successfully inserted into the database!");
}
$json_encode = json_encode($data);
print("$json_encode");
?>
Hope it will work.
You are not cancelling the form submission
onsubmit='delete_status()'
needs to be
onsubmit='return delete_status()'
and data: status_id, looks wrong unless you have a variable defined somewhere else