How to define an element with a a sql row id usng JSON encoded data - javascript

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");
}
});

Related

removing users from page on button click using ajax technology

I want to remove the whole element on button click.
Removal must be done through Ajax technology, that is, without reloading the page.
After deleting a user, the entry with him should disappear from the list of all users.
Here is the structure of my code:
<?php
require_once "lib/mysql.php"; //database connection
$query = $pdo->prepare('SELECT * FROM `users`');
$query->execute();
$users = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($users as $user) {
echo '<div class="infoAllUsers"><b>Name: </b>' . $user['name'] . ', <b>Login: </b>' . $user['login'] . '<button onclick="deleteUser('.$user['id'].');">Delete</button></div>';
}; //display all users
?>
<script>
function deleteUser(id) {
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {'id': id},
success: function(data) {
$(this).closest(".infoAllUsers").remove();
}
});
}
</script>
There are no errors in js and php, there is nothing in the console, deletion from the database occurs correctly.
I am new to jQuery so I have tried some things like:
$(this).parent('div').remove();
$(this).closest('div').remove();
$(this).parent('.infoAllUsers').remove();
Take a different/cleaner approach
Set the id as a data attribute and assign a class, then add the click event to that.
<button class="delete" data-id="'.$user['id'].'">Delete</button>
$('.infoAllUsers .delete').click(function(elm) {
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {
'id': $(elm).data('id')
},
success: function() {
$(elm).parent().remove();
}
});
})
<?php
require_once "lib/mysql.php"; //database connection
$query = $pdo->prepare('SELECT * FROM `users`');
$query->execute();
$users = $query->fetchAll(PDO::FETCH_ASSOC);
foreach($users as $user) {
echo '<div class="infoAllUsers"><b>Name: </b>' . $user['name'] . ', <b>Login: </b>' . $user['login'] . '<button onclick="deleteUser('.$user['id'].', this);">Delete</button></div>';
}; //display all users
?>
<script>
function deleteUser(id, this2) {
var $t = $(this2);
$.ajax({
url: 'ajax/deleteUser.php',
type: 'POST',
cache: false,
data: {'id': id},
success: function(data) {
$t.closest('.infoAllUsers').remove();
}
});
}
</script>
The code seems correct, the only thing that occurs to me is that your php backend is not returning an Http code that is in the 2XX range and that is why it does not enter the success function of your ajax request, have you tried to make a console.log() inside the function that deletes the <div> to see if the JS reaches that point?
Jquery.ajax() function documentation

Submit form with AJAX and PHP without page reload

I have "add to favorite" feature in my wordpress project, I am using <form> to submit the feature. Each time I click on add to fav button it works, but the page is always reloaded which is annoying so I decided to use AJAX, but I can not connect it with my PHP file.
This is PHP file, where I wrote function for the feature
if (! function_exists('favorite_button_icon')) {
function favorite_button_icon() {
echo apply_filters( 'favorite_button_icon', get_the_favorite_button_icon() );
}
}
if (! function_exists('get_the_favorite_button_icon')) {
function get_the_favorite_button_icon() {
$output = '';
$action = $currentPath; // window.location.href
$name = is_favorite() ? 'remove_favorite' : 'add_favorite';
$class = 'favorite-button-pro' . ( is_favorite() ? ' favorite' : '' );
$icon = is_favorite() ? 'Added' : 'Add';
$output .= '<form method="post" id="favorite_user_post"
class="favorite_user_post" action="'. $action .'">';
$output .= '<button id="submit-favorite" type="submit" name="'. $name .'"
value="'. get_the_ID() .'" class="'. $class .'">';
$output .= $icon;
$output .= '</button></form>';
return apply_filters( 'get_the_favorite_button_icon', $output );
}
}
And I am just calling that function in html
<div class="add-to-favorites-option" >
<?php favorite_button_icon() ?>
</div>
Everything above works, but as I said, page is being reloaded.
This is my attempt to use AJAX
jQuery('#favorite_user_post').submit(function (e) {
e.preventDefault();
var form = jQuery(this);
var url = form.attr('action');
jQuery.ajax({
type: 'POST',
url: url,
data: form.serialize(),
success: function (data) {
console.log(data);
},
error: function () {
console.log('Fail');
},
});
});
I get absolutely no fire on submit, am I missing something?
You need to use the wp_ajax_ hook: https://developer.wordpress.org/reference/hooks/wp_ajax_action/
Simple example below:
You PHP code to process the ajax request:
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
// code that captures your ajax POST request
wp_die(); // this is required to terminate immediately and return a proper response
}
Your Ajax call:
jQuery('#favorite_user_post').submit(function (e) {
e.preventDefault();
var form = jQuery(this);
// note the added "my_action" to tell the server what function to fire (my be a better way to append this to your form data)
var url = form.attr('action') + "&=my_action";
jQuery.ajax({
type: 'POST',
url: url,
data: form.serialize(),
success: function (data) {
console.log(data);
},
error: function () {
console.log('Fail');
},
});
});

Accessing JSON returned by php script using jquery ajax

Basically my program is a web page with 5 radio buttons to select from. I want my web app to be able to change the picture below the buttons every time a different button is selected.
My problem is coming in the JSON decoding stage after receiving the JSON back from my php scrip that accesses the data in mysql.
Here is my code for my ajax.js file:
$('#selection').change(function() {
var selected_value = $("input[name='kobegreat']:checked").val();
$.ajax( {
url: "kobegreat.php",
data: {"name": selected_value},
type: "GET",
dataType: "json",
success: function(json) {
var $imgEl = $("img");
if( $imgEl.length === 0) {
$imgEl = $(document.createElement("img"));
$imgEl.insertAfter('h3');
$imgEl.attr("width", "300px");
$imgEl.attr("alt", "kobepic");
}
var link = json.link + ".jpg";
$imgEl.attr('src', link);
alert("AJAX was a success");
},
cache: false
});
});
And my php file:
<?php
$db_user = 'test';
$db_pass = 'test1';
if($_SERVER['REQUEST_METHOD'] == "GET") {
$value = filter_input(INPUT_GET, "name");
}
try {
$conn = new PDO('mysql: host=localhost; dbname=kobe', $db_user, $db_pass);
$conn->setAttribute(PDO:: ATTR_ERRMODE, PDO:: ERRMODE_EXCEPTION);
$stmt = $conn->prepare('SELECT * FROM greatshots WHERE name = :name');
do_search($stmt, $value);
} catch (PDOException $e) {
echo 'ERROR', $e->getMessage();
}
function do_search ($stmt, $name) {
$stmt->execute(['name'=>$name]);
if($row = $stmt->fetch()) {
$return = $row;
echo json_encode($return);
} else {
echo '<p>No match found</p>;
}
}
?>
Here's my HTML code where I am trying to post the image to.
<h2>Select a Great Kobe Moment.</h2>
<form id="selection" method="get">
<input type="radio" name="kobegreat" value="kobe1" checked/>Kobe1
<input type="radio" name="kobegreat" value="kobe2"/>Kobe2
<input type="radio" name="kobegreat" value="kobe3"/>Kobe3
</form>
<div id="target">
<h3>Great Kobe Moment!</h3>
</div>
And here's is what my database looks like:
greatshots(name, link)
name link
------ --------
kobe1 images/kobe1
kobe2 images/kobe2
kobe3 images/kobe3
Whenever I run the web app right now, the rest of the images on the page disappear and the image I am trying to display won't show up. I get the alert that "AJAX was a success" though, but nothing comes of it other than the alert. Not sure where I am going wrong with this and any help would be awesome.
As mentioned you should parse the JSON response using JSON.parse(json);.
Also, you should specifically target the div element with a simpler setup:
$("#target").append('<img width="300px" src="' + link + '.png"/>');

Session not sending correctly through AJAX

I have the following code that I thought worked correctly, but it turns out the users session is not being sent correctly. Let's say I was on trying to make a post, it does not take my id, it takes the id of the last user who registered for my site. Why would this be?
I have this as my $userid variable and it should be taking my session. I am initializing the session at the top of the page.
What am I doing wrong?
$(document).ready(function(){
$("#submit_announcement").on("click", function () {
var user_message = $("#announcement_message").val();
//$user = this.value;
$user = $("#approved_id").val();
$.ajax({
url: "insert_announcements.php",
type: "POST",
data: {
"user_id": $user,
//"message": user_message
"user_message": user_message
},
success: function (data) {
// console.log(data); // data object will return the response when status code is 200
if (data == "Error!") {
alert("Unable to get user info!");
alert(data);
} else {
$(".announcement_success").fadeIn();
$(".announcement_success").show();
$('.announcement_success').html('Announcement Successfully Added!');
$('.announcement_success').delay(5000).fadeOut(400);
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + "|" + errorThrown);
//console.log("error"); //otherwise error if status code is other than 200.
}
});
});
});
PHP and Form
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
try {
//Prepare
$con = mysqli_connect("localhost", "", "", "");
if ($user_stmt = $con->prepare("SELECT `id` FROM users")) {
$user_stmt->execute();
$user_stmt->bind_result($user_id);
if (!$user_stmt) {
throw new Exception($con->error);
}
}
$user_stmt->store_result();
$user_result = array();
?>
<div class="announcement_success"></div>
<p>Add New Announcement</p>
<form action="" method="POST" id="insert_announcements">
<input type="hidden" value="<?php echo $userid; ?>" id="approved_id" name="user_id" />
<textarea rows="4" cols="50" id="announcement_message" name="message" class="inputbarmessage" placeholder="Message" required></textarea>
<label for="contactButton">
<button type="button" class="contactButton" id="submit_announcement">Add Announcement</button>
</label>
</form>
UPDATE: PHP file to show an example
// $announcement_user_id= $_POST['user_id'];
$userid = ( isset( $_SESSION['user'] ) ? $_SESSION['user'] : "" );
$announcement_message= $_POST['user_message'];
$test = print_r($_POST, true);
file_put_contents('test.txt', $test);
//var_dump($announcement_user_id);
$con = mysqli_connect("localhost", "", "", "");
$stmt2 = $con->prepare("INSERT INTO announcements (user_id, message, date) VALUES (?, ?, NOW())");
if ( !$stmt2 || $con->error ) {
// Check Errors for prepare
die('Announcement INSERT prepare() failed: ' . htmlspecialchars($con->error));
}
if(!$stmt2->bind_param('is', $userid, $announcement_message)) {
// Check errors for binding parameters
die('Announcement INSERT bind_param() failed: ' . htmlspecialchars($stmt2->error));
}
if(!$stmt2->execute()) {
die('Announcement INSERT execute() failed: ' . htmlspecialchars($stmt2->error));
}
//echo "Announcement was added successfully!";
else
{
echo "Announcement Failed!";
}
You're selecting all of the users:
SELECT `id` FROM users
So when you get one record from that result, it's probably going to coincidentally be the latest record in the table.
You're trying to bind a parameter to i:
$user_stmt->bind_result($user_id);
so maybe you meant to have a WHERE clause?
SELECT `id` FROM users WHERE `id` = ?
Though, that seems... unnecessary. Since you already have the ID. You seem to be posting the ID from client-side, and keeping it in session state, and getting it from the database. So it's not entirely clear what you're even trying to do here. But one thing that is clear is that query is going to return every record from that table.

AJAX form submission with php and jquery

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

Categories

Resources