How to increase my Ajax Like Button Speed (Jquery + PHP) - javascript

I have made a Ajax Like Button. After clicking the like button, it takes around 800ms - 1100 ms to do the following things:
Open insertlike.php page in the background using Jquery
Add the like to database in insertlike.php page
Confirm the like using JSON
Turn the like button color into green.
But 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.

Related

JavaScript alert window after php script executed

here is may delete script - klient_usuwanie_script.php - It's working very well. BUT I would like it to present JavaScript alert when a record is deleted. So after the script deletes record it is a window with records shown - klient_usuwanie.php But I would like it to be this window with records but also with an alert saying "record deleted"
<?php
$sql = "DELETE FROM Klienci WHERE id= :del_klient";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
'del_klient' => $_GET['id']
));
header('Location:klient_usuwanie.php?msg='.urlencode($msg).'');
?>
So to clear it up. I have a page where I see records to delete - klient_usuwanie.php with a button "delete". When I press delete the script klient_usuwanie_script.php (which is included above) deletes a record. After that it redirects to the page klient_usuwanie.php and I can see other records and I can delete them. BUT after I delete a record I would like an alert window which says "Record deleted" that's all.
When I comment out
header('Location:klient_usuwanie.php?msg='.urlencode($msg).'');
and put
echo .$stmt->rowCount();
Than it shows me that one record was deleted but I would like it to be in an alert window and ideally alert to be shown on a redirected page.
You can redirect with query string like this:
header('Location:klient_usuwanie.php?msg='.urlencode($msg).'&deleted=true');
And in klient_usuwanie.php, parse the query param and show alert with javascript like the following:
window.onload = function() {
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.get("deleted") === "true") {
alert("Record deleted");
}
}
Add to header('Location:klient_usuwanie.php?msg='.urlencode($msg).'');
header('Location:klient_usuwanie.php?msg='.urlencode($msg).'&skasowane=tak');
In the klient_usuwanie.php add someting like this:
if($_GET['skasowane']=="tak"){echo "<script>alert(\"I am an alert box!\");</script>";}
echo '<script type="text/javascript" language="Javascript">alert("Record Deleted Thats all")
</script>';
Suggestion for modern approach:
Disclaimer: This answer is more related to the intention than the exact request.
Why? Doing a full page reload for this sort of request is an outdated practice.
Nowadays, you'd more likely rely on AJAX calls for this sort of scenario.
A delete endpoint would take in a request with the ID and respond the correct HTTP code to indicate if operation was successful.
Restful HTTP endpoints can of course be written in PHP to respond with data instead of HTML.
Check out Swagger with good endpoint examples: https://editor.swagger.io
In your front-end, you could then implement the necessary JavaScript code to execute the AJAX request and manipulate the DOM as necessary.
Though many would use a Framework like Angular or React to standardise this workflow.
User Experience
This approach is far nicer to users as the browser does not need to reload the entire page again. As it only triggers one tiny HTTP request, it's much faster and the scroll location doesn't jump around either.
I've put up an example for the HTML on JS-Fiddle with jQuery to simplify the AJAX call:
https://jsfiddle.net/sny9hw73/3/
Example:
<div id="entry-<?=$id;?>" class="banner-message">
<p>My Entry with real request</p>
<button onClick="delete(<?=$id;?>);">Delete Entry</button>
</div>
<script>
function delete(id) {
$.ajax({
url: '/entry.php,
data: { 'entryId': id },
type: 'DELETE',
success: function(result) {
$('#entry-' + id).remove();
},
fail: alert('Delete Record No: ' + id + ' failed')
}
</script>
Note:
Alerts are also not always great. While simple, they stop code execution and don't render well in some scenarios. I.e.: inside webviews or on mobile devices.
They also cause fullscreen to exit.
A more professional approach is to have the notification played in the DOM.
Angular Material's Snackbar is neater in that sense.

Checking if a sessions is empty, unsetting it, and then sending $_POST data onclick

I have two possible sets of information to export to another PHP page whenever i click a button.
One of them is a session. It's something like this:
$_SESSION['excel_name']['Main_'] = "Main_".date("y_m_d_Hi");
$_SESSION['excel_array']['Main_']['Plan1'] = array();
The post data sends the same information, but doesn't save it in a session to prevent conflict between too many sessions. So what i want to try, is to check if there is a session set. If there is, i'll unset it, and send the $_POST data. When there isn't, i'll set one. I have tried doing this:
session_start();
if(isset($_SESSION) && !empty($_SESSION)) {
unset($_SESSION['Main_']);
unset($_SESSION['Plan1']);
unset($_SESSION['excel_array']);
$_POST['excel_name']['Main_'] = "Main_".date("y_m_d_Hi");
$_POST['excel_array']['Main_']['Plan1'] = array();
} else {
$_SESSION['excel_name']['Main_'] = "Main_".date("y_m_d_Hi");
$_SESSION['excel_array']['Main_']['Plan1'] = array();
}
The logic might seem a little weird for some of you, but i'm almost certain it would work... But. I wanted to do this in a button. Reason being, whenever i click the button, I export the information to the next PHP page. I want to check for these conditions before sending the information, not in the moment i load the page.
Is it possible?
There is several way to do it, but before reading my answer, please note that javascript verification can be edited and exploited maliciously.
You could do an AJAX request to a php page that would implement your logic and return a code 200 or 401. Then you can act before the next page loads.

How to use JS to display images from database

So I made a website that displays FPS information stored in a mysql database. For each second of gameplay I have a pair of number(fps)-image(screenshot).
I display the numbers in a line chart made with JavaScript. The behaviour desired is when I click on a bullet in the chart, the screenshot for that particular second is displayed in a div on the page.
I have to mention that the screenshots are stored in the database and they are very low in size. I display then using PHP like this:
$query = "SELECT `image` FROM `logs` WHERE `session_id`=".$_GET['session']." AND `second`=".$second;
$sth = $mysqli->query($query);
$result=mysqli_fetch_array($sth);
if (!empty($result))
echo ' <img id="screen" src="data:image/jpg;base64,'.base64_encode($result['image']).'"/>';
The method I'm using now is when I click on a bullet in the chart (action recorded in JS), I send it as a GET parameter and read it with PHP afterwards, like this:
window.location.href = url + "?second=" + second;
This method obviously will refresh my page. The problem is, the chart I made also has a zoom/scroll option and that resets whenever the page is refreshed, making the experience very bad for the user.
Is there any method to display the screenshots without refreshing the page, for this particular case (where I have to query the database for each click/picture)? Maybe there is a better way of approaching this problem?
Thanks.
I think you've got 2 solutions which are Ajax or Websocket depending your needs.
AJAX
Ajax permit to asynchronously, only when you need, call the server and get datas from an URL which could be a webservice or PHP page... Perhaps, it's the better solution in your case.
To make it easy, you can use JQuery library by donwloading the script and insert it in your HTML :
<script src="jquery-3.0.0.min.js"></script>
To call the server, using JQuery :
$.ajax({
url: url + "/yourphppage.php",
data: "parameter=" + yourOptionelParameter,
async: false,
success: function(data) {
refreshYourChart(data);
},
error: function() {
alert("Your error");
},
contentType: 'charset=utf-8'
});
Or if your prefer pure javascript.
Now, you just have to work on the presentation of your data, on the server side. It could be what you want HTML, TXT, JSON, XML...
Websocket
Websocket is like a permanent tunnel opened between your server and the client. Each side can ask or send datas in real time.
It seems to be a library server side :
http://socketo.me/
And client side, it's very easy :
Nice documentation on mozilla website
Hope it helps. Good luck.
To change a picture source, as I see the easiest way is using an ajax call, so you can send any kind of parameters to your server, and in return your will get your new picture source.
$.get('urlToYourServer.com?parameter=1', function(data){
$('#img').attr('src', data.imgSrc);
})

window.location.replace strange behavior

So I'm having this issue where I lose all my data on the first window.location.replace try (The second time i reload the same page everything seems to work fine)
I have searched around and haven't found anything like this
Here is the code so I can explain my issue more toroughly:
$(document).ready(function() {
$('#login_form').on('submit', function(event){
event.preventDefault();
// Retrieve form data
var formData = {
'index' : $('input[name=user]').val(),
'password' : $('input[name=pass]').val()
};
//convert formData from JS object to PHP understandable
var formData1=jsObj2phpObj(formData);
var url= 'login.php';
//sending with post in ajax to register.php
$.post(url,{formData1:formData1})
.done(function(data){
if(!(data["Log_success"])){
alert("Log failed")
}
else
{
window.location.replace('http://localhost/CPPv2/admin_commented/index.html#home');
var draw_stringholder="";
draw_stringholder+=data["user_index"]+data["user_email"];
document.getElementById("myPanel").innerHTML=draw_stringholder;
}
}
So what my function does is that it sends data to a PHP page and recieves JSON encoded data back. The first time I submit the form I seem to recieve no network data back (I think it's because of the window.location.replace removing it) but after refreshing the page and submiting the form again everything works fine (The Index and email are written inside myPanel element).
I have tried using window.location / window.location.href ... (I think i tried every other function there is) and they just don't send me anywhere like they're not working at all. The if(!(data["Log_sccuess"])) part always works (so the client - server communication works fine).
It's also important to say that im using JqueryMobile-1.4.4 (also tried their redirect method didn't work)
To sum it up I would like to change my current page link to a other one without losing the server generated data. (Since Im bassicaly staying on the same page just changing the Id part of it). I can fix my issue by refreshing the page after I have logged in (sending server request after log in) but that doesn't seem like the right way to do it.
Instead of window.location.replace I used $.mobile.changePage( "#ulr", { transition: "slideup"} );

JQuery Send data to page using jQuery Post and data()

I'm having a bit of difficulty conceptualising this: I have some data stored to a button:
var input2 = '<button id="viewmap1" class="viewmap">Find on Map</button>';
//MAKE DATA
$(input2).data('longlat', coords);
Now I want to send that data to another page. I understand I am to use jQuery post, eg:
$.post("test.html", { func: "getNameAndTime" },
function(data){
alert("Hello");
}, "json");
But im not entirely sure how to go about it. Can any one point me in the right direction? Thanks
Sending data to a different page isn't as simple as it sounds. If it were simple, crackers could manipulate all the other pages that you currently have open in browser tabs.
When you call $.post(), that just sends data to the server, not to another page. The URL is a way to tell the server how to process the data but it doesn't magically connect you to the browser tab/window which has test.html open.
The usual solution is to use a single page which contains the button and the elements to display the results (a.k.a "view"). You send the POST request and then update the view in the callback function.
$(input2).on('click', function(){
// do your post stuffs
});
then need to trigger the button click
$(input2).click();

Categories

Resources