Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery AJAX post to update database

Tags:

jquery

ajax

php

I'm using the following code in my HTML form - trying to make a sort of "lottery scratch ticket" type effect. There's a grid, each item with a dynamic number from a database. Clicking the square calls the clickme() function, makes the db call, and then changes the image. I'm just on the first part trying to get the database to update.

My PHP/HTML:

    if ($unlock == 0) { 
    echo '<div> class="' . $currentgrid .'" name="' . $slot . '"   
    onclick="clickme();" style="cursor: pointer;">'; 
    } else { echo '<div>'; }

And my javascript.js file:

function clickme()
{
// $(function() {
//    $(".gridsquare").click(function() {

    var slotnumber = $(this).attr('name');
    // var gridnumber = $(this).attr('class');
    var dataString = 'slot='+ slotnumber;
    // + '&gridnumber=' + gridnumber;

        $.ajax({
            type: "POST",
            url: "post/supergridupdate.php",
            data: dataString,
            success: function(){
                // $('.success').fadeIn(200).show();
                // $('.error').fadeout(400).hide;
            }
        });

    return false;
//    });
// });

}

supergridupdate.php:

    <?php 
     $slot = $_POST['slot']; 
     // $gridnumber = $_POST['gridnumber']; 
     $gridnumber = 1;
     $sql = "INSERT INTO test (slot, gridnumber) VALUES ('$slot', '$gridnumber')";
     $result = mysql_query($sql) or die(mysql_error()); 
     ?> 

Right now it all displays, I can click divs but the database doesn't update.

UPDATE: Got it to work with help, just simply passing the variable in the javascript function now instead of using jquery.

like image 476
916 Networks Avatar asked Dec 31 '25 20:12

916 Networks


1 Answers

Are you certain that 'slotnumber' has a value? Also have you tried sending an object rather than a string? var dataString = {'slot': slotnumber}; --EDIT in your function try to pass the element to the function onclick="clickme(this);"

function clickme(el)
{
// $(function() {
//    $(".gridsquare").click(function() {

    var slotnumber = $(el).attr('name');
    // var gridnumber = $(this).attr('class');
like image 166
scrappedcola Avatar answered Jan 02 '26 11:01

scrappedcola