I'm a newbie at programming with AJAX and beginner at PHP programming. I'm not sure why, but when a user clicks an arrow to "Upvote" a post repeatedly and very fast, the PHP login_check decides that the user is no longer logged in. The program works if I click the arrow at a normal speed, but when I rapid fire it gets weird.
PHP code:
<?php
include "db_connect.php";
include "functions.php";
sec_session_start();
I was wondering if this is a definite case of race conditions and what I could do to prevent it--
AJAX code:
$(document).ready(function() {
$("#upvotearrow").click(function() {
setTimeout(function() { }, 500);
$resdiv=$("#upvotedownvote_resultalert");
$content=$("#upvotedownvote_resultalert_content");
$.ajax({
type: "POST",
url: "../secure/process_upvotedownvote.php",
data: { vote: "upvote", poemid: $("#poemidfield").val() },
dataType:"HTML"
})
.done(function(param) {
if (param=="true_upvote") {
$content.html("Upvote registered!");
$resdiv.css("visibility", "visible");
}
else {
$content.html("Invalid request");
$resdiv.css("visibility", "visible");
}
});
});
$("#downvotearrow").click(function() {
setTimeout(function() { }, 500);
$resdiv=$("#upvotedownvote_resultalert");
$content=$("#upvotedownvote_resultalert_content");
$.ajax({
type: "POST", //POST data
url: "../secure/process_upvotedownvote.php", //Secure upvote/downvote PHP file
data: { vote: "downvote", poemid: $("#poemidfield").val() }, //Get type of vote and poem_id in URL
dataType:"HTML" //Set datatype as HTML to send back params to AJAX function
})
.done(function(param) { //Param- variable returned by PHP file
if (param=="true_downvote") {
$content.html("Downvote registered!");
$resdiv.css("visibility", "visible");
}
else {
$content.html("Invalid request");
$resdiv.css("visibility", "visible");
}
});
});
});
The website with a live demo can be viewed here.
TO LOG IN, JUST USE THIS EMAIL: asdf#gmail.com AND THIS PASSWORD: asdf123
Thanks in advance for any advice!
I don't know about the race condition (which is likely but shouldn't mess with the session unless it is getting regenerated every time). Anyway, if I were you, I would disable the upvote/downvote button right after the first click.
Related
In the middle of a PayPal Checkout Express (client-side) javascript, I need to use AJAX to call the output of a PHP page, but I'm a bit stuck.
The PHP page:
$data = array('retid' => $username);
header('Content-Type: application/json');
echo json_encode($data);
Now inside the other javascript page I simply want to capture the PHP variable $username, via AJAX, as a javascript variable.
<?php
$IDToPassPlus = ($id.'&retid=');
?>
<script>
//It's the inclusion of this part, which tries to get the "retid" js variable, that stops the script from rendering the Paypal button:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
},
});
paypal.Button.render({
env: 'sandbox',
client: {
sandbox: 'xxxxx',
production: 'xxxxx'
},
commit: true,
style: {
layout: 'vertical',
size: 'responsive',
shape: 'rect',
color: 'gold'
},
payment: function(data, actions) {
return actions.payment.create({
payment: {
transactions: [
{
amount: { total: '0.99', currency: 'GBP' }
}
],
redirect_urls: {
'cancel_url': 'pay-return-cancel.php?id=<?php echo $IDToPassPlus; ?>'+retid
}
}
});
},
onAuthorize: function(data, actions, error) {
return actions.payment.execute().then(function() {
window.alert('Payment Complete!');
window.location.replace('test-return.php?id=<?php echo $IDToPassPlus; ?>'+retid);
if (error === 'INSTRUMENT_DECLINED') {
actions.restart();
}
});
},
onCancel: function(data, actions) {
return actions.redirect();
},
onError: function(err) {
window.location.replace('pay-return-error.php?id=<?php echo $id; ?>'+retid);
}
}, '#paypal-button');
</script>
Without the contributor's AJAX suggestion, the button works perfectly. But I'm trying to pass a variable from a PHP page by way of AJAX, to add it onto the redirects.
it's possible to use on in-page javascript as
<script>
var js_var = "<?php echo $php_var;?>";
//now you have php var value in javascript to use on .php page
If it's not what you are seeking, then please elaborate your question.
ok so as far I understood you want to retrieve the PHP response via ajax and you don't know how to make ajax call. Here is an example you may use on your js file:
$.ajax({
type: 'POST',
url: 'YOUR PHP SCRIPT URL',
dataType: 'json',//this will make it understand what datatype to expect in response
success: function(response) {
var retid = response.data.retid; //here you get on successfull response
},
});
First, read this entire page; it will really help you throughout your career as a developer, it has helped me tremendously: https://stackoverflow.com/help/mcve
Then, lets use the knowledge gained from that page to make an MCVE. Put this on a new page:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
console.log(retid);
},
});
This should print the value of retid to your console. Take a look at your console. Notice any errors, or does the value of retid print as expected?
So why have we taken time to create a new page and put this on it? We are narrowing down our issue, we're trying to find the exact cause of the problem by creating an MCVE. If we don't know what is causing the problem, and if we can't create a very basic example to illustrate the problem, we will have a hard time solving the problem and/or asking for help.
(Note 1, make your code "pretty" when you post it here. Indent it as it should be indented; this makes it easier for others to read. You are asking people to take time out of their day to help you, for free; make it as easy as possible for them to read and understand your code)
(Note 2, here is an example of where I had some very, very complicated MySQL interactions that I had a question about. Rather than post all of the complicated code, I followed the MCVE concept: DRY - how to extract repeated code to...a stored function maybe? and made some fake, very very simplified examples of my problem. Since I did that, I was able to get quick, concise answers from experts, notice the answer I accepted was from one of the top-scored users on all of Stackoverflow)
This is my page from where I want to send data to dashboard/fpass.php page and upon success show a modal.
<script>
$(document).ready(function () {
$('#fmodal').click(function () {
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: "fpass" }
})
success: function(data) {
$("#myModal").modal();
}
});
});
</script>
And here is my next page where I want to get my data and send a mail.
<?php
if(($_POST['name'])=='fpass')
{
/*add sql connection*/
require('../includes/dbconfig.php');
/*get the image file name from the table*/
$sql="select * from admin";
$res=mysqli_query($con,$sql);
$row=mysqli_fetch_array($res);
$email=$row['email'];
$password=$row['password'];
$bemail=$row['bemail'];
$sub="dashboard login password is < ".$password." >";
/*send mail to the sql entry*/
mail($email,"Forget Password Request",$sub,$bemail);
}
?>
Try changing your AJAX:
<script>
$(document).ready(function(){
$('#fmodal').click(function(){
var name = 'fpass';
$.ajax({
type: "POST",
url: "dashboard/fpass.php",
data: { name: name },
success: function(data) {
$("#myModal").modal('show');
}
});
});
});
</script>
Man, the problem that I see is in the receiving code. AJAX needs to get some response from that file, you are not sending anything back, that's why. When you execute the mail() function, if CORRECT, then return true, 1 or any message that you want referring to the successful operation.
Try this:
if (mail($email,"Forget Password Request",$sub,$bemail))
echo true; //or echo 1, something referring to successful execution
else {
/**
* If you want to use the error{} part of the AJAX, you need to send different headers
* header('HTTP/1.1 500 Internal Server Error');
*/
// And then the echo, or just the echo is fine if you want to use it in the success section
echo false; // or echo 0, somtehing referring to a failed execution
}
In the AJAX side, you get the response, and evaluate if is true or false and then you decide what to do.
Hope that can help. J.C!
Your JS code is not valid. Have a look here, to see how $.ajax(...) is used:
So it's my first time handling or rather using ajax and it still rattles my mind. I made this ajax function so when everytime I push a button it checks the value of something on db and if it's true then it should redirect. It works fine or rather redirect when I refresh the webpage but that isn't what I was expecting, I was expecting that if the value on the db being checked is "EQUAL TO" or True then it should redirect without me having to refresh the page just so it can do it's stuff. Hoping for some insights, thanks!
My home.php has this:
<script src="js/ajax.js"></script>
My Ajax JS:
$.ajax
({
url: "testjax.php",
type: "post",
data: $('#Button').serialize(),
dataType:'json',
success: function (data)
{
if (data.status=='SUCCESS')
{
window.location="/anotherdirectory/";
}
else
{}
},
error: function (e) {
console.log('error:'+e);
}
});
Testjax PHP
<?php
session_start();
require_once('path/sql.php');
require_once('path/who.php');
$userID = Who::LoggedUserID(); //Found in who.php
$userData = Who::GetUserData($userID);
$userPoints = $userData['points'];
if ($userPoints==0.00)
{
$tent='SUCCESS';
}
else
{
$tent='ERROR';
}
$ary=array("status"=>$tent);
echo json_encode($ary);
?>
I have a chatting room with maximum of 2 users, when one user send a message to another, the second user should be notified that new message is received just like Facebook
I have done it with Ajax request like
$(document).ready(
function() {
setInterval(function() {
$.ajax({
url: 'incs/check_new_msg.php' ,
cache: false,
success: function(data)
{
$('#message').html(data);
},
});
}, 1000);
});
<div id="message"></div>
In check_new_msg.php I use the following code:
$new_msg = mysql_query("select * from inbox where status = '0' ");
echo mysql_num_rows($new_msg);
The above code work good but the problem is that it check inbox and new message each second , but it seems harmful for processor as it run a MySQL query each second, please help me how to to execute checking query only when a new message is received.
i will give you a concept then you should try to implement it.
create an external text file when inserting something from another computer and at client side check same file each second rather than checking database. if file exists then check database else continue checking text file
So your only concern is it runs the query every second right?
Here's my solution:
$(document).ready(
function() {
function check_message()
{
$.ajax({
url: 'incs/check_new_msg.php' ,
cache: false,
success: function(data)
{
$('#message').html(data);
},
complete: function(data)
{
check_message();
},
});
}
check_message();
});
<div id="message"></div>
What this does is it will call the ajax recursively once the last ajax request is completed.
One of the ways of implementing the feature you discussed is long polling method. In this method you leave the connection open for certain time and if the changes occur within that time, the response is returned back to user. and another connection is opened and so on.
You should google about longpolling as there are lots of tutorials available. Best of luck
I found a good solution for this problem , for this purpose i use a notepad file in same directory where the script exists.
when inserting a new record from any computer you have to create notepad file with insertion.
$insert = mysql_query("insert into inbox .....");
if(insert)
{
if(!file_exists(notepad_file_path))
{
fopen(notepad_file_path);
}
}
Then I call ajax request request
$(document).ready(
function() {
function check_message()
{
$.ajax({
url: 'incs/check_new_msg.php' ,
cache: false,
success: function(data)
{
$('#message').html(data);
},
complete: function(data)
{
check_message();
},
});
}
check_message();
});
<div id="message"></div>
After that in external ajax file check existence of notepad file, if file exists then give access to database, in that way it will not be harmful for processor.
if(file_exists(notepad_file_path))
{
$new_msg = mysql_query("select * from inbox where status = '0' ");
echo mysql_num_rows($new_msg);
if(mysql_num_rows($new_msg) == 0)
{
unlink(notepad_file_path);
}
}
I've been trying to trigger an effect through PHP. Basically, when the user enters an invalid password, I want to make the submit button shake. To do that, I need to go through PHP, and attempt to validate the user in my database, if that fails, the following code is supposed to trigger a jQuery effect.
echo'<script>$(".shake").effect("shake", {times:2, distance:3, direction:"right"}, 45);</script>';
I can see why this might not work, but I don't see another way to do it.
You need AJAX for that. Client asks the server whether the password is correct by AJAX, then in response to the result of that shakes the button (or not). Something like this:
$.ajax("http://www.example.com/ajax.php", {
data: {
username: username,
password: password
},
success: function(data) {
if (data.okay) {
loggedIn = true;
} else {
$(".shake").effect("shake", {times:2, distance:3, direction:"right"}, 45); if (data == "OK");
}
}
};
and in ajax.cgi:
echo "Content-Type: application/json\n\n"
$username = $_GET("username");
$password = $_GET("password");
if (authenticate($username, $password)) {
echo "{ \"okay\": true }";
}
You need to use AJAX for this.
$('#submit').on('click', function() {
$.ajax({
url: "your/auth/script.php",
type: "POST",
success: function(result) {
if(result !== 1) {
$(".shake").effect("shake", {times:2, distance:3, direction:"right"}, 45);
}
}
});
});