Search code examples
phpmysqlajaxsocial-media-like

Send Like/Dislike to database with ajax


I have a little problem, I need to send an ajax request to a file. Here is my HTML File (index.html)

<a id="like" href="./?act=like&id=24" title="Nobody likes this post!">Like</a> &middot; <a id="dislike" href="./?act=dislike&id=24" title="Nobody dislikes this post!">Dislike</a>

And my like.php file:

<?php
if(!is_logged()) {
    header("Location: ./?act=Home");
die();
}
$uid = $user['id'];
$id = $_GET['id'];
if(isset($id)) {
    $query = mysql_query("INSERT INTO ld (auth_id,post_id,val) 
                          VALUES ('".$uid."','".$id."','1')");
    if($query) {
    header("Location: ".$_SERVER['HTTP_REFERER']);
    } else {
    echo "Contatta l'amministratore riportando l'errore 101";
    }
} else {
header("Location: ./?act=Home");
}
?>

And my "ld" table:

== Struttura della tabella ld

|------
|Campo     |Tipo      |Null|Predefinito
|------
|//**id**//|int(5)    |No  |
|auth_id   |varchar(5)|No  |
|post_id   |varchar(5)|No  |
|val       |varchar(1)|No  |
== Dump dei dati per la tabella ld

|5|4|1|1
|6|4|1|1
|7|4|1|1
|8|4|1|1
|9|4|1|1
|10|4|1|1
|12|4|1|1
|13|4|1|1
|14|4|1|2
|20|4|15|1
|23|5|17|1
|29|4|17|1
|30|4|18|1
== Struttura della tabella ld

|------
|Campo     |Tipo      |Null|Predefinito
|------
|//**id**//|int(5)    |No  |
|auth_id   |varchar(5)|No  |
|post_id   |varchar(5)|No  |
|val       |varchar(1)|No  |

I really don't know how to send an ajax request, and I have also tried to learn ajax but no way, I can't understand it.


Solution

  • You should use jquery, it's actually very simple with it. First include this in your HTML file:

    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
    

    Then add this, it is called a "listner" and it pays attention in this case to when your link is clicked:

    // A # is used since we are using an id to get the element
    // A . is used for a class, but we are using the id at the moment
    $('#like').click(function(e) { // We assign a click listner with a handler (a function)
      e.preventDefault(); // run this to stop it from going to a new page automatically
      $.get('./', {'act' : 'like', 'id' : $(this).attr('data')}, function(e) {
        // Handle success here
      }, 'json'); // expecting a json object back by using echo json_encode(array(...)) in PHP
    });
    

    With my example you will need to change the html to this:

    <a id="like" href="" data="24" title="Nobody likes this post!">Like</a>
    

    And then you could do the same thing with dislike. The {} as the second parameter i did in the $.get is a javascript array as a fyi. Here is the $.get method i used in jquery's documentation: http://api.jquery.com/jQuery.get/

    For information on what ajax is and how it works check out this article: http://www.webdesignerdepot.com/2008/11/how-ajax-works/

    Feel free to ask for any clarifications