user3306998
user3306998

Reputation: 15

jQuery AJAX call won't update database

I've been learning how to update databases using jQuery and AJAX so you don't need to refresh the page when you submit something, but I'm a little bit stuck.

This example is quite simple - you click the "accept" button, and in the database, the column "accepted" is updated to be '1' instead of '0'. The jQuery function appears to be working correctly, but the value isn't updating. I've tried switching from data: 'id='+id to the JSON data: { id: data } approach, as well as just using .val() instead of .serializeArray(), but nothing seems to work. Any advice?

form.php

<form id='acceptGoal' method='post'>
<input type='hidden' name='id' value='$gid'>
<input type='button' id='submit'>Accept?</button>
</form>
/* $gid is the unique identifier of each individual item to be accepted */

script.js

$('#submit').click( function() {
    var data = $("#id").val();

    $.ajax({
        type: "POST",
        url: "accept.php",
        datatype: "json",
        data: { id: data }
        });
    });

accept.php

require 'core/initialize.php';
$query=$db->prepare("UPDATE goals SET accepted=:a WHERE id=:i");
$query->bindParam(":a", $a=1);
$query->bindParam(":i", $_POST['id']);
if ($query->execute()) {
    echo "Done";
    }
else {
    echo "Something went wrong.";
    }

Upvotes: 0

Views: 782

Answers (1)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

first,you have syntax error at the end, an extra comma there:

 $.ajax({
        type: "POST",
        url: "accept.php",
        datatype: "json",
        data: { id: data }, //<--------  Here is mistake 
        });

second, your hidden field does not have id attribute with the value id:

<input type='hidden' name='id' value='$gid'> // no id attribute in it while you accessing in jquery

while you are accessing it:

var data = $("#id").val(); // this will return nothing as element with this id not exists

change it to:

<input type='hidden' id='id' name='id' value='$gid'>

you have to do like this:

$.ajax({
            type: "POST",
            url: "accept.php",
            datatype: "json",
            data: { id: data } 
            });

and you should add success and error callback to check it ajax call was successful or error occured:

$.ajax({
            type: "POST",
            url: "accept.php",
            datatype: "json",
            data: { id: data },
            success:function(response){
            alert(response);
            },
            error:function(response){
             alert("error");
            }  
            });

Upvotes: 1

Related Questions