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?
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>');
});
});
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With