500 (Internal Server Error) For Ajax POST in Laravel - ajax

Please can someone provide a simple example for ajax in laravel 5.1. I have tried everything and still no success. Tried the other solutions here but no luck, maybe it is my copy of laravel, I really don't understand. I just want to see how its done correctly. Please help me out. Thanks.
Route: Route::post('/signin', 'UserController#ajax');
<form action="signin" method="POST" id="form1">
<input type="hidden" name="_token" value="{{ csrf_token() }}">
<fieldset>
<p><label for="email">E-mail address</label></p>
<p><input type="email" value="{{ old('email') }}" onBlur="if(this.value=='')this.value='mail#address.com'" onFocus="if(this.value=='mail#address.com')this.value=''" name="email"></p> <!-- JS because of IE support; better: placeholder="mail#address.com" -->
<p><label for="password">Password</label></p>
<p><input type="password" name='password' value="password" onBlur="if(this.value=='')this.value='password'" onFocus="if(this.value=='password')this.value=''"></p> <!-- JS because of IE support; better: placeholder="password" -->
<p><input type="submit" value="Login" name="submit" id="sign"></p>
</fieldset>
</form>
for the controller:
public function ajax(Request $request)
{
if(Request::ajax()) {
$data = Request::all();
print_r($data);
]);
}
And ajax:
$('#sign').click(function(event) {
$.ajaxSetup({
headers: { 'X-CSRF-Token' : $('meta[name=_token]').attr('content') }
});
var inputs = $('#form1').serialize();
$.ajax({
url: 'http://localhost/laravel/public/signin',
type: 'POST',
dataType: 'json',
data: inputs,
success: function (data) {
console.log(data);
}
})
return false;
});

Related

Form not submitting within Iframe

I want to submit a form within an iframe using javascript. this is the code which i tried. This doesn't work. Any one have idea?
$(document).ready(function () {
$("#get_response_form").submit();
});
<iframe src="" frameborder="0">
<form action="https://app.getresponse.com/add_subscriber.html" accept-charset="utf-8" method="post"
id="get_response_form">
<!-- Name -->
name: <input type="text" name="name" value="{{ array_key_exists('fname',$this->data)?$this->data['fname']:'' }}
{{ array_key_exists('lname',$this->data)?$this->data['lname']:'' }}" /><br />
<!-- Email field (required) -->
email: <input type="text" name="email"
value="{{ $this->data['email']?$this->data['email']:'' }}" /><br />
<!-- List token -->
<!-- Get the token at: https://app.getresponse.com/campaign_list.html -->
<input type="hidden" name="campaign_token" value="{{ $this->campaign->get_respond }}" />
<!-- Subscriber button -->
<input type="submit" value="Subscribe" />
</form>
</iframe>
$("#get_response_form").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
e.preventDefault();
var form = document.forms.namedItem("name of your form");
$.ajax({
url: "{{url('Post url in your web.php')}}",
method: 'POST',
data: form,
success: function (response) {
location.reload();
console.log(response);
// alert(response);
},
error: function (response) {
console.log('Error:', response);
// alert(response);
}
})
$('#get_response_form')[0].reset();
});

My ajax request return status error 405 on laravel

I'm using laravel 6. IT returns me error 405 when using external ajax.js file to handle my form.
message: The POST method is not supported for this route. Supported methods: GET, HEAD.
This is my form in blade:
<form >
#csrf
<div class="form-group">
<label>Name:</label>
<input type="text" name="name" class="form-control" placeholder="Name" required="">
</div>
<div class="form-group">
<label>Password:</label>
<input type="password" name="password" class="form-control" placeholder="Password" required="">
</div>
<div class="form-group">
<strong>Email:</strong>
<input type="email" name="email" class="form-control" placeholder="Email" required="">
</div>
<div class="form-group">
<button class="btn btn-success btn-submit">Submit</button>
</div>
</form>
my ajax.js:
$(document).on('submit','#employeeSignupFrom',function (e) {
var token = $('input[name="_token"]').attr('value')
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': token
}
});
$.ajax({
$url:'/signupemployee',
type:'post',
data: $(this).serialize(),
contentType:'json',
success: function( response, textStatus, jQxhr ){
alert('done')
},
error: function( jqXhr, textStatus, errorThrown ){
alert('error!');
}
});
e.preventDefault()
})
the route(web.php):
Route::post('/signupemployee','FormsController#signupEmployee');
and my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
class FormsControllers extends Controller
{
public function signupEmployee(Request $request){
$employeeInfo=$request->all();
return response()->json(['alert'=>'done!']);
}
}
First remove $ sign from your url:
//$url:'/signupemployee', <- remove $
url:'/signupemployee',
Second change contentType to:
contentType: 'application/json',
Finally your ajax should be something like this:
$.ajax({
url: '/signupemployee', //<- $ sign should deleted
type: 'POST',
data: data,
contentType: 'application/json', //<- not just json
headers: {
'X-CSRF-TOKEN': token
}
})

Laravel ajax only the first button excute the other button will not response

I need your help guys im stuck because when i click the first button it will execute but the other button it will not excute im using ajax for the form and i use foreach. If someone know how to solve please tell me.
This is my current view code:
<tbody>
#foreach($customers as $name => $member)
#foreach($member->slice(0,1) as $value)
<tr>
<td>{{$value->id}}</td>
<td>{{$value->MATNR}}</td>
<td>{{$value->MAKTX}}</td>
<td>
<select class="form-control">
<option>{{$value->UNIT1}}({{$value->CONV1}})</option>
<option>{{$value->UNIT2}}({{$value->CONV2}})</option>
</select>
</td>
<td>
<select class="form-control">
#foreach($member as $value)
<option value="{{$value->CHARG}}">{{$value->CHARG}}</option>
#endforeach
</select>
</td>
<td>{{$value->VERME}}</td>
<td>
<form name="ajaxForm" id="ajaxForm" class="form-horizontal" novalidate="">
<input type="text" name="_token" value="{{ csrf_token() }}">
<input type="text" name="id" value="{{$value->id}}">
<button type="button" class="btn btn-primary" id="btnSave" value="add">Save</button>
</form>
</td>
</tr>
#endforeach
#endforeach
</tbody>
This is my current controller code
public function cart() {
if (Request::isMethod('post')) {
$id = Request::get('id');
$customers = DB::table('Materials')->select('Materials.MATNR','Materials.MAGRV','Materials.CONV1','Materials.id','Materials.CONV1','Materials.UNIT1','Materials.CONV2','Materials.UNIT2','Materials.MHDHB','Materials.MAKTX','Inventory.CHARG','Inventory.VERME')->join('Inventory',function($join){
$join->on('Inventory.MATNR','LIKE',DB::raw("CONCAT('%',Materials.MATNR,'%')"));
})->groupBy('Materials.MATNR','Materials.MAGRV','Materials.CONV1','Materials.id','Materials.CONV1','Materials.UNIT1','Materials.CONV2','Materials.UNIT2','Materials.MHDHB','Materials.MAKTX','Inventory.CHARG','Inventory.VERME')->find($id);
$cart = ShoppingCart::add($customers->id, $customers->CHARG, 5, 100.00, ['MAKTX' => $customers->MAKTX, 'kg' => $customers->VERME]);
}
}
And my current route
Route::post('/cart', 'system\request_customer#cart');
Ajax current code
$(document).ready(function(){
$("#btnSave").click(function (e) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
})
e.preventDefault();
$.ajax({
type: 'POST',
url: 'cart',
data: $('#ajaxForm').serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});
});
});
So this is my new view
<form method="POST" class="form-horizontal ajaxForm">
<input type="hidden" id="token" name="_token" value="{{ csrf_token() }}">
<input type="hidden" name="id" id="id" value="{{$value->id}}">
<input type="hidden" name="MATNR" value="{{$value->MATNR}}">
<button>Submit</button>
</form>
and my new ajax
$(".ajaxForm").submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
url: 'cart',
type: 'POST',
data: formData,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
});
I had the same problem. I solved it by replacing id with class. I don't know why this is a solution, but it worked in my case. To make it easier for you, here is what you have to do. Just try it, according to me, It must work!
Replace every #ajaxForm with .ajaxForm.
Replace <form name="ajaxForm" id="ajaxForm" class="form-horizontal" novalidate=""> with <form name="ajaxForm" class="form-horizontal ajaxForm" novalidate="">
Let me know if it works. It worked in my case. In my case, I was having the same error. I mean, only first button or submit button worked.
If you are JQuery expert or know the reason behind this, please let me know!

500 Internal server error also after checking CSRF protection

I'm still having problems with submitting a form via AJAX in a Laravel project. I tried following some tutorials about submitting tokens with an AJAX request in Laravel, but I'm still having the error 500 (internal server error)
This is my script
$(document).on('click',"#registra_fornitore",function() {
$.ajax({
url: '/fornitori/create',
method: "POST",
data: {
'name':$('#nameSF').val(),
'_token': $('#_tokenSF').val(),
'nit':$('#nitSF').val(),
},
dataType: "json",
success: function(data){
alert(data);
}
});
This is the HTML for the form
<form>
<div class="form-group">
<label for="nameSF">Nome</label>
<input type="text" class="form-control" id="nameSF" placeholder="Nome">
</div>
<div class="form-group">
<label for="nitSF">NIT</label>
<input type="text" class="form-control" id="nitSF" placeholder="NIT">
</div>
<input type="hidden" id="_tokenSF" value="{{ Session::token() }}">
<button type="button" class="btn btn-default" data-dismiss="modal">Annulla</button>
<button type="button" class="btn btn-primary" id="registra_fornitore">Registra</button></form>
And this is the routes file
Route::group(['middleware' => ['web']], function () {
Route::get('/', function () {
return view('home');
});
Route::get('insert/{scope}','AdminController#getInsert');
Route::post('fornitori/create','SupplierController#postCreate');});
Any ideas of the problem? I tried also the different approach, writing the token value in a meta tag in the header of my template, and passing it in the ajaxsetup
Sorry, I found out the problem was a misspelling error in the storing method in the controller.

Ajax not working for many form on same page

in a view im repating the same form and posting it via ajax, my concern is the ajax is working for 1st form but not working from second form, below is the code im using.
<form action="http://localhost/comment" method="post" accept-charset="utf-8">
<input type="text" name="comment_text" value="" id="comment_text" size="35" class="comment_text">
<input type="submit" id="post_comment" name="post_comment" value="submit comment" class="post_comment" >
</form>
<form action="http://localhost/comment" method="post" accept-charset="utf-8">
<input type="text" name="comment_text" value="" id="comment_text" size="35" class="comment_text">
<input type="submit" id="post_comment" name="post_comment" value="submit comment" class="post_comment" >
</form>
<form action="http://localhost/comment" method="post" accept-charset="utf-8">
<input type="text" name="comment_text" value="" id="comment_text" size="35" class="comment_text">
<input type="submit" id="post_comment" name="post_comment" value="submit comment" class="post_comment" >
</form>
<form action="http://localhost/comment" method="post" accept-charset="utf-8">
<input type="text" name="comment_text" value="" id="comment_text" size="35" class="comment_text">
<input type="submit" id="post_comment" name="post_comment" value="submit comment" class="post_comment" >
</form>
<script type="text/javascript">
$('.post_comment').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $('.comment_text').val()
};
$.ajax({
url: "<?php echo site_url('/comment'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
</script>
Your problem is post_text: $('.comment_text', this).val() which will give you the value of the first selected .comment, what you want is the .comment in the current form. Try
<script type="text/javascript">
$('.post_comment').click(function() {
var form_data = {
csrfsecurity: $("input[name=csrfsecurity]").val(),
post_text: $(this).closest('form').find('.comment_text').val()
};
$.ajax({
url: "<?php echo site_url('/comment'); ?>",
type: 'POST',
data: form_data,
success: function(response){
$(".home_user_feeds").html("markUpCreatedUsingResponseFromServer");
}
});
return false;
});
</script>
Also element ids should be unique.

Resources