I want only execute my ajax post 1 time, i try to avoid to the user refresh the page and execute so much times the ajax post,
I thought in create a cookies, but i don't know, and i'm no sure, somebody know how?
This is my jquery.
var t = jQuery.noConflict();
t( document ).ready(function() {
t.cookie("example", "foo", { expires: 7 }); // Sample 2
console.log( "ready!" );
alert(t.cookie("example"));
var data = '<?php echo json_encode($json_full);?>';
t.ajax({
url: 'my api url',
type: 'POST',
success: function(r) { alert(JSON.stringify(r)) },
dataType: 'JSON',
data: { data: data, }
})
});
/I need run this AJAX only one time because is a checkout page to send the order, and if i refresh the page, send every time the same order, and this i don't want/
Thanks a lot!
Things like these can not be safely controlled on the client's browser. Any user with minimal knowledge in JavaScript will be able to open up the developers tools for their browser and manipulate the code or any values you might have stored (such as deleting the cookie you have set).
This limitation should be implemented on the server.
It really depends on the scope of your application. You might be able to limit the requests per IP address, but that might prevent multiple people from the same office for example loading the page at the same time.
Using user authentication and persistent server storage you'll be able to limit the effect of the request, but you probably won't be able to prevent the actual request from being sent as anyone can make that request even from outside the browser. You could store the user_id of the user that initiated the request and only allow the resulting action to occur if a certain time has passed since the last request.
A better solution to avoid double submits, is to use a POST query for the submit request and let the server respond with a redirect to a normal (harmless) receipt/thankyou page.
Then if the user refreshes the receipt page they will simply repeat the GET request to the receipt page and not the post.
You should still add some checks server side to avoid multiple POST requests somehow (using sessions, timestamps or something), in case a malicious user deliberately tries to resubmit.
This will only work on IE8 and above, but you can use localStorage:
var t = jQuery.noConflict();
t( document ).ready(function() {
t.cookie("example", "foo", { expires: 7 }); // Sample 2
console.log( "ready!" );
alert(t.cookie("example"));
if(localStorage['submitted'] === undefined){
var data = '<?php echo json_encode($json_full);?>';
t.ajax({
url: 'my api url',
type: 'POST',
success: function(r) {
localStorage['submitted'] = true;
alert(JSON.stringify(r));
},
dataType: 'JSON',
data: { data: data, }
})
}
});
This way the first time it will run the AJAX because you haven't set the localStorage variable, but upon success you do and it will not resubmit on page refresh.
If you wanted to have the ability to send again upon a future visit, just use sessionStorage instead of localStorage. Same syntax and everything.
Related
This question already has answers here:
Can the unload Event be Used to Reliably fire ajax Request?
(5 answers)
Closed 4 years ago.
I'm creating a queue-like page where only 1 person should be able to edit information about a specific database entry at a time.
Let's say a user is on page profile.php?id=1 - only the very first person who loaded this page should be able to make changes to it.
I've attempted to do this with JavaScript/jQuery, but am facing a problem.
On page load, I send an AJAX request to a PHP file that essentially sets a table cell to true for a specific ID. Then, I use a beforeunload event to set this cell to false when the page is unloaded. With this specific implementation, there is a problem though. The beforeunload event is either not fired when the tab is closed, or it is fired and the AJAX request does not have time to complete. This is a big problem because a user could potentially load up the page, see there is nothing to edit, and then close the tab without thinking about it, thus locking the page indefinitely until I reverse the lock in the database manually - and I would hate to have to force people to not use their browser the way they want to.
Here is my code:
$( document ).ready(function() {
var locked = <?=json_encode($data['in-review']);?>;
if(locked) {
$('input').attr('disabled', true);
$('#delete-model-button').attr('disabled', true);
$('#uidfield').attr('disabled', true);
$('#submitbutton').attr('disabled', true).text("This model is in review by another reviewer.");
} else {
$.ajax({
url: 'process/in-review.php',
type: 'POST',
data: {uid: $("#uidfield").val(), value: 1},
success: function (result) {
console.log("Model Locked in Review");
}
});
$(window).on('beforeunload', function() {
$.ajax({
url: 'process/in-review.php',
type: 'POST',
data: {uid: $("#uidfield").val(), value: 0},
success: function (result) {
console.log("Model Unlocked");
}
});
});
}
});
As you can see, if a user loads into a page that is already review locked, the beforeunload process is not called at all because that would allow users to unlock a form that another user may be working on.
How can I effectively unlock these pages if a user closes their tab or browser?
In case it matters, here is my in-review.php page:
<?php
include('db.php');
$uid = $_POST['uid'];
$value = $_POST['value'];
$db->run("UPDATE `devices` SET `in-review`=? WHERE `uid`=?", [$value, $uid]);
--EDIT:
This is commented as a duplicate question, but I disagree with this. That question is specifically asking "Can the unload Event be Used to Reliably fire ajax Request?" - I already know the answer to that is "Yes", because that is the method I am currently using, I also know it does not work at all for closing tabs/browser, therefore my question is not if this is a reliable method for what I want to do (I already know it is not), I'm asking for a different method that I can use to do this.
have you tried making a synchronous call of Ajax in beforeunload event?
i.e.
$(window).on('beforeunload', function() {
$.ajax({
url: 'process/in-review.php',
type: 'POST',
async: false,
data: {uid: $("#uidfield").val(), value: 0},
success: function (result) {
console.log("Model Unlocked");
}
});
});
The problem here is browser needs to keep connect alive with the server until the request is completed.
When the user clicks on other pages in your application that means connection to the server is alive and operation can be completed, and in case of browser/tab close connection to server is lost.
This might work on some situations i.e. your server was fast enough to respond before complete browser closure i.e. destruction in window object
I wants to get updated comment from chat list to the page without refreshing the page, Thats I have used ajax call for the list but I have to call this function for every 5 seconds to check whether new chat is inserted or not to the database,
$(document).ready(function(){
setInterval(function(){
$.ajax({
type:'POST',
url: baseUrl+"chat",
cache: false,
data: dataString,
crossDomain: true,
success: function(data){
var getData = JSON.parse(data);
if(getData.status == "success")
{
for(i=0;i<getData.chat.length)
{
$("chatList").text("");
$("chatList").append("<span class='black'>"+getData["chat"][i].name+" : <span class='blue'>"+getData["chat"][i].comment+"</span>");
}
}
else
{
alert(getData.message);
}
}
});
},5000);
});
So I wants to know if there is any easy way to do this or from PHP MySQL it is possible to send page a new comment inserted notification ?
Best practice is to use HTML5 WEB WORKERS.
HTML5 Web Workers
The problem with JavaScript on the browser is that it runs on a single thread. In other words, two scripts or processes cannot run simultaneously. If you are processing JavaScript after page load, the end user cannot interact dynamically with the page. The JavaScript will not handle UI events while processing something else. If you process something large before page load, the end user has to wait all-together which is a horrible user experience.
You can use a websocket, socket.io for example. That will allow you to send notifications from the server to the client.
So, when you recieve data from your chat (cient) in your API (server), after updating the database, you will have to send a 'notification' to your client.
When your client get the notification, you can make your AJAX call :
socket.on('notification', function(){
doYourAJAXStuff();
});
You can use socket.io api to get real-time information to the client..
I have an html page and I need to load some usual information(can be seen by all people) from DB.
so I put this code in the html:
<script type="text/javascript">
$(document).ready( function() {
setTimeout( "getRate()", 100 );
});
function getRate() {
$.ajax( {
type: "GET",
url: "api.php",
dataType: "json",
data: {call: 'getRate'},
success: function(result){
//set result to the DOM element....
},
error: function(){
}
});
}
</script>
and I have a api.php file like this:
<?php
if($_SERVER['REQUEST_METHOD']=="GET") {
$function = $_GET['call'];
if($function == "getRate") {
//get result from DB
echo json_encode(result);
}
}
but my code reviewer said that when put this url in the browser directly "https://****.com/api.php?call=getRate", it also returned the json result,is it safe??
well there is no secret information requested by the ajax call,so
it's I think it's OK , but I'm not sure.
Is there any security risk for doing like this?
If your question is whether or AJAX itself is secure, then yes, AJAX is used all the time to exchange information between a browser and a remote API.
As for your code specifically, there doesn't seem to be a vulnerability here provided:
The raw JSON response truly doesn't have any secret information
The SQL query (or equivalent) used to generate the JSON isn't vulnerable to injection attacks if someone tries to craft the call: getRate param to something malicious.
The AJAX call doesn't alter the state of the database
The AJAX call doesn't tie up resources for anything other than a very small amount of time. For instance someone spamming https://****.com/api.php?call=getRate shouldn't bring down the site.
I am creating A login system using AJAX,PHP & SQL obviously.
Anyway I am trying to implement A real time login feature so it will log the user in without refreshing the page.
I have done that almost but the only issue when the user clicks remember me that uses cookies instead of sessions but the JQuery isn't proccessing that?
I want it to detect depending if it was checked ether remember the user or not it only starts a session, when it does register a cookie the logout page is not deleting the cookie which he did before i added the jquery code in so nothing on the php end and I am mainly A PHP Developer and still learning.
(I cannot post the server side code for privacy reasons as I be using this in A project
but it looks similar to any other normal php login script)
Here's the JQuery
function validLogin(){
var user_login=$('#user_login').val();
var user_pass=$('#user_pass').val();
var remember_me=$('#remember_me');
var dataString = 'user_login='+ user_login + '&user_pass='+ user_pass;
$("#flash").show();
$("#flash").fadeIn(100).html('Loading..');
$.ajax({
type: "POST",
url: "ajax/procces.php",
data: dataString,
cache: false,
success: function(result){
var result=trim(result);
$("#flash").hide();
if(result=='correct'){
window.location='index.php';
}else{
$("#errorMessage").html(result);
}
}
});
}
function trim(str){
var str=str.replace(/^\s+|\s+$/,'');
return str;
}
Thanks
You don't pass your variable 'remember me' to your ajax request. For instance :
data: {login: user_login, passwd: user_pass, rememberMe: remember_me}
Another point, be careful you treat information from client-side. Never trust the client. Test all your values in PHP.
i am new to web development creating a kind of social networking website for college project. I want to include update the messages count in the message menu every time there is a new msg in the database for the user(like facebook message menu on homepage)
But it's frustrating learning ajax, however after searching on web and reading some topics from some books I came to the solution that i can make an $ajax call in my js file in the homepage and send data ('name'=>'user') stored in javascript cookie that i have created on loading of home page after the user login, to a php file which will search across the recent_msg table in database to fetch the recent message for the logged in user if any after fetching the php file will create the html file with code snippet and further another jquery code will append that snippet from file to the message list menu.
the PHP part is not the problem but how can i send the username to the php file using jquery ajax api, here is the code what i think i can apply but i am doubtful in that if this is the correct way
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
}
} );
},10);
});
what is the purpose of success function in the code?
data needs to be in the form of an object / key-value-pair (EDIT: or if a string, as a valid querystring). data: { name: usr }. However, since it's in a cookie, your PHP page will have direct access to that cookie. It's safer to let your session cookie tel the PHP page who the user is instead of relying on an AJAX call to tell the PHP page who it is.
http://php.net/manual/en/features.cookies.php
So I'd drop data from your AJAX call altogether, and in your PHP page, use $_COOKIE["name:"]
Then whatever HTML gets passed back from the PHP page will arrive in the data call. If it's HTML, then simply add it to your HTML to some message div, such as.
<div id="recent-messages"></div>
<script type="text/javascript">
$(document).ready(function{
setInterval ( function()
{
var usr = getCookie("name");
$.ajax ( {
url: '/phpScripts/recent_msg.php',
type: 'POST',
data: usr,
success: function(data){
$('#recent-messages').html(data);
}
} );
},10);
});
</script>
The success function executes whenever your ajax call completes successfully. This means that the page actually exists and no server-side errors occurred on the page. The variable data will contain whatever information is returned from the page on the sever /phpScripts/recent_msg.php. Generally this is either json or xml, but it entirely depends on your implementation of recent_msg.php.
If the user has to log in that means you have to have created a session. In that case you can store the logged in user's information such as their name in $_SESSION on the server and there is no need to store it as a cookie. Since $_SESSION is already on the server, there is no need to send that data via ajax in any case.