I have made a Ajax Like Button. After clicking the like button, it takes around 800ms - 1100 ms to do the following things:
insertlike.php
page in the background using Jqueryinsertlike.php
pageBut Facebook's
and other website's Like button works very fast.
Facebook directly change the like button color on click or it only change after adding the like into database?
This is my code:
index.php
code to make ajax request
$(".insertlike").submit(function(e) {
var data = $(this).serialize();
var url = $(this).attr("action");
var form = $(this);
$.post(url, data, function(data) {
try {
data = JSON.parse(data);
$(form).children("button").html(data.addremove + " Watchlist");
$(form).children("input#addedornotsend").attr("value",data.addedornotsend);
} catch (e) {
console.log("json encoding failed");
return false;
}
});
return false;
});
Code inside insertlike.php
<?php
// Add to Database code
$response = new \stdClass();
$response->addremove = "".$addremove."";
$response->addedornotsend = "".$addedornotsend."";
die(json_encode($response));
Any way to insert the like button speed? Maybe some php cache trick or something like that? I am still newbie.
Edit: This is my server response time speed test:
You can follow the Event Based Architecture. As soon as, user clicks on the like button, put the message in queue and then write to DB in background(Data Grid also can be a solution here, not sure if PHP has good data-grid solutions). And response to client will be sent back, assuming DB record is updated successfully.
https://martinfowler.com/articles/201701-event-driven.html
If you are updating single table, 800ms - 1100 ms does not seem to be acceptable timeline. Try to tune your SQL, check if the DB is properly tuned.Try to use ConnectionPool etc.
In Facebook, a. apart from updating the DB on like, b. It also does other background processing like generating the NewsFeeds to relevant parties etc. I am speculating that FB might be doing part b using events based architecture rather than keeping the user to wait.
Why are you doing . submit()
, you should be doing . click()
.
And what Facebook does is probably changing button's color right on click, without waiting for response. If the response results in error then probably the button's color is changed back to normal.