I am submitting a form and AJAX is displaying errors as it should but when everything goes right, it means that when form values are saving in database correctly AJAX is not triggering the success function.
Here's the Laravel product verification code:
public function productVerify(Request $request)
{
$val = $request->validate
(
[
'name' => 'required',
's_description' => 'required',
'l_description' => 'required',
'image_src' => 'required|mimes:jpg,png,jpeg',
'category' => 'required',
'quantity' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
'price' => 'required|integer|not_in:0|regex:^[1-9][0-9]+^',
],
[
'required' => 'The :attribute field is required',
'mimes' => 'Image should be a JPG, JPEG, or PNG',
'integer' => 'The :attribute field should be an integer.',
's_descripton.required' => 'The short description is required',
'l_descripton.required' => 'The long description is required',
'image_src.required' => 'The image file is required.'
]
);
if (!$val)
{
return response()->json(['errors']);
}
else
{
return response()->json(['success' => 'Product Added Successfully']);
}
}
Here's the AJAX code:
$(document).ready(function()
{
$("#addForm").submit(function(event)
{
// Store all data from form as object;
var formData = new FormData(this);
$.ajaxSetup({
headers:
{
'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content')
}
});
// AJAX implementation error:function() return errors without page reload.
$.ajax(
{
url: '/save_product',
type: "POST",
processData:false,
contentType:false,
cache:false,
dataType: 'json',
data:formData,
success: function(xhr)
{
responseSu = xhr.responseJSON.success;
alert(responseSu);
},
error:function(xhr, status, error)
{
// Errors from the XML Http Request JSON Response
responseER = xhr.responseJSON.errors;
// console.log(responseER);
$("#error").html(" ");
// For Each loop for printing errors from the response
$.each(responseER, function (key, item)
{
console.log(item);
$("#error").append("<li class='text-danger'>"+item+"</li>")
// Hide Errors after 15 seconds with a fadeout animation
$("#error").show().delay(15000).fadeOut();
});
}
});
// Stop form from submitting normally
event.preventDefault();
});
});
After the form is submitted successfully and data is inserted into database it gives the error:
