-1

I have the following script:

$(function (){
            $('.press_me').click(function(){
            var request = $.ajax({
                                    type: "POST",
                                    url: "counter.php"

                                  });
                                  request.done(function( msg ) {

                                        alert('Success');
                                        return;

                                  });
                                  request.fail(function(jqXHR, textStatus) {
                                        alert( "Request failed: " + textStatus );
                                    });
            });
    }); 

and counter.php:

<?php
// Connection to database
  $connection=mysqli_connect("host","user","pass","db");
// Check connection
  if (mysqli_connect_errno())
    {
    echo 'NOT_OK';
    //echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }

// Increasing the current value with 1
 mysqli_query($connection,"UPDATE table SET amount = (amount + 1) WHERE ID='1'  ");

  mysqli_close($connection);

  echo 'OK';   ?>

1.In order to see the updated value, I have to refesh the page, which i believe it means that the ajax is not working asynchornously, and that's what i would want.i tried everything with the async parameter but i failed.

2.What update clause should i use so as to update each row separately, as the code in this state updates only one row or if i omit the where clause, it updates all of them. Can anyone help me?

Alex Resiga
  • 71
  • 1
  • 11
  • 2
    You need to update the DOM on the AJAX success event. AJAX sends data to the server that otherwise would require a page reload. To update the correct record pass the ID with the request. – chris85 Jan 22 '16 at 20:23
  • i'm a beginner so could please explain what that means? – Alex Resiga Jan 22 '16 at 20:24
  • 2
    After `mysqli_query($connection,"UPDATE table SET amount = (amount + 1) WHERE ID='1' ");` Do a select and return the new amount (or you could assume that it just increases by 1 and add 1 in JS, if two people increase at the same time though this will be incorrect) then update your HTML with the JS so the new amount is displayed. This thread shows on way of updating with the success event, http://stackoverflow.com/questions/18064666/update-div-with-jquery-ajax-response-html. – chris85 Jan 22 '16 at 20:26
  • If you just follow what @chris85 is telling you and do the homework yourself, you will be learning better an important part of the web dev – Adib Aroui Jan 22 '16 at 20:27
  • thanks i will give it a try and i hope that i ll get it rhight – Alex Resiga Jan 22 '16 at 20:31

1 Answers1

0

To answer your 2 questions:

  1. You're not telling the page what to do with the result once the AJAX request has been completed. All you're doing is an alert that says "Success". If you want the page to update with the new number of amount from your database, your php script has to give this new amount back to the AJAX function. See javascript part below, where it says "Here comes the part where you actually update...". In this part, you will have to put something that actually updates the HTML (DOM) of the web page without the user refreshing the webpage. This can easily be done with javascript. See below.

  2. I'm not sure what you mean. Right now you are increasing the amount in table by 1 where ID='1', so only the amount of the row with ID = 1 will increase by 1. I'm assuming you have multiple buttons with class='press_me'. If that is the case, you'll have to give all these buttons a differnt ID, and then pass that ID along to the AJAX post call.

So your button would be:

<button class="press_me" id="ID HERE">Click me</button>

And your javascript would be:

$('press_me').click(function(){ 
    var button_ID= $(this).attr("id");

    $.post('counter.php', {button_ID: button_ID}, function(result){

        // the var 'result' is the new count of this button, 
        as generated by the PHP page below. Do with this var whatever 
        you want. If you want to show the new amount of this counter 
        in a div for example, you can do:

        $('.counter_div').html('New count: ' + result);

    });
});

And your PHP:

<?php
$connection=mysqli_connect("host","user","pass","db");

mysqli_query($connection,"UPDATE table SET amount = (amount + 1) WHERE ID='" . $_POST["button_ID"] . "'");

//Get the new count for this button, and echo it, so it can 
be picked up by the AJAX call return:

$get_count= mysqli_query("SELECT * FROM `table` WHERE `ID`='" . $_POST["button_ID"] . "'");
$count_data= mysqli_fetch_array($new_count_data);
echo($count_data["amount"]);

mysqli_close($connection);
?>
Laurens Swart
  • 1,234
  • 9
  • 24
  • thanks but there's one thing: the buttons are actually some pictures which are echo-ed into a table so i don't think i can give them separate ids.. but each value that i want to increase comes from a table with multiple people which have ID there as primary key.can i use that ID somehow? – Alex Resiga Jan 22 '16 at 20:35
  • @chris85 i'm not dealing with sensitive information.. it's pretty public what i'm trying to do – Alex Resiga Jan 22 '16 at 20:38
  • Chill your horses @chris85, I'm just trying to make an example for him that is easy to understand. Of course you need to use mysql_real_escape_string or a mysqli equivalent, or any other way of the many many ways to prevent SQL injection. – Laurens Swart Jan 22 '16 at 20:39
  • Yes @AlexResiga, you can use any ID you want. I would have to see your entire table / website structure to give you a working piece of code, but for example you could select the ID of the table row that the button is in, by doing something like `$(this).parent('tr').attr('id');` – Laurens Swart Jan 22 '16 at 20:41
  • and also i think this is dumb but still.. i include the ajax request above that $.post('counter.php....) ? – Alex Resiga Jan 22 '16 at 20:42
  • @LaurensSwart is there anyway we could get to chat about my problem? of course if you don't mind wasting time on my noob problems – Alex Resiga Jan 22 '16 at 20:45
  • 1
    @LaurensSwart No, `mysql_real_escape_string` won't work with `mysqli` and prepared statements are what new users should be using/learning. – chris85 Jan 22 '16 at 21:04