Update MySQL database on click - php

I am writing a website that needs to update a users credits so that it adds a javascript value to the existing credits in the database on a button click and I can't seem to find out how to do it (I'm very new to ajax so go easy...)
HTML:
<form method="post">
<input id="depositBtn" type="submit" value="Deposit">
</form>
jQuery
$( "#depositBtn" ).submit( function() {
$.ajax({
url: 'deposit.php',
dataType: 'json',
type: 'post',
data: {total: tot},
success: function(data) {
alert(data);
}
});
});
PHP
$db = new PDO('mysql:host='.$servername.';dbname='.$dbname.';charset=utf8', $username, $password);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$getCredits = $db->prepare("SELECT credits FROM userinfo WHERE steamid = ? ");
$getCredits->bindParam(1, $steamid, PDO::PARAM_INT);
$credits = $getCredits->fetch(PDO::FETCH_ASSOC);
$allcredits = $credits['credits'];
$bank = $_POST['total'];
$result = array(
'success' => true,
'credits' => $bank+$allcredits
);
echo json_encode($result);

It seems like there is no much wrong with your coding, specially regarding the JavaScript which you have put!
But I suggest you the following:
(Assuming: that your alert box shows what is the response from the server in the success block.)
$( "#depositBtn" ).submit( function(e) {
e.preventDefault();
console.log('total : '+tot);
$.ajax({
url : 'deposit.php',
type : 'POST',
dataType : 'json',
data : {total: tot},
success : function(data) {
alert(data);
}
});
});
What my change to your code is:
1st Change:
$( "#depositBtn" ).submit( function(e) { // you catch the submit button click event.
e.preventDefault(); // you prevent the default event of the submit button
2nd Change:
console.log('total : '+tot); // which will print your 'tot' variable to web browser
// console before it is sent to your PHP Script.
3rd Change:
type : 'POST', // You have put 'post' for the type.
For further reading on preventing the default events read the following question thread!
Note:
Don't forget to check your JS Variables before you send them to the any server side scripts written in any lang. (PHP, Java, Rubi, ...)
Hope this helps!
Cheers!

Related

problem to print result after ajax success

Please help to fix this issue with like counting.
i create a news feed like facebook using php mysql and ajax.
problem is that when i click on like button it prints like count from (this value) and showing to all, let say i have 5 posts and like current value for different posts are 100, 200 , 70 , 80 , 578. when I click on first post ajax success count 100+1 = 101 for first post and for all other post printting same 101 likes. now if i will go to 2nd post and its like value 200, ajax will show 200+1 =201 like. so after click on 2nd post all 5 posts like will show 201. its creating problem for me. I understand that after ajax success i mentioned to show the value to div class (.ajax_like_result), thats why its showing in every post, same result until i am not clicking on different post.
how to fix this so that when I click on any post it wil show only its real like value??
I try to change the DIV attribute id , instead of class then it only works for first post. other post totally not working. if i set div atribute to class then like is working but printing incorrectly as i mentioned above.
I have pasted below- html , php and ajax code . thanks for your help.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.ajax_like').on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(".ajax_like_result").html(data);
}
});
});
});
</script>
html :
<li class="ajax_like" type="submit" name="data-id" data-id="<?php echo $page;?>" value="<? echo $post_id;?>">
<div class= "ajax_like_result" ><?php print $likes;?></div>
</li>
like.php code :
<?php //user info start
session_start();
$conn=mysqli_connect("localhost", "u1068033_ab24", "ab#24", "u1068033_ab24");
mysqli_set_charset($conn,"utf8");
$id=$_SESSION['id'];
$get_post_id = $_POST['post_id'];
$page = $_POST['page'];
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
$likes=$row['likes'];
$sql="UPDATE $page SET `likes`=$likes+1 WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$sql="SELECT `likes` FROM $page WHERE `post_id`='$get_post_id'";
$query=mysqli_query($conn,$sql);
$row=mysqli_fetch_assoc($query);
echo $row['likes'];`enter code here`
?>
You should need some corrections on your jQuery
$(document).ready(function(){
$('.ajax_like').each( function(){
$(this).on('click', function () {
var post_id = $(this).val();
var page = $(this).attr("data-id");
$.ajax({
type: 'POST',
url: 'like.php',
data: {post_id:post_id, page:page},
dataType: 'json',
// cache: false,
success: function(data){
$(this).find(".ajax_like_result").html(data);
}
});
});
})
});
you are writing the result to all HTML elements with the same class "ajax_like_result" when using this line:
$(".ajax_like_result").html(data);
you can use something such as:
$("li[data-id='"+page+"'] div.ajax_like_result").html(data);
Also better using native JavaScript and not jQuery, using document.querySelector
document.querySelector(`li[data-id='${page}'] div.ajax_like_result`).innerHTML = data;
and replace the jQuery AJAX with the native JavaScript fetch
example in one piece of code block with native JavaScript (no need for jQuery):
document.addEventListener("DOMContentLoaded", (event) => {
document.querySelectorAll('li[data-id]').forEach((elem)=>{
elem.addEventListener('click', event => {
const domElem = event.target;
const postId = domElem.getAttribute('value');
const page = domElem.getAttribute('data-id');
const data = {post_id:postId, page:page};
console.log({data});
fetch('like.php', {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log('Success:', data);
const selector = `li[data-id='${page}'] div.ajax_like_result`;
document.querySelector(selector).innerHTML = data;
})
.catch((error) => {
console.error('Error:', error);
});
});
});
});
and better also to remove from the PHP code the '?>' as the PHP ends the script execution at the end and it will reduce some possible unwanted white spaces.

delete data in sql using ajax and php in XDK

i want to delete a row of data in my sql when delete button is pressed in xdk. i searched for some codes but still doesnt delete the data.
this is the php file (delete.php)
<?php
include('dbcon.php');
$foodid = $_POST['foodid'];
$query = "DELETE FROM menu WHERE id ='$foodid'";
$result=mysql_query($query);
if(isset($result)) {
echo "YES";
} else {
echo "NO";
}
?>
and now here is my ajax code.
$("#btn_delete").click( function(){
alert("1");
var del_id = $(this).attr('foodid');
var $ele = $(this).parent().parent();
alert("2");
$.ajax({
type: 'POST',
url: 'http://localhost/PHP/delete.php',
data: { 'del_id':del_id },
dataType: 'json',
succes: function(data){
alert("3");
if(data=="YES"){
$ele.fadeOut().remove();
} else {
alert("Cant delete row");
}
}
});
});
as you can see, i placed alerts to know if my code is processing, when i run the program in xdk. it only alerts up to alert("2"); . and not continuing to 3. so i assume that my ajax is the wrong part here. Im kind of new with ajax.
<?php
$sqli= "*select * from temp_salesorder *";
$executequery= mysqli_query($db,$sqli);
while($row = mysqli_fetch_array($executequery,MYSQLI_ASSOC))
{
?>
//"class= delbutton" is use to delete data through ajax
<button> Cancel</button>
<!-- language: lang-js -->
//Ajax Code
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
$.ajax({
type: "GET",
url: "deletesales.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
return false;
});
});
</script>
//deletesales.php
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'pos';
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_database);
$id=$_GET['id']; <!-- This id is get from delete button -->
$result = "DELETE FROM temp_salesorder WHERE transaction_id= '$id'";
mysqli_query($db,$result);
?>
<!-- end snippet -->
A couple of things:
You should be testing using console.log() instead of alert() (imo)
If you open up your console (F12 in Google Chrome) do you seen any console errors when your code runs?
Your code is susceptible to SQL Injection, you will likely want to look into PHP's PDO to interact with your database.
Does your PHP file execute correctly if you change:
$foodid = $_POST['foodid'];
To
$foodid = 1
If number 4 works, the problem is with your javascript. Use recommendations in numbers 1 and 2 to diagnose the problem further.
Update:
To expand. There are a few reasons your third alert() would not fire. The most likely is that the AJAX call is not successful (the success handler is only called if the AJAX call is successful). To see a response in the event of an error or failure, you can do the following:
$.ajax({
url: "http://localhost/PHP/delete.php",
method: "POST",
data: { del_id : del_id },
dataType: "json"
})
.done(function( msg ) {
console.log(msg);
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
More information on AJAX and jQuery's $.ajax can be found here
My "best guess" is a badly formatted AJAX request, your request is never reaching the server, or the server responds with an error.

Send selectbox value to php variables without page reloading

I'm learning AJAX by reading some online tutorials, so please understand I am very new to AJAX and programming in general. I have managed to do the following with 3 selectboxes:
populates selectbox 2 based on selection from selectbox 1
populates selectbox 3 based on selection from selectbox 2
Everything is working perfectly
Here is my code:
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
Here is an Example
What I want to do
I would like to send the value of the 3 selectboxes to 3 php variables without the form reloading.
My Problem
When the user clicks submit:
The form reloads (which I dont want)
The selectbox values does not get send to my php variables
my code to get the values after submit is clicked is as follows:
if(isset($_POST['submit'])){
$a = $_POST['sport'];
$b = $_POST['tournament'];
:
}
However my code is flawed as I mentioned above.
If any one can help me to explain how to send my form data to the 3 php variables without the form reloading it will be greatly appreciated
If you don't want to submit your form when you click the button, you need to set that input as button and not submit. You can, also, attach the submit event handler to the form and prevent it to submit:
$("form").on("submit", function(e){
e.preventDefault(); //This is one option
return false; //This is another option (and return true if you want to submit it).
});
So, being said this, you could probably do something like:
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'yoururl',
data: formData,
type: 'post', //Based on what you have in your backend side
success: function(data) {
//Whatever you want to do once the server returns a success response
}
});
});
In your backend:
if (isset($_POST["sport"])) {
//Do something with sport
}
if (isset($_POST["tournament"])) {
//Do something with torunament
}
echo "Successfull response!"; //You have to "write" something in your response and that is what the frontend is going to receive.
Hope this helps!
Try using the javascript function preventDefault().
See this SO question.
Use a <button>Submit</button> element instead of <input type="submit"/> since the submit automatically submits the form.
Edit: And you would have to use on.('click') instead of looking for submit event in your jQuery.

Executing a PHP file from a jQuery / AJAX request

I'm making a chat function where staff members with the appropriate privileges can delete a line that has been posted to the chat room.
I'd like this function to work without refreshing the page, but I can't seem to get the jQuery / AJAX part of it right? Nothing happens at all.
As a jQuery newbie I was hoping that someone could point out the line that I'd have to look at?
a href that needs to be clicked to delete line:
for (var i in json.lines) {
lines.push("[<a class='delete' href='#' data-lineID='" + json.lines[i].id + "'>x</a>] " + json.lines[i].user + json.lines[i].divide + " " + json.lines[i].message);
}
jQuery:
$('a.delete').on('click', function(event) {
var id = $(this).data('lineID');
/* Request to .php file */
var request = $.ajax({
url: "/communications/chat.php?page=delete",
type: "POST",
data: { id : id },
dataType: "html"
});
event.preventDefault();
return false;
});
Part of the PHP script to execute:
case 'delete' :
if(isset($_POST['id']) && !empty($_POST['id'])) {
$id = $_POST['id'];
try {
$query = $udb->prepare("UPDATE `chat_lines` SET `deleted` = '1' WHERE `id` = ?");
$query->bindValue(1,$id);
$query->execute();
} catch (Exception $e) {
die($e->getMessage());
}
}
break;
Any help is appreciated :)
This could be a long shot, but I think that your issue is caused by HTML element not being there when you load the Javascript.
jQuery will attach an event listener (in this case the click one) when the script is loaded.
If the element is added after the script loads, the listener is not attached so it won't trigger your code.
What you have to do is to use event delegation. This means that you have to change your javascript code to this:
$('#mainContainerOfYourChat').on('click', 'a.delete', function(event) {
var id = $(this).data('lineID');
/* Request to .php file */
var request = $.ajax({
url: "/communications/chat.php?page=delete",
type: "POST",
data: { id : id },
dataType: "html"
});
event.preventDefault();
return false;
});
In this way jQuery will listen to the main container of your page, when a click is fired, if it matches the a.delete selector, it will trigger your code.
If your PHP is deleting the post from the DB your only problem is it stays loaded on the client side until you reload the page.
If that is so you'll only need to include a line to remove the comment if the ajax call is successful:
var request = $.ajax({
url: "/communications/chat.php?page=delete",
type: "POST",
data: { id : id },
dataType: "html",
success: function(){
$("a.delete[data-lineID="+id+"]").parent().remove();
}
});

jQuery preventDefault() not working inside AJAX call

So, I am doing a check when a user inputs an email to see if the email exists or not.
$('form.recover-form#check-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: {email: email},
success: function(response) {
if ( response == 'no' ) {
span.text('email does not exist');
} else if ( response == 'ok' ) {
form.submit();
}
}
});
});
The php code
if ( Input::isPost('email') ) {
$email = Input::post('email');
$check = $dbh->prepare(" SELECT * FROM users WHERE email = :email ");
$check->execute(array( 'email' => $email ));
echo ( $check->rowCount() == 1 ) ? 'ok' : 'no' ;
}
This way as soon as I submit the form it submits and the e.PreventDefault() inside the AJAX call is not working. If I put e.PreventDefault() before the AJAX call however, the form does not submit and the error appears if the email does not exists ( this is what I want to achieve ).
I can't understand where the problem is, hope you can help.
Thank you.
EIDT: This is the updated code
The problem is that you don't call preventDefault during the handling of the event. Instead, during the handling of the event, you start an ajax call (which is asynchronous), and then let the event continue. The ajax call completes later, which is too late to prevent the event's default — it's already happened.
Move the e.preventDefault() directly into the event handler, outside the ajax success handler.
$('.recover-form').on('submit', function(e){
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
e.preventDefault(); // <=================== Here
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
// ============================ Not here, this would be too late
span.text('email does not exist');
}
}
});
});
In a comment, you've said:
Yes, it works for the validation, but I want to submit the form if ajax returns a positive response. I only do a check with AJAX, if it fails stop the submit, if it succeed continue the submit.
You can't hold up the original form submission waiting for the result of an asynchronous ajax call. What you do instead is cancel the original form submission, do the ajax, and then if the result is okay, re-submit the form using the submit method on the raw DOM form element. That method doesn't re-trigger submit event handlers.
Example: Live copy
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<meta charset=utf-8 />
<title>Delaying form submit during ajax</title>
</head>
<body>
<form action="http://www.google.com/search" method="GET">
<input type="text" name="q" value="kittens">
<input type="submit" value="Submit">
</form>
<script>
(function() {
$("form").submit(function(e) {
var rawFormElement = this; // Remember the DOM element for the form
// Stop form submission
display("Got form submit event, simulating ajax");
e.preventDefault();
// Simulate ajax check of data
setTimeout(function() {
// (This is the 'success' callback for the ajax)
display("Ajax call complete, pretending result is good and submitting");
// All okay, go ahead and submit the form
rawFormElement.submit(); // Doesn't trigger 'submit' handler
}, 1500);
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})();
</script>
</body>
</html>
You can't prevent the default action from a success handler of ajax request because of the asynchronous nature of it.
Instead by default prevent the form submission, then in the success handler if it is valid then call the submit again.
$('.recover-form').on('submit', function (e) {
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
//prevent the submit
e.preventDefault();
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function (response) {
if (response == 0) {
span.text('email does not exist');
} else {
//submit if valie
form[0].submit()
}
}
});
});
First, you're options are incorrect. cache and async require boolean values, not strings.
async: false,
cache: false,
Secondly, instead of submitting the form after the ajax request you're instead triggering the event. Try this instead.
form.get(0).submit();
It returns the form node rather than a jquery object, allowing you to submit it directly rather than triggering an event (otherwise you would have an infinite loop.)
You don't really need async: false or cache: false in this case.
You need to do the following:
$('.recover-form').on('submit', function(e){
e.preventDefault();
var form = $(this),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
span.text('email does not exist');
}
}
});
});
Notice how I've moved the e.preventDefault() to the beginning. This is because you were calling it when the ajax request responds which might happen 100s of milliseconds or even seconds after the form has been submitted
This happens because success function passed for jQuery.ajax() is executed assyncly, then it will be executed after event handler function is finish.
You should put the e.preventDefault() out of ajax function. and everything will work.
Better you can try something like this ,
<form name="myForm" onsubmit="return submitObj.validateAndSubmit();"> <!-- your form -->
<!-- your AJAX -->
var submitObj = {
validateAndSubmit : function()
{
var form = $('.recover-form'),
input = $('.check-recover-email'),
span = $('.recover-error'),
email = input.val();
span.text('');
$.ajax({
url: 'ajax/check-email',
async: 'false',
cache: 'false',
type: 'POST',
data: form.serialize(),
success: function(response){
if ( response == 0 ) {
return false;
}
else{
return true;
}
}
});
}
};

Categories