Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax post to route in Laravel 4

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 controller@action.
is there anyway or workaround to do this?

like image 698
Pars Avatar asked Dec 20 '22 22:12

Pars


2 Answers

In your route,

Route::get('data', array('uses' => 'HomeController@store'));

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>');
    });
});
like image 109
Anshad Vattapoyil Avatar answered Dec 24 '22 02:12

Anshad Vattapoyil


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' => 'HomeController@action'));

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

like image 22
Damien Pirsy Avatar answered Dec 24 '22 00:12

Damien Pirsy