willium
willium

Reputation: 2128

Posting not working via JS (Jquery) but is with form

I have a rather confusing problem.

I have a php file (http://example.com/delete.php)

<?php
session_start(); 
$user_id = $_SESSION['user_id'];
$logged_in_user = $_SESSION['username'];
require_once('../classes/config.php');
require_once('../classes/post.php');
$post = new Post(NULL,$_POST['short']);
#print_r($post);
try {
 if ($post->user_id == $user_id) {
  $pdo = new PDOConfig();     

   $sql = "DELETE FROM posts WHERE id=:id";

   $q = $pdo->prepare($sql);
   $q->execute(array(':id'=>$post->id));       

  $pdo = NULL;
 }
 else {throw new Exception('false');}
}       
catch (Exception $e) {
   echo 'false';
}
?>

and I'm trying to get this jquery to post data to it, and thus delete the data.

$('.post_delete').bind('click', function(event) {

    var num = $(this).data('short');

    var conf = confirm("Delete This post? (" + num + ")");

    if (conf == true) {
        var invalid = false;
        $.post("http://example.com/delete.php", {short: num},
        function(data){

            if (data == 'false') {
                alert('Deleting Failed!');
                invalid = true;
            }
        });

        if (invalid == false) { 
          alert("post Has Been Deleted!");
        } 
        else {
            event.preventDefault();
            return false;
        }


    } 
    else {
        event.preventDefault();
        return false;
    }



});

and when I do that, it returns "Post Has Been Deleted!" but does not delete the post.

Confused by that, I made a form to test the php.

<form action="http://example.com/delete.php" method="POST">
<input type="hidden" value="8" name="short"/>
<input type="submit" name="submit" value="submit"/>
</form>

which works beautifully. Very odd.

I have code almost identical for deleting of a comment, and that works great in the javascript.

Any ideas? Beats me.

Thanks in advance, Will

EDIT: this works... but doesn't follow the href at the end, which is the desired effect. Odd.

$('.post_delete').bind('click', function(event) {

    var num = $(this).data('short');

    var conf = confirm("Delete This Post? (http://lala.in/" + num + ")");

    if (conf == true) {
        var invalid = false;
        $.post("http://example.com/delete/post.php", {short: num},
        function(data){

            if (data == 'false') {
                alert('Deleting Failed!');
                invalid = true;
            }
        });

        if (invalid == false) { 
          alert("Post Has Been Deleted!");
        ******************************************
            event.preventDefault();
            return false;
        ******************************************
        } 
        else {
            event.preventDefault();
            return false;
        }


    } 
    else {
        event.preventDefault();
        return false;
    }



   });

Upvotes: 0

Views: 205

Answers (2)

Shikiryu
Shikiryu

Reputation: 10219

If your PHP script delete the post, it doesn't return anything.


My bad, it's not answering the real question, but still is a mistake ;)

Actually, it seems that PHP session and AJAX doesn't quite work well together sometimes.

It means that if ($post->user_id == $user_id) will never validate, hence the non-deleting problem.

2 ways to see this :

  1. Log $user_id and see if it's not null
  2. Try to send the $_SESSION['user_id'] with your ajax post and check with it. But not in production, for security reason.

1-

Your PHP should return something in every case (at least, when you're looking for a bug like your actual case).

<?php
[...]
try {
 if ($post->user_id == $user_id) {
  [...]
  echo 'true';
 }
 else {throw new Exception('false');}
}       
catch (Exception $e) {
   echo 'false';
}
?>

2-

jQuery is nice to use for AJAX for many reasons. For example, it handles many browsers and make checks for you but moreover, you can handle success and error in the same .ajax() / .post() / .get() function \o/

$('.post_delete').bind('click', function(event) {
    var num = $(this).data('short'); // If that's where your data is... Fair enough.
    if (confirm("Delete This Post? (http://lala.in/" + num + ")")) {
        $.post("delete/post.php", {short: num}, // Relative is nice :D
        function(data){
            if (data == 'false') {
                alert('Deleting Failed!');
             }else{
                alert("Post Has Been Deleted!");
                // Your redirection here ?
            }
        });
     }
});

3-

If you need to send data from a form to a script and then do a redirection, I won't recommand AJAX which is usually use not to leave the page ! Therefore, you should do what's in your comment, a form to a PHP script that will apparently delete something and then do a redirection.

Upvotes: 1

Nick Craver
Nick Craver

Reputation: 630559

In your code I don't see num defined anywhere...and invalid isn't set when you think it is, so you're not passing that 8 value back and you're getting the wrong message, either you need this:

$.post("http://example.com/delete.php", {short: $("input[name=short]").val()},

Or easier, just .serialize() the <form>, which works for any future input type elements as well:

$.post("http://example.com/delete.php", $("form").serialize(),

I'm not sure where your code is being called, if for example it was the <form> .submit() handler, it'd look like this:

$("form").submit(function() {
  $.post("http://example.com/delete.php", $(this).serialize(), function(data){
    if (data == 'false') {
      alert('Deleting Failed!');
    } else {
      alert("Post Has Been Deleted!");
    }
});

Note that you need to check inside the callback, since invalid won't be set to true until the server comes back with data the way you currently have it, because it's an asynchronous call.

Upvotes: 0

Related Questions