4

I have a subscribe box :

enter image description here

My goal is when the user enter the email, I want to save it to my database.

I already know how to achieve this using form post via Laravel.


Form POST via Laravel

public function postSubscribe() {

    // Validation
    $validator = Validator::make( Input::only('subscribe_email'),

        array(

            'subscribe_email'  => 'email|unique:subscribes,email',
            )
        );

    if ($validator->fails()) {

        return Redirect::to('/#footer')
        ->with('subscribe_error','This email is already subscribed to us.')
        ->withErrors($validator)->withInput();

    }else{

        $subscribe        = new Subscribe;
        $subscribe->email = Input::get('subscribe_email');
        $subscribe->save();

        return Redirect::to('/thank-you');

    }

}

Now, I want to achieve this using Ajax call to avoid the page load and also to learn more about Ajax. Here are what I've tried :


Form

{!! Form::open(array('url' => '/subscribe', 'class' => 'subscribe-form', 'role' =>'form')) !!}

<div class="form-group col-lg-7 col-md-8 col-sm-8 col-lg-offset-1">
  <label class="sr-only" for="mce-EMAIL">Email address</label>
  <input type="email" name="subscribe_email" class="form-control" id="mce-EMAIL" placeholder="Enter email" required>

  <!-- real people should not fill this in and expect good things - do not remove this or risk form bot signups-->
  <div style="position: absolute; left: -5000px;"><input type="text" name="b_168a366a98d3248fbc35c0b67_73d49e0d23" value=""></div>
</div>
<div class="form-group col-lg-3 col-md-4 col-sm-4"><input type="submit" value="Subscribe" name="subscribe" id="subscribe" class="btn btn-primary btn-block"></div>


{!! Form::close() !!}

Ajax Call

<script type="text/javascript">
  $(document).ready(function(){
    $('#subscribe').click(function(){
      $.ajax({
        url: '/subscribe',
        type: "post",
        data: {'subscribe_email':$('input[name=subscribe_email]').val(), '_token': $('input[name=_token]').val()},
        dataType: 'JSON',
        success: function (data) {
          console.log(data);

        });
    });
  });
</script>

Controller

public function postSubscribeAjax() {

        // Getting all post data

        if(Request::ajax()) {
            $data = Input::all();
            die;
        }

        dd($data);
    }

Route

Route::post('/subscribe','SubscribeController@postSubscribeAjax');


Result

I keep getting:

Undefined variable: data

Which mean my Request::ajax() is not containing anything? Why is that?

How can I achieve this using an Ajax call?

2 Answers 2

2

This was resolved in Chat

We had to fix a couple syntax errors and change the input button to a html button so that it would prevent the form from submitting. There are other ways we could have done this, but this worked.


So I'm going to address a few things here. Starting from bottom moving on up!!

Route

You can do this without the slash. Route::post('subscribe','SubscribeController@postSubscribeAjax');

Controller

Your Controller is good enough, but you need to actually display the result from the ajax. We will handle that.

Remove the die in your check if there is an Ajax request.

Ajax

<script type="text/javascript">
  $(document).ready(function(){
    $('#subscribe').click(function(e){
         e.preventDefault(); // this prevents the form from submitting
      $.ajax({
        url: '/subscribe',
        type: "post",
        data: {'subscribe_email':$('input[name=subscribe_email]').val(), '_token': $('input[name=_token]').val()},
        dataType: 'JSON',
        success: function (data) {
          console.log(data); // this is good
        }
      });
    });
  });
</script>

Form

Pretty sure the form is good.

Sign up to request clarification or add additional context in comments.

10 Comments

Oh my god, you're awesome. Thanks for sharing your knowledge. :D
In my controller, I tried dd(Request::ajax()); I got false, Am I suppose to see true or false ?
I'm not sure what should I do now,$data = Input::all(); never get run.
you should see true when it is an ajax request. So we need to double check something here... Did the page submit using ajax or did it show you a console??
what do you get with Request::all() ??
|
1

Assuming the "Undefined variable" error is happening in your postSubscribeAjax method, it looks like you have a problem with scope. Specifically, when the PHP interpreter gets to the line dd($data), the variable $data has not been defined yet.

This is not surprising, since $data is assigned inside the block of code following an if statement - it is not available outside that block.

You can solve this problem by adding $data = null; before the if statement, BUT... this is only going to show you that you have a different problem. Here's why:

You're getting an "undefined variable" error. The means that your code is skipping the if block (how do I know this? because if it didn't skip it, it would execute the die statement and you'd never see the error). This means that your code is not correctly identifying the request as an AJAX request.

What I would do is this: skip the if block entirely. Simply get your data and process it.

It's been a while since I looked at this stuff, but IIRC, there is no reliable way to detect AJAX requests. To the server, an AJAX request is just like any other request. Some Javascript libraries (jQuery included, if I'm not mistaken) set a header on the request to identify it as AJAX, but it is neither universally required nor universally detected.

The only benefit to this AJAX detection is to prevent your users from accessing the AJAX URL directly from a browser. And, ultimately, if someone really wants to do that, you can't stop them since they can (with a little work) spoof any request.

1 Comment

Should still be a part of 5, but see documentation for ajax on 4

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.