Home » Php » Ajax post to route in Laravel 4

Ajax post to route in Laravel 4

Posted by: admin November 30, 2017 Leave a comment

Questions:

I am going to send some data to current page using ajax to insert something in database.
Assume this ajax code:

$('#newPost :submit').click(function(e){
            var BASE = 'http://localhost/project/public/';
    e.preventDefault();
    $.post(BASE, {
        'message' : $('#newPost textarea.message').val()
        }, function(data) {
        $('#content').prepend('<p>' + data + '</p>');
    });
});

This piece of code sends data to URL / and it works well. but I want to send it to a Route.Name which route sends it to a [email protected]
is there anyway or workaround to do this?

Answers:

In your route,

Route::get('data', array('uses' => '[email protected]'));

In HomeController,

public function store() {
  $input = Input::all(); // form data
  // validation rules
  $rules = array(
    'email'   => 'required|email', 
    'name'    => 'required', 
  ); 

  $validator = Validator::make($input, $rules); // validate
  // error handling
  if($validator->fails()) {
    if(Request::ajax()) {   // it's an ajax request                 
      $response = array(
         'response'  =>  'error',
         'errors'    =>  $validator->errors()->toArray()
      );                
    } else { // it's an http request
       return Redirect::intended('data')
                  ->withInput()
                  ->withErrors($validator);
    }
  } else { // validated
     // save data
  }
}

And finally the script,

var root_url = "<?php echo Request::root(); ?>/"; // put this in php file
$('#newPost :submit').click(function(e){
    var BASE = root_url + 'data';
    e.preventDefault();
    $.post(BASE, {
        'message' : $('#newPost textarea.message').val()
        }, function(data) {
        $('#content').prepend('<p>' + data + '</p>');
    });
});

Questions:
Answers:

You could change

var BASE = 'http://localhost/project/public/';

to

var BASE = '<php echo URL::route("name");?>'

Your route should then be:

Route::post('action', array('as' => 'name', 'uses' => '[email protected]'));

Note the use of the named routes instead of building the url using URL::to('controller/action')