TriMinh
TriMinh

Reputation: 59

Jquery ajax not working (Laravel 4)

I use jquery ajax to add data to database. When i click submit button, my page return blank. I use firebug to debug and see message: 500 (Internal Server Error).

routes.php

Route::controller('subscribers', 'SubscribersController');

SubscribersController.php

class SubscribersController extends \BaseController {

//The method to show the form to add a new feed
public function getIndex() {
    //We load a view directly and return it to be served
    return View::make('subscribe_form');
}

//This method is to process the form
public function postSubmit() {

    //We check if it's really an AJAX request
    if(Request::ajax()) {
        $validation = Validator::make(Input::all(), array(
        //email field should be required, should be in an email
        //format, and should be unique
        'email' => 'required|email|unique:subscribers, email'));

        if($validation->fails()) {
            return $validation->errors()->first();
        } else {
            $create = Subscribers::create(array(
                'email' => Input::get('email')
            ));
            //If successful, we will be returning the '1' so the form
            //understands it's successful or if we encountered an unsuccessful creation attempt, 
            //return its info
            return $create?'1':'We could not save your address to our system, please try again later';
        }
    } else {
        return Redirect::to('subscribers');
    }
}

}

view file:

{{--Form Starts Here --}}
{{Form::open(array('url' => URL::to('subscribers/submit'), 'method' => 'post'))}}
<p>Simple Newsletter Subscription</p>
{{Form::text('email', null, array('placeholder'=>'Type your E-mail address here'))}}
{{Form::submit('Submit!')}}

{{Form::close()}}
{{--Form Ends Here --}}

{{--This div will show the ajax response --}}
<div class="content"></div>
{{-- Because it'll be sent over Ajax, we add the jQuery source --}}
{{HTML::script('http://code.jquery.com/jquery-1.11.0.min.js') }}
<script type="text/javascript">
//Even though it's on footer, I just like to make
//sure that DOM is ready
$(function() {
    //We hide de the result div on start
    $('div.content').hide();
    //This part is more jQuery related. In short, we make an Ajax post request and get
    //the response back from server
    $('input[type="submit"]').click(function(e) {

        e.preventDefault();

        $.post('http://localhost/laravel-blueprint/newsletter/public/subscribers/submit', {email: $('input[name="email"]').val()
            }, function($data) {
                if($data == '1') {
                    $('div.content')
                        .hide()
                        .removeClass('success error')
                        .addClass('success')
                        .html('You\'ve successfully subscribed to our newsletter')
                        .fadeIn('fast');

                } else {
                    //This part echos our form validation errors
                    $('div.content')
                        .hide().removeClass('success error')
                        .addClass('error')
                        .html('There has been an error occurred: <br /><br />'+$data)
                        .fadeIn('fast');
                }
            });
    });
    //We prevented to submit by pressing enter or any other way
    $('form').submit(function(e) {
        e.preventDefault();
        $('input[type="submit"]').click();
    });
    });
</script>

i use laravel 4 log-access:

127.0.0.1 - - [11/Mar/2014:17:54:41 +0700] "POST /laravel-blueprint/newsletter/public/subscribers/submit HTTP/1.1" 500 381

Any solution?

Upvotes: 1

Views: 497

Answers (2)

tliokos
tliokos

Reputation: 3636

In order for your code to work, do the following changes:

SUBSCRIBERS CONTROLLER

class SubscribersController extends \BaseController {

    public function getIndex() {

        return View::make('subscribe_form');
    }

    public function postSubmit() {

        if(Request::ajax()) {

            $validation = Validator::make(Input::all(), 

            ['email' => 'required|email|unique:subscribers,email']);

            if($validation->fails()) {

                return  $validation->errors()->first();

            } else {

                // Note here that the model is Subscriber and not Subscribers

                // This is the default convention for the subscribers table

                $create = Subscriber::create(array(

                  'email' => Input::get('email')

                ));

                return $create ? '1' : 'We could not save your address';
            }
        } else {

            return Redirect::to('subscribers');
        }
    }
}

IMPORTANT FOR SUBSCRIBER MODEL

class Subscriber extends Eloquent {

    // I don't know if you have timestamps enabled, but if not this is necessary

    public $timestamps = false; 

    // Must be present for mass assignment to work (Subscriber::create)

    protected $fillable = array('email');
}

Upvotes: 1

Swaraj Giri
Swaraj Giri

Reputation: 4037

Comment

500 (Internal Server Error) might be caused due to a PHP fatal.

Do you have error_reporting on? If not, try

error_reporting(E_ALL); ini_set('display_errors', 1);

and check.

Upvotes: 0

Related Questions