Mark Seah
Mark Seah

Reputation: 542

Jquery AJAX returning error 500 despite the successful execution on server side

I am encountering a problem with codeigniter and JQuery Ajax Post.

My javscript

        $('.remove').click(function(){
        var category=event.target.id;
        var id=$('input[name=article_id]').val();
        var p={};
        p['id']=id;

        $.ajax({
            type: "POST",
            url: "/backend.php/blog/removeCategories",
            async:true,
            cache:false,
            data: {id: id, category: category }
            }).done(function(msg){
                jQuery('#category_list').load('/backend.php/blog/refreshCategories/',p,function(str){});
            });

My codeigniter's controller

 function removeCategories(){
        $id=$_POST['id'];
        $category_id=$_POST['category'];

        $this->article->removeCategory($category_id,$id);
    }

I can't get the ajax function to work because there is always an error 500 received from the server. Although, firebug returns that there is an error loading the resources, the function removeCategories was executed anyways.

Upvotes: 5

Views: 7913

Answers (3)

Slipstream
Slipstream

Reputation: 14762

In Codeigniter if you have csrf_protection activated in config it will return Error 500!

To solve this you have to send the csrf value.

Example:

$.ajax({
          type: "POST",
          url: "http://example.com",
          data: {
                 '<?php echo $this->security->get_csrf_token_name(); ?>' : 
                 '<?php echo $this->security->get_csrf_hash(); ?>'
                }
       });

Upvotes: 2

NDBoost
NDBoost

Reputation: 10634

Your error could be in the model. Use chrome dev toolkit to find out what the returned page content is. HTTP CODE 500 means server error, typically due to a syntax problem within PHP somewhere.

Also, In your ajax call you should use success: and error:. This would allow you to halt execution if the code throws an error.

Why are you calling backend.php/ Are you not using index.php ??

One other way to do this is instead of using .load() you can simply pass back the html from the controller and then on success: function(data){} append it to the container. This would allow you to monitor whether the ajax call was error() or success() and act accordingly.

Upvotes: 3

marteljn
marteljn

Reputation: 6516

Make sure your data is being passed properly by making the following changes to the data option.

$.ajax({
            type: "POST",
            url: "/backend.php/blog/removeCategories",
            async:true,
            cache:false,
            data: {"id": id, "category": category }
            }).done(function(msg){
                jQuery('#category_list').load('/backend.php/blog/refreshCategories/',p,function(str){});
            });

The way you have it coded, the key of each key value pair is being set to the variable's value.

Upvotes: 6

Related Questions