Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

$.post() giving bad url string

I made a site that shows dynamically created HTML using ajax with jQuery.

On one part it shows diferent entries from a database table, and on each row there's a button to delete that specific entry from the database. This is the code that should make that happen:

$('body').on('click', '.deleteWaitlist', function(){
        console.log("Clicked on .deleteWaitlist name = " + $(this).attr('name'));

        // Get the varible name to send to your php
        var i = $(this).attr('name');
        console.log( "$(this).attr('name') = i" );

        $.post({
            url: "deleteWaitlist.php", 
            data: { id : i}, 
            success: function(result){
                console.log("Ajax success " + result);
            }, 
            //dataType: "html"
        });
        return false;
    });

However, when I click the button I get the error

POST localhost:8888/workplace/site/[object%20Object] 404 (Not Found)

Correct me if I'm wrong, but [object%20Object] is what we get from an undefined toSting() method right? I tried specifing diferent kinds of dataTypes but made no diference.

I can't seem to find the problem, can dataType be something besides xml, json, script or html? This function don't return anything so dataType is not even needed isn't it?

This is deleteWaitlist.php:

<?php
    include("con.php");    
    $sql = "DELETE FROM waitlist WHERE id=" . $_POST[id] . "";
    mysqli_query($c,$sql);
?>

EDIT: To clarify, the mentioned error shows only on the console, since I want an async site most buttons prevent navigation. On the actual page clicking the button has no effect. Also, this is the code that creates the buttons:

while ($places = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>". $places ['ID']."</td>";
    echo "<td>". $places ['NAME']."</td>";
    echo "<td>". $places ['CHAIRS']."</td>";
    echo "<td>". $places ['CREATED']."</td>";
    echo '<td>
        <button class="btn btn-default deleteWaitlist" type="submit" name="' . $places['ID'] . '">X</button>
        </td>';
    echo "</tr>";
}
like image 738
TianRB Avatar asked Jul 27 '15 23:07

TianRB


1 Answers

$.post expects the first param an URL string If you want to pass an object with other options, you must use $.ajax.

Try

$.ajax({
            type: "POST",
            url: "deleteWaitlist.php", 
            data: { id : i}, 
            success: function(result){
                console.log("Ajax success " + result);
            }
        });

Correct me if I'm wrong, but [object%20Object] is what we get from an undefined toSting() method right?

You are right. When you use $.post with first parameter as object jQuery thinks it as post url and does toString() to that parameter. In your case its like object.toString() which throws the error [object%20Object]

like image 109
kiranvj Avatar answered Oct 23 '22 03:10

kiranvj