I'm trying to pass data to my laravel controller function via Ajax. At this point I just want to return the data being sent to verify ajax is working. I can "GET" with ajax, but when I try to "POST" ajax brakes.
Could someone please tell me what I'm doing wrong? Thank you.
Here is my ajax code...
var startMapLocation = { startCity: "Cleveland", startStat: "Oh" };
$.ajax({
type: "POST",
url: url,
data: startMapLocation,
success: function(data, status) {
//alert(data);
console.log("success:", data);
},
error: function() {
alert("Ajax Broke!" + status);
}
});
My laravel function is...
public function postphp( Request $request)
{
$a = $request->all();
$city = $a["startCity"];
return json_encode( $city );
}
Thanks every one for your help. To resolve this issue, I first had to verify that my route was a post route not a get route.
Route::post('/postphp', 'GSResultController#postphp');
I also need to get my csrf-token and add it to the ajax call.
headers: {
"X-CSRF-TOKEN": $('meta[name="csrf-token"]').attr("content")
},
This fixed my problem.
In my blade I use an ajax call to call a route. In my controller I am returning a different view. However, the view does not change. I am wondering if I need to change the view differently because I am using an ajax call that needs a return of success or not.
Here is my ajax code in my blade:
$('#btnAnalyze').click(function(){
var text = $('#cv').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: "/widget/measurableresults",
data: {
text: text,
},
success: function (msg) {
console.log("Success");
},
error: function (msg) {
console.log(msg);
}
});
});
Here is my route
Route::post('/widget/measurableresults', 'WidgetController#measurableresults');
Here the method in my controller:
public function measurableresults()
{
$text = Input::get('text');
Log::debug( $text );
return view('results.measurableresults');
}
The Log::debug prints out the value of $text and the ajax call returns success. However, the view does not change to results.measurableresults. What am I missing?
Try and remove the line Log::debug( $text );, it's probably blocking the return statement to execute
update
You seem not to understand how things work in ajax and php communication, the success code you're receiving doesn't mean ajax returned the expected value, if you log the ajax response, you'll get the html text in the view you're returning, it's not that ajax will magically change the view for you.
Please make more research in regards to this.
I have a route like this --
Route::put('avote', 'voteController#avote')->middleware('auth');
I want to access this route from a ajax send request.
When i use this code --
$data = {/* some data here */};
$.post("/avote", $data, function(result) {
$('#avote h2').html(result);
$('#avote a span').css('color', 'orange');
$('#avote a span').unwrap();
});
I get an error method not allowed. I know that it is the problem of method I used (used post not put)
I question is, is there any way i can get the information from /avote using ajax or any other scripts?
Please dont suggest me to change the route request from put to post or Any other way to protect the /avote route
I used Route::put() beacuse i have a database update function in the route controller
Move to $.ajax() function instead of $.post and provide method (type) property:
$.ajax({
url: "/avote",
data: $data,
method: "PUT",
// or type: "PUT", if your jquery version is prior to 1.9
success: function(result) {
$('#avote h2').html(result);
$('#avote a span').css('color', 'orange');
$('#avote a span').unwrap();
}
});
I am fairly new in the Ajax's world, tho I've tried it maybe twice and it always worked like a charm. Now I am trying to send variable with ajax() method but it seems like I have 0 errors in my console but I think the problem is that I am sending no variable at all.. If, in my php file, I echo a string it's working. So my problem is that I can't echo out the variable. I am on Laravel 5, this is why you will see Request::get('my_input_name').
Here is my js code :
$('.select_blocs_check').click(function() {
var blocID = $(this).val();
$.ajax({
type: "POST",
url: "http://localhost/send/getBlocHtml/",
data: {id: blocID},
success: function(html) {
$('#preview-wrap').html(html);
}
});
});
This is my php file
public function getBlocHtml()
{
$bloc_id = Request::get('id');
echo $bloc_id;
}
So, if I change my php file like this
public function getBlocHtml()
{
$bloc_id = Request::all();
print_r($bloc_id);
}
Now, it will print out : array(). Like if I have nothing in my data.. What's wrong with my data parameter in $.ajax ?
I see Laravel 5 in your question. Try Request::input('id'); Which will pull both Post and get.
Change how you pass your data. Try this :
$.ajax({
type: "POST",
url: "http://localhost/send/getBlocHtml/",
data: {'id': blocID},
success: function(html) {
$('#preview-wrap').html(html);
}
});
try change Request::get('value') to Input::get('value')
API says
This method is used for all request verbs (GET, POST, PUT, and DELETE)
In Laravel 5 API is Input static method.
And article which may help to you.
This is my test ajax in laravel 5 (refer below)
$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
url: "test",
type:"POST",
data: { testdata : 'testdatacontent' },
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
and the trigger link
Try
and my route
Route::post('test', function()
{
return 'Success! ajax in laravel 5';
});
but it gives me an error when I run the console in google chrome and it doesn't return the expected response "return 'Success! ajax in laravel 5';"
POST http://juliver.laravel.com/test 500 (Internal Server Error)
whats wrong/problem to my code? anything I'm missing?
While this question exists for a while, but no accepted answer is given I'd like to point you towards the solution. Because you're sending with ajax, and presumably still use the CSRF middleware, you need to provide an additional header with your request.
Add a meta-tag to each page (or master layout): <meta name="csrf-token" content="{{ csrf_token() }}">
And add to your javascript-file (or section within the page):
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
See https://laravel.com/docs/master/csrf#csrf-x-csrf-token for more details.
90% of the laravel ajax internal server error is due to missing CSRF token. other reasons can inlucde:
Wrong Request Type (e.g sending post to get)
Wrong data type recived (e.g ajax is expecting JSON and app returns string)
Your .htaccess is misconfigured
Missing Route
Code Error
You can read further about this in details here: https://abbasharoon.me/how-to-fix-laravel-ajax-500-internal-server-error/
I guess this has been solved by now but still the best thing to do here is to send the token with your form
{!! csrf_field() !!}
and then in your ajax
$("#try").click(function(){
var url = $(this).attr("data-link");
$.ajax({
url: "test",
type:"POST",
data: { '_token': token, 'someOtherData': someOtherData },
success:function(data){
alert(data);
},error:function(){
alert("error!!!!");
}
}); //end of ajax
});
You can add your URLs to VerifyCsrfToken.php middleware. The URLs will be excluded from CSRF verification.
protected $except = [
"your url",
"your url/abc"
];
In App\Http\Middleware\VerifyCsrfToken.php you could try updating the file to something like:
class VerifyCsrfToken extends BaseVerifier {
private $openRoutes =
[
...excluded routes
];
public function handle($request, Closure $next)
{
foreach($this->openRoutes as $route)
{
if ($request->is($route))
{
return $next($request);
}
}
return parent::handle($request, $next);
}
};
This allows you to explicitly bypass specific routes that you do not want verified without disabling csrf validation globally.
Laravel 7.X
In bootstrap.js, in axios related code, add:
window.axios.defaults.headers.common['X-CSRF-TOKEN'] = $('meta[name="csrf-token"]').attr('content');
Solved lot of unexplained 500 ajax errors.
Of course it's for those who use axios
By default Laravel comes with CSRF middleware.
You have 2 options:
Send token in you request
Disable CSRF middleware (not recomended): in app\Http\Kernel.php remove VerifyCsrfToken from $middleware array
for me this error cause of different stuff.
i have two ajax call in my page.
first one for save comment and another one for save like.
in my routes.php i had this:
Route::post('posts/show','PostController#save_comment');
Route::post('posts/show','PostController#save_like');
and i got 500 internal server error for my save like ajax call.
so i change second line http request type to PUT and error goes away.
you can use PATCH too.
maybe it helps.
you have to pass the csrf field through ajax please look at the code here
$.ajax({
type: "POST",
url:'{{URL::to("/delete-specialist")}}',
data: {
id: id,
_token: $('#signup-token').val()
},
datatype: 'html',
success: function (response) {
if(response=="deleted"){
$("#"+id).hide();
$("#message").html("successfully deleted");
}
}
});
and you also need to write this input field before this
<input id="signup-token" name="_token" type="hidden" value="{{csrf_token()}}">
still if you do not understand please enjoy this video
https://www.youtube.com/watch?v=ykXL8o0slJA&t=20s
do not forget add "use Illuminate\Http\Request;" on your controller
Short and Simple Solution
e.preventDefault();
var value = $('#id').val();
var id = $('#some_id').val();
url="{{url('office/service/requirement/rule_delete/')}}" +"/"+ id;
console.log(url);
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
/* the route pointing to the post function */
url: url,
type: 'DELETE',
/* send the csrf-token and the input to the controller */
data: {message:value},
dataType: 'JSON',
/* remind that 'data' is the response of the AjaxController */
success: function (data) {
console.log(data)
//$('.writeinfo').append(data.msg);
//$('#ruleRow'+id).remove();
}
});
return false;
Using post jquery instead helped me to solve this problem
$.post('url', data, function(response) {
console.log(response);
});
I had same problem. In my case, issue arise because my id field of table (in database) was not set to auto increment. When I set it to auto increment then it started working.