19

I have a button which calls a modal box to fade into the screen saying a value posted from the button then fade off, this works fine using jquery, but I also want on the same click for value sent from the button to be posted to a php function, that to run and the modal box to still fade in and out.

I only have this to let my site know what js to use:

 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>

I'm still new so sorry for a rookie question, but will that allow ajax to run, or is it only for jquery?

The current script I'm trying is: (Edited to be correctly formed, based on replies, but now nothing happens at all)

<script>
$('button').click(function() 
{

    var book_id = $(this).parent().data('id'),
    result = "Book #" + book_id + " has been reserved.";

    $.ajax
    ({ 
        url: 'reservebook.php',
        data: "book_id="+book_id,
        type: 'post',
        success: function()
        {
            $('.modal-box').text(result).fadeIn(700, function() 
            {
                setTimeout(function() 
                {
                    $('.modal-box').fadeOut();
                }, 2000);
            });
        }
    });
});
</script>

Though with this the modal box doesn't even happen.

The php is, resersebook.php:

<?php

session_start();

$conn = mysql_connect('localhost', 'root', '');
        mysql_select_db('library', $conn);

    if(isset($_POST['jqbookID']))
    {
        $bookID = $_POST['jqbookID'];

        mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
    }

?>

and to be thorough, the button is:

<div class= "obutton feature2" data-id="<?php echo $bookID;?>"><button>Reserve Book</button></div>

I'm new to this and I've looked at dozens of other similar questions on here, which is how I got my current script, but it just doesn't work.

Not sure if it matters, but the script with just the modal box that works has to be at the bottom of the html body to work, not sure if for some reason ajax needs to be at the top, but then the modal box wouldn't work, just a thought.

Vereonix
  • 1,341
  • 5
  • 27
  • 54
  • **Danger**: You are using [an **obsolete** database API](http://stackoverflow.com/q/12859942/19068) and should use a [modern replacement](http://php.net/manual/en/mysqlinfo.api.choosing.php). You are also **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that a modern API would make it easier to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Dec 12 '13 at 12:47
  • ah thank you, I keep being told this, and I keep meaning to read up on it and migrate over. – Vereonix Dec 12 '13 at 12:57
  • Are you serious not using `mysql_real_escape_string()`, `htmlspecialchars()` and `filter_input()`?! SQL Injection is only one problem. `` causes XSS as well. – mgutt Mar 15 '15 at 23:17

4 Answers4

19

Try this. Edited to the final answer.

button:

<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
    <button class="reserve-button">Reserve Book</button>
</div>

script:

<script>
$('.reserve-button').click(function(){

    var book_id = $(this).parent().data('id');

    $.ajax
    ({ 
        url: 'reservebook.php',
        data: {"bookID": book_id},
        type: 'post',
        success: function(result)
        {
            $('.modal-box').text(result).fadeIn(700, function() 
            {
                setTimeout(function() 
                {
                    $('.modal-box').fadeOut();
                }, 2000);
            });
        }
    });
});
</script>

reservebook.php:

<?php
session_start();

$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);

if(isset($_POST['bookID']))
{
    $bookID = $_POST['bookID'];

    $result = mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);

    if ($result)
        echo "Book #" + $bookId + " has been reserved.";
    else
        echo "An error message!";
}
?>

PS#1: The change to mysqli is minimal to your code, but strongly recommended.

PS#2: The success on Ajax call doesn't mean the query was successful. Only means that the Ajax transaction went correctly and got a satisfatory response. That means, it sent to the url the correct data, but not always the url did the correct thing.

Minoru
  • 1,680
  • 3
  • 20
  • 44
  • Still nothing, happens at all. This is my first time using ajax, and its not going well. I understand all the code but it just doesn't work. The fact the modal works on its own, but with the introduction of the ajax it doesn't, is there anything that could simply stop ajax from running? Also not sure my eyes are playing up but is there a missing close bracket on your script? well I closed in case, still nothing :/ – Vereonix Dec 12 '13 at 13:10
  • @Tom Does it insert anything in the database? Or it simply doesn't do anything? – Minoru Dec 12 '13 at 13:12
  • @Tom Try again with the edited code. Just change the `data` field on the Ajax call. – Minoru Dec 12 '13 at 13:14
  • Simply nothing, even though the modal doesn't come up every time I still check the db, and it hasn't had anything inserted, I can't tell if the php just isn't running, or the ajax isn't. – Vereonix Dec 12 '13 at 13:15
  • @Tom Put an `alert(result)` on the begining of the `success` part. If something is returned an the problem is only the modal, this should show something. – Minoru Dec 12 '13 at 13:17
  • @Tom Anything new? If nothing worked, the only thing I have in mind is if the `reserbook.php` is in the same directory as the `php file` that use the script. – Minoru Dec 12 '13 at 13:25
  • So "success: alert(result), function(result)"? Nothing happens still, is there something really basic I can do just to see if anything ajax works for me? – Vereonix Dec 12 '13 at 13:28
  • 1
    let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/43045/discussion-between-lucas-harada-and-tom) – Minoru Dec 12 '13 at 13:30
  • Well reservebook.php is in the same folder as books.php which is the file where the script is being run, if thats what you mean, I'm doing this via xampp as well if that could cause any issues. – Vereonix Dec 12 '13 at 13:30
  • Are you serious not using `mysql_real_escape_string()`, `htmlspecialchars()` and `filter_input()`?! – mgutt Mar 15 '15 at 23:12
1

You Ajax is bad formed, you need the sucsses event. With that when you invoke the ajax and it's success it will show the response.

$.ajax
        ({ 
            url: 'reserbook.php',
            data: {"book_id":book_id},
            type: 'post',
            success: function(data) {
                $('.modal-box').text(result).fadeIn(700, function() 
                {
                   setTimeout(function() 
                    {
                    $('.modal-box').fadeOut();
                    }, 2000);
                });
              }
             }

Edit:

Another important point is data: "book_id="+book_id, that should be data: {"book_id":book_id},

Wilfredo P
  • 4,070
  • 28
  • 46
  • `,` missing after `type: 'post'`. – dbf Dec 12 '13 at 12:44
  • I've changed my ajax to this, but now nothing happens, I've updated my posted to show my full script, probably messed it up. Thought though, and you might face palm, in my reservebook.php do I need to have: or will it be able to get the variable regardless, also that script will allow this ajax to work right, its not just for jquery? :S – Vereonix Dec 12 '13 at 12:50
  • @Tom if you copied and pasted I update the answer becouse I was missing a `,` but the Jquery library Is not the problem. – Wilfredo P Dec 12 '13 at 13:05
1

You have an error in your ajax definitions. It should be:

$.ajax
({ 
    url: 'reserbook.php',
    data: "book_id="+book_id,
    type: 'post',
    success: function()
    {
        $('.modal-box').text(result).fadeIn(700, function() 
        {
            setTimeout(function() 
            {
                $('.modal-box').fadeOut();
            }, 2000);
        });
    }
});
floriangosse
  • 1,124
  • 1
  • 8
  • 19
0
$.ajax
({ 
    url: 'reservebook.php',
    data: {
    jqbookID : book_id,
    },
    type: 'post',
    success: function()
    {
        $('.modal-box').text(result).fadeIn(700, function() 
        {
            setTimeout(function() 
            {
                $('.modal-box').fadeOut();
            }, 2000);
        });
    }
});

});

Try this

Abhisek Mishra
  • 269
  • 3
  • 15