How to increase the speed of Ajax Like Button (jQuery + PHP)

I made Ajax Like Button. After pressing a similar button, it takes about 800 ms - 1100 ms to perform the following actions:

  • Open insertlike.php page in background using jQuery
  • Add this to the database at insertlike.php
  • Confirm like this using JSON
  • Turn the button color as green.

But Facebook's and the other site Like Button works really fast.

Does Facebook directly change the color of the button as on a click, or does it only change after adding this to the database?

This is my code:

index.php 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 same button speed? Maybe some php cache trick or something like that? I'm still a beginner.

Edit: this is a server response time rate test:

enter image description here

+5
source share
2 answers

You can keep track of events based architecture . As soon as the user clicks on the type button, put the message in the queue and then write to the database in the background (Data Grid may also be the solution here, not sure if PHP has good grid solutions). And the response to the client will be sent back, provided that the record in the database is successfully updated.

https://martinfowler.com/articles/201701-event-driven.html

If you are updating a single table, then 800 ms - 1100 ms does not seem to be an acceptable timeline. Try to configure your SQL, check if the database is configured correctly. Try using ConnectionPool etc.

On Facebook, a. except updating the database, for example, b. It also performs other background processing, such as generating NewsFeeds for relevant parties, etc. I assume that FB can execute part b using an event-based architecture rather than keeping the user on hold.

+2
source

Why are you doing . submit() . submit() you should do . click() . click() .

And what Facebook does is likely to change the color of the button right on click, without waiting for an answer. If the answer causes an error, the button color will probably be changed to normal.

+1
source

Source: https://habr.com/ru/post/1272693/


All Articles