Laravel Validation fails when passing data through ajax Request - php

I am passing the value of the radio button to the controller when it is selected through ajax. The validation in the controller fails saying the field is required. I logged the dataString which carries the value in beforeSend. It logged the value of the selected of radio button. I also checked the network tab's requests which has the data in the request payload. I don't understand what causes the error here.
<input type="radio" name="port_type" id="low-risk" value = "low-risk" >
if ($('#low-risk').is(":checked")) {
var p_type = $(this).val();
console.log(p_type);
showFunds(p_type);
}
Here is the function that has ajax function
function showFunds(p_type){
var hello = p_type;
//console.log(p_type);
var dataString = 'p=' +hello;
//console.log(dataString);
$.ajax({
type: "POST",
url: "/showFunds",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: dataString,
cache: false,
contentType: false,
processData: false,
beforeSend : function(){
console.log('logging BS');
console.log(dataString);
},
success: function(data) {
console.log(data);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
},
});
}
Here is my controller
public function showFunds(Request $request){
$validator = \Validator::make($request->all(),[
'p' => 'required',
]);
if ($validator->fails()) {
//return response()->json(['msg'=>'val_fail']);
return response()->json(['msg'=>$validator->errors()]);
}
else{ }
The validator failing sending the errors "The p field is required."

Try this:
function showFunds(p_type){
var hello = p_type;
//console.log(p_type);
var dataString = JSON.stringify({p: hello});
//console.log(dataString);
$.ajax({
type: "POST",
url: "/showFunds",
headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
data: dataString,
cache: false,
contentType: false,
processData: false,
beforeSend : function(){
console.log('logging BS');
console.log(dataString);
},
success: function(data) {
console.log(data);
},
error : function(xhr ,status ,error)
{
console.log(xhr);
},
});
}

Related

Ajax getting 400 Bad Request when submitting Form only on Firefox

I have written a php code in wordpress to submit a form using ajax. It working fine on chrome but getting 400 Bad request on Firefox. This is my code:
jQuery(document).ready(function($){
jQuery( 'form[name="contact-me"]' ).on( 'submit', function(e) {
e.preventDefault();
var form_data = {};
$(this).serializeArray().forEach( function(element){
form_data[element.name] = element.value;
});
$.post(zt_send_form_obj.ajax_url, {
action: "zt_save_campain_form_data",
_ajax_nonce: zt_send_form_obj.nonce,
type: "POST",
contentType: 'application/json; charset=utf-8',
values: JSON.stringify(form_data),
}, function(data) {
if (data.success) {
if(data.data.info.message=='no'){
$('#myModal').show();
console.log('cod is in')
}
if(data.data.info.message=='yes'){
$('#CodeModal').show();
$('.the_cod_div').append('<span>'+data.data.info.code+'</span>');
console.log('data saved');
}
}
else{
console.log("not working");
}
});
});
});
Try this
$('form[name="contact-me"]').submit(function (e) {
e.preventDefault();
var form = $('#form_id')[0]; //set form id
var varform = new FormData(form);
varform.append("action", "zt_save_campain_form_data");
$.ajax({
url: ajaxurl,
type: 'POST',
dataType: 'json',
data: varform,
processData: false,
contentType: false,
cache: false,
crossDomain: true,
success: function (response) {
//if success do this...
console.log(response);
},
error: function (xhr, textStatus, error) {
console.log(xhr, textStatus, error);
}
})
});
Inside your form you can put this code for nonce validation
<?php wp_nonce_field( 'name_of_my_action', 'name_of_nonce_field' ); ?>

Laravel: MethodNotAllowedHttpException error with no message after AJAX call to resource controller

I'm updating the value of some models in a database but when I hit submit I get the following error:
"message: "", exception:
"Symfony\Component\HttpKernel\Exception\MethodNotAllowedHttpException",
file:
"C:\xampp\htdocs\Restaurante1\vendor\laravel\framework\src\Illuminate\Routing\RouteCollection.php",
line: 255"
This is my JQuery code:
var formData = new FormData();
formData.append('id', $(this).attr("data-id"));
formData.append('first', $('#schedules_morning').val());
formData.append('second', $('#schedules_night').val());
$.ajax({
async: true,
cache: false,
url: '/schedules',
type: 'PUT',
data:
{
formData
},
dataType: 'JSON',
processData: false,
contentType: false,
success: function (data) {
$('.form_valid_container').fadeIn().html('<span class="form_valid_text">✓ '+ data.success +'</span>');
form.trigger("reset");
console.log(data.success);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(){
$('.form_error_container').fadeIn().html('<span class="form_error_text">✘ '+ errors.message +'</span>')
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I'm sending the request to a resource controller route:
Route::resource('/schedules','ScheduleController');
public function update(Request $request)
{
$schedule = Schedule::findOrFail($id);
$schedule->morning = $request->morning;
$schedule->night = $request->night;
$schedule->save();
return response()->json([
'schedule' => $schedule,
'success' => 'Horario actualizado correctamente',
]);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
PHP (Laravel) Just trick up PUT and DELETE request so with all put request in laravel they put a hidden variable called _method with value put and laravel validated that method agains the post request. So replace your code like below and it should work.
var formData = new FormData();
formData.append('id', $(this).attr("data-id"));
formData.append('first', $('#schedules_morning').val());
formData.append('second', $('#schedules_night').val());
formData.append('_method', 'put');
$.ajax({
async: true,
cache: false,
url: '/schedules',
type: 'POST',
data:
{
formData
},
dataType: 'JSON',
processData: false,
contentType: false,
success: function (data) {
$('.form_valid_container').fadeIn().html('<span class="form_valid_text">✓ '+ data.success +'</span>');
form.trigger("reset");
console.log(data.success);
},
error: function (data){
var errors = data.responseJSON;
console.log(errors);
$.each(errors , function(){
$('.form_error_container').fadeIn().html('<span class="form_error_text">✘ '+ errors.message +'</span>')
});
}
});

Pass data from ajax to laravel 5.1 Controller in order to save to mysql?

I need to pass data from jquery (version 1.9.1) to my Controller (Laravel 5.1) and then save it to mysql.
How to do that and pass the variable slot? It didn't work so far. For any further details, please asked me.
jquery:
$(".tic").click(function(){
var slot = $(this).attr('id');
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { _token: {{ csrf_token() }}, moves: slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
Controller:
public function addhistory(Request $request)
{
$history = new History();
$history->game_id = Game::orderBy('id', 'desc')->first()->id;
$history->moves = $request->moves;
$history->save();
return redirect()->back();
}
Routes:
Route::post('/addhistory', 'GameController#addhistory');
Errors in console:
(index):198 Uncaught ReferenceError: HAmcYRScL9puItnUGbd2kHx.... is not defined
at HTMLAnchorElement.<anonymous> ((index):198)
at HTMLAnchorElement.dispatch (191.js:3)
at HTMLAnchorElement.v.handle (191.js:3)
191.js file is the jquery version of 1.9.1
You can use this code, it may works
$(".tick").click(function (event) {
event.preventDefault();
$('.loading').show();
var form = $(this);
var data = new FormData($(this)[0]);
var url = form.attr("action");
$.ajax({
type: "POST",
url: url,
data: data,
async: false,
cache: false,
contentType: false,
processData: false,
success: function (data) {
alert("Data has been saved successfully.");
},
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
}
});
return false;
});
Try this code-
$(".tic").click(function(){
var slot = $(this).attr('id');
var token= $("input[name='_token']").val();
playerTurn(turn, slot);
$.ajax({
url: '/addhistory',
type: 'POST',
data: { '_token': token, 'moves': slot },
success: function()
{
alert("Data has been saved successfully!");
}
});
});
And in your controller you don't need return redirect because the request is asynchronous. So I am returning true. Make sure you include History model at the top of your controller
public function addhistory(Request $request)
{
$game_id=Game::orderBy('id', 'desc')->first()->id;
History::create([
'game_id'=>$game_id,
'moves'=>$request->moves
]);
return true;
}

ajax beforeSend not working when sending formData

I am having a div
that shows a loader image while sending ajax requests
I attached the div in the beforeSend attribute of ajax. The issue is if I send serialize() data then the beforeSend works but doesn't work when I send formData
Works
$.ajax({
url: 'centre-basic-process.php',
type: 'post',
data: $('#centreform').serialize(),
beforeSend: function() {
$('.displayLoader').show();
},
success: function(response) {
console.log(response);
$('#centreformupload').show();
$('#centreform').hide();
$('html, body').animate({
scrollTop: 0
}, 0);
}
});
Doesn't work
$.ajax({
url: 'centre-upload-process.php',
type: 'POST',
data: formData,
async: false,
beforeSend: function() {
$('.displayLoader').show();
},
success: function(response) {
alert("You have succesfully submitted the form. Please complete the payment method");
document.location.href = "dashboard.php";
},
cache: false,
contentType: false,
processData: false
});
I even tried ajaxStart() but facing same issue. Can anyone help me?

jquery change event to submit form using ajax

Here is my form
<form name="uploadImg" id="uploadImg" class="profile-image" enctype="multipart/form-data">
<input type="file" name="profile" id="updProfileImg">
</form>
Here is my jquery event
$("#updProfileImg:file").change(function() {
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
})
})
But the change event is not triggering form submit so I tried trigger('submit') but the page is refreshing instead of submitting in ajax.
You are binding the events incorrectly. As you currently have it, changing the field will trigger the binding of the submit. It need to be like this:
// bind the submit event
$('#uploadImg').submit(function() {
var queryString = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
});
});
// bind the change event to trigger a submit
$("#updProfileImg:file").change(function() {
$("#uploadImg").submit();
});
A simple modification works
$("#updProfileImg:file").change(function() {
//$('#uploadImg').submit(function() {
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {
},
success: function() {
}
})
//})
})
you should try this code:
$("#updProfileImg:file").on("change", function(){
var queryString = new FormData($('#uploadImg')[0]);
$.ajax({
type: "POST",
url: 'index.php?route=account/edit/upload',
data: queryString,
contentType: false,
processData: false,
beforeSend: function() {},
success: function() {}
})
});
because i expect the ".change()" will be fired one time in the first change.

Categories