How to improve my ajax script to get data faster - javascript

I want to do is when a user fill a valid email in the textbox and click the send button it will send to his email his password directly.
My problem is the result takes 3 secs or more in order the ajax script receives the result specially when the php echo 0 to ajax. Does anyone know how to make my code faster?

Make your connection persistent using mysql_pconnect.
Return only changed data and apply the difference instead of returning whole set of data.
Also, instead of hitting database often, you can cache as much as you can.
Also, refer to PHP micro-optimization tips.

Asynchronous request doesn't mean the request are fast, it means you can continue with your code flow without waiting for the response.
Running a query on your database and sending a mail will take time.

The problem might be not in your ajax code.
Not really know how many records in table tbl_mkash. For a lot number of records (million of records) indexing field elog_email might speed up the query.

Related

Most efficient way of executing/validating values in javascript by getting mysql values using AJAX OR Cookies

I want to select the entire table from mysql and validate those values using javascript. I know I can do this using AJAX which will send a HTTP request to the server but I feel sending too many HTTP request to the server can be quite bad as the page will load much slower, or I could store the value as the page load in the client cookie. I think it will be much faster but might be too much data stored in the cookie specially if the mysql table is too big.
What do you guys think should be the best approach for this? Is it a good thing to store mysql data in a client cookies
UPDATE
Say I have 100 Items in mysql, these 100 items I needed them displayed in a page dynamically, as the next time the page is loaded there might be 101. That means I need to validate how many items are there and allocate them to the page, and im not sure how to do that and where either client side or server side.
You could do an AJAX call for the information, do the validating of what data you need/don't need, then send it back as an array. When you get the array back you can do a for loop through the array creating the div's for each index/object in the array. This way if you have 5 items that need to be shown, you can show them. Then later if you have 7, you can show them as well. Hope this helps!

PHP code to write current score to MySQL database

I have a website where you need to create an account and login to play the game. I have PHP that refers to a MySQL database with a column for UserId, Username, firstname, lastname, password and score. The login works fine. Then, you are taken to the html document that contains the game. It is somewhat like cookie clicker, where your objective is to get the highest score possible through interacting with an object.
I have a score variable called "clicks" which increases quite rapidly.
I have some javascript code that reads;
if (clicks%5==0) {
sendScore()
}
What this means is when clicks is divisibly by 5 it activates a function called sendScore. It activates the function every 5 increments because I assume sending data to the table multiple times a second would be demanding too much from the server. This function will write the current players score to the MySQL table column named "score", the row in relation to the players UserID. UserID is a number that is generated when an account is created so that the user's account can be easily referred to.
I know its just me overthinking it, but I cannot seem to write a working piece of PHP code that I can link to the sendScore() function that sends the player's current score ('clicks' javascript variable) to their score column in the MySQL database.
Any help would be appreciated.
Thank you.
NOTE!!!!
The request to send info has to be an AJAX request. Maybe this is why it doesn't work. I am used to writing forms, but forms would refresh the page. Can anyone help write an AJAX request for this situation?
What is your current sendScore function?
It is kind of hard to give a detailed answer without more of your code, but I'll try:
Your sendScore function will need to send a request to the PHP script that will handle this request. You can do that either using pure JavaScript, using XMLHttpRequest. More on that here: http://blog.garstasio.com/you-dont-need-jquery/ajax/. However, you can also use a framework such as jQuery to do some of the heavier lifting. More on jQuery and AJAX functions (specifically post-requests) can be found here: https://api.jquery.com/jQuery.post/.
Then you'll need a PHP function that can handle the request. You have to point your JavaScript function (that performs the POST request) to the URL of this script. Then you can process the information sent by your JavaScript just as you would process a 'normal' form.
To get your values from JavaScript to PHP and vice versa, it's probably easiest to use JSON, as both JavaScript and PHP handle JSON nicely these days, and it's a lot easier than XML.

Prevent fake looping ajax requests to PHP

On my website, I have created a comment section for blog posts. Users can write comments, click a button, and an AJAX request will be sent to PHP containing the data in JSON. The PHP will process & validate the data and then insert it into the database. On success, all comments are retrieved from the database and, using JQuery, all of the page's comments are reloaded.
The problem is that anyone can come along and, using their browser's console, forge an AJAX request, fill in their own JSON, and send the request to PHP. If done like this, all that happens is my client-side validation is useless. The server-side validation would still work. However, there's a bigger problem.
for(var i = 0; i < 10000; i++) {
//ajax request
}
The user can very easily insert thousands and thousands of records into my database instantly.
Does anybody have any suggestions on how I can prevent something like this from happening? It must involve creating something on the server side that can't be guessed by a user, and somehow checking against that during an AJAX request. I'm just not sure how exactly to go about this.
Thanks for the help.
The only way for you to be safe in this respect is to add a CAPTCHA.
This will prevent mass / automated posts. One possible library to use is Securimage . It is simple to use and integrate. You can have it running in 10 minutes with your AJAX stuff.
Relying on other means such as cookies or client side validation of some sort is risky, if possible at all. For instnace KA_lin 's solution can be compromised in 5 minutes: a malicious user can be sending forged cookies that will always have a page count of 0 and thus will always be allowed to post. Or even worse, he could create a small program that will post to your page without sending any cookie at all. The above code will create a new cookie and accept his post, every time ...
I would add a session variable containing the number of posts a user makes, given many pages you can form something like $SESSION['page_id_total_nr_comments'] and track this number, add a config variable that let`s the use to add a maximum of X comments per article for example:
function canUserAddComment($pageId){
$maxAllowed =......;
if(!isset($SESSION[$pageId+'_nr_comments'])){
$SESSION[$pageId+'_nr_comments'] = 0;
}
if($SESSION[$pageId+'_nr_comments']< $maxAllowed){
$SESSION[$pageId+'_nr_comments']++;
return true;
}
return false;
}
OR
On save get the number of comments a use already made on the article and decide if ha can make another(still with a config variable)

jQuery: Using a single Ajax call, receive progressive statuses instead of one single response?

I'm just wondering..is it possible to receive multiple responses from a single ajax call?
I'm thinking purely for aesthetic purposes to update the status on the client side.
I have a single ajax method that's called on form submit
$.ajax({
url: 'ajax-process.php',
data: data,
dataType: 'json',
type: 'post',
success: function (j) {
}
});
I can only get one response from the server-side. Is it possible to retrieve intermittent statuses? Such as:
Default (first): Creating account
Next: Sending email confirmation
Next: Done
Thanks for your help! :)
From a single ajax call, I don't think it is possible.
What you could do is check frequently where the process is (it's what is used for the upload bars in gmail for example). You do a first ajax request to launch the process, and then a series of ajax request to ask the server how he is doing. When the server answers "I'm done", you're good to go, and until that you can make the server respond and say the current state.
There is something called comet which you can set up to "push" requests to client, however it is probably way more than what you are wanting to invest in, time-wise.
You can open up a steady stream from the server, so that it continues to output, however I'm not sure how client-side script can handle these as individual "messages". Think about it like a server that outputs some info to the browser, does more work, outputs some more to the browser, does more work, etc. This shows up more or less in real time to the browser as printed text. It is one long response, but it is still one response. I think ajax only handles a response once it finished being sent, but maybe someone else will know more than me on the topic.
But you couldn't have the server output several individual responses without reloading itself, at least not with PHP, because once you start outputting the response, the response has begun and you can't chop that up without finishing the response, which happens when the script is done executing.
Your best bet is with the steady stream, but again, I'm not sure how ajax handles getting responses in chunks.
Quick Update
Based on the notes for this plugin:
[http://plugins.jquery.com/project/ajax-http-stream]
things don't look promising. Specifically:
Apparently the trend is to disallow access to the xmlhttprequest.responseText before the request is complete (stupid imo). Sorry there's nothing I can do to fix this
Thus, not only can you not get what you want in one request, you probably can't get it multiple requests, unless you want to break up the actual server-side process into several parts, and only have it continue to the next step when an ajax function triggers it.
Another option would be to have your script write it's status at specific points to another file on the server, call it "status.xml" or "status.txt". Have your first ajax function initialize the process, and have a second ajax function that queries this status file and outputs that to the user.
It is possible, but it has more to do with your backend script. As Anthony mentioned there is a tech called comet. Another term I've heard is called "Long polling". The idea is that you delay the time in which your php(insert language of choice) script finished processing.
In php you can do something like this:
while($response !== 'I'm done'){
sleep(1);
}else{
return $some_value;
exit();
}
This code stops your script from completely finishing. sleep(1) allows the script to stop and lets the server rest for 1 millisecond, before it loops back through. You can adjust the sleep time based on your needs. In php the amount of time the script sleeps is not counted agains your server timeout time.
You'll obviously need to make more checks for you code. You'll probably also want to allow for an abort script call. Something like sending a get request to kill the backend script. Maybe on the javascript unload event.
In the tests that I've done. I made the initial ajax call, and when the value was returned, I made another ajax call, that way your back end script wont time out.
I've only played around with this on my local server, so i'm not sure how real world this is, but it works.

header(Location:) via AJAX not redirecting

First off, let me say that I know this does not seem like an uncommon issue. I do not intend to clutter these forums with questions that have already been answered, but, I have worked through probably about 3 dozen threads with similar issues and have been unable to reach a solution.
The short description of my issue is this: I am trying to redirect after submitting a form using php's header(location:) function, and it's not redirecting. It is a little bit complicated because the form is submitted via AJAX. The steps my code goes through are as follows:
User submits form > form data sent via AJAX > form processing page validates data > if valid, form processing page inserts data into database > if submission is successful, form processing page adds redirect URL to $_SESSION > form processing page returns a 'redirect' variable > javascript/AJAX checks for redirect variable, and refreshes page if found > page header checks $_SESSION for redirect URL, and if found, sets appropriate headers and exits.
I guess the first thing I want to ask is, is this the right way of going about this? It seems to me that there should be a simpler way of doing this. It's obviously much simpler to pass the redirect URL to the javascript and do a window.location redirect, but I read that it's much better/more secure to handle that on the server side, so I'm trying to do that.
Assuming I'm going about this in the right direction, what could be going wrong here? I've checked for leading and trailing whitespace, BOM characters, I've even tried output buffering and I still have the same issue.
What happens on form submission is, the page refreshes, but it returns to the original form page rather than the redirect url. I have turned on the most detailed error reporting and get no errors at all.
One thing that may or may not be of interest, I have an error_log function set up to log all headers to a file right after I set the Location: header. When I redirect outside of AJAX (which works), the accept: header is set to html, but when I try to do it via AJAX, the accept header is set to JSON. Could that cause a problem?
Thank you so much for taking the time, and again, apologies if this is a dumb question. I have used this forum for years and have never once had to post a question on it because it has always solved my problems until now. Thanks in advance!
PHP is too generous to include in your code not only HTML code, but also JavaScript code. I'll explain one thing. When you send data by ajax, it is often difficult return Boolean data (whether true or false, depending on the conditions we work side server with php in some file established in our direction ajax) to give a final answer.
On the other hand, returning to the generosity of PHP, always when we try to validate data server-side and through ajax, we can manipulate the section where work freely to show some response message, a redirect to somewhere on your page or create a session. Anyway, whatever.
What I mean is that in your controller section where you will work with AJAX, you can set different conditions. That is, if the user data are correct, then you could send to call a script from Javascript to redirect him with a location.reload (); and also assign a session automatically. If the user does not have the correct data, then what we should do is return a warning message or alert to the exit AJAX, usually it goes after a:
function (response) {
$ ('.answer').html(response);
}
Note that it is not necessary require, for example, a $ ('.answer').html(response); to return an answer, because ajax only sends data to the server and if there is a reply message well, and if not well. Many times what I do, is to send messages via console, although it is often convenient to do so, because as often work with several conditions and that depends on the result of our request, we will be forced to show some response in some element within our code.
What I advise you is that you work javascript in PHP, and hence redirect to other pages, assign sessions or simply return a message. Remember that an ajax request is not only asynchronous, but repetitive and can send it to call as often as you need. The fact that you sent your ajax call php file and you have returned an answer, does not mean you can go back to work with it once you finish your ajax request.
It is the right way to do what you want, it is often easier to manipulate our server-side code that client side. Greetings.

Categories

Resources