How to fix Laravel AJAX request not working - mysql

I am trying to store the data from multiple ratio buttons to the database.
And the AJAX post request is below:
$.ajax({
url: '{{ route("checklist.store") }}',
method:'POST',
data:{
_token: CSRF_TOKEN,
data1 : value1,
data2 : value2
},
success:function(data){
console.log('success');
}
});
The message in the console is printed on the console but the item is not created in the database.
Store method in controller :
$hacInspectionsChecklistTable = HacInspectionsChecklistTable::create($request->all());

Check your Model first :
protected $fillable = [
'data1', 'data2'
];
If everything is ok you can try with something like that
Ajax code :
$.ajax({
url: '{{ route("route.store") }}',
method:'POST',
data:{
_token: CSRF_TOKEN,
data1 : value1,
data2 : value2
},
success:function(data){
if(data=="created"){
console.log('success');
}
}
});
Route
Route::post('/youroute', [YourController::class, 'store'])->name('route.store');
Controller
public function store(Request $request){
$data = new Model();
$data->data1 = $request->data1;
$data->data2 = $request->data2;
$data->save();
return response()->json('created');
}

Related

new FormData works on one site but not on other

In my previous project I have:
let send = (form) => {
form = $(form)
...........
$.ajax({
method: 'post',
url: form.attr('action'),
data: new FormData(form[0]),
contentType: false,
processData: false
})
..........
return false
}
And my form looks like:
<?php $form = \yii\widgets\ActiveForm::begin([
'id' => 'w0',
'action' => 'site/send-contact',
'fieldConfig' => [
'options' => [
'tags' => false
]
]
]) ?>
................ some fields ............
\yii\widgets\ActiveForm::end(); ?>
Here, using the new FormData(..) works totally fine. You can check it here in the console networks tab. I have added var_dump($_POST) in the action. Now on my new project, new FormData(..) doesn't work. Absolutely no idea why. The dumped array is empty.
$.ajax({
method: 'get',
url: 'site/index',
data: {
data: new FormData($("#w0")[0])
},
})
And the form:
$form = \yii\bootstrap\ActiveForm::begin();
........... some fields here ............
\yii\bootstrap\ActiveForm::end()
Tried with post,get,contentType,processData just for any case but still empty array. Any suggestions? Thank you!
You can use Form submit event to submit form using ajax:
jQuery(document).ready(function($) {
$(".formclass").submit(function(event) {
event.preventDefault(); // stopping submitting
var data = $(this).serializeArray();
var url = $(this).attr('action');
$.ajax({
url: url,
type: 'post',
dataType: 'json',
data: data
})
.done(function(response) {
if (response.data.success == true) {
alert("Wow you commented");
}
})
.fail(function() {
console.log("error");
});
});
});
For more info

Laravel: sending JSONArray from ajax to Controller error: Undefined variable myData

I am sending a JSONArray via Ajax to Controller. and it is returning
"500 Internal Server Error"
After checking response of URL in console I found that my Array is undefined:
message- Undefined variable: myData
exception- ErrorException
file- C:\xampp\htdocs\EDO_Roster\app\Http\Controllers\EventController.php
This is my Ajax Code:
var myJson = JSON.stringify(myData);
var button = document.getElementById("submit");
button.addEventListener("click", function(event){
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
type: "POST",
url: "{{route('postEvent' , 'myJson')}}",
data: {myData: myJson},
contentType: "application/json; charset=utf-8",
dataType: "json",
}).done( function(data){
console.log('Ajax was Successful!');
console.log(data);
}).fail(function(){
console.log('Ajax Failed');
});
});
route of the function:
Route::post('randomPost', 'EventController#postEvent')->name('postEvent');
This is my Controller Code
public function postEvent(Request $request)
{
$events = DB::table('auto_events')
->insert(array(
'edo_id' => $myData->edo_id,
'strat' => $myData->start,
)
);
return response($events, 200);
}
I've tried several solutions provided at stack overflow like changing Ajax calls, checked my route several times.
You haven't defined the variable $myData inside your controller, that's why you got that error on your controller, you're supposed to get the input data from $request
just try as below
public function postEvent(Request $request)
{
$myData = $request->all();
$events = DB::table('auto_events')
->insert(array(
'edo_id' => $myData->edo_id,
'strat' => $myData->start,
)
);
return response($events, 200);
}

Pass json from ajax to laravel controller

would you like to help me? I have an ajax like this
var id = {{#$projectid}};
var datatab = JSON.stringify({data: change})
$.ajax({
url: 'save/'+id,
type: 'POST',
dataType: 'JSON',
data: {json:datatab},
success: function(response, textStatus, jqXHR) {
});
and then, I want to pass the datatab as json to database in json field
this is my save function in controller
public function save($project_id=0, Request $request)
{
$project_id = $request->project_id;
$weight = $request->weight;
TaskPlanning::create([
'project_id' => $project_id,
'weight' => $weight
]);
return response()->json([]);
}
In database, weight field is json. and I want to save my json file from ajax to weight
This is my model
class TaskPlanning extends Model
{
protected $table = 'p_task_planning';
protected $fillable = ['project_id','weight'];
public function project()
{
return $this->belongsTo(Project::class,'project_id','id');
}
public function milestone()
{
return $this->belongsTo(Milestone::class,'milestone_id','id');
}
protected $casts = [
'weight' => 'array'
];
}
Try this,
var id = {{#$projectid}};
var datatab = JSON.stringify({data: 'change'});
$.ajax({
url: 'save/'+id,
type: 'POST',
dataType: 'JSON',
data: {_token : '{!! csrf_token() !!}',
weight : datatab,
project_id : id
},
success: function(response, textStatus, jqXHR) {
});
use axios instead of $.ajax..
just make sure you add meta tag
<meta name="csrf-token" content="{{ csrf_token() }}" >
then
use axios like this..it will auto load csrf token
axios.post('save/'+id, data).then(function (response) {
//response
});

no display fail message from controller

I need validate user's nickname when the gonna registre in my proyect:
My Controller
$inputData = Input::get('nickname');
parse_str($inputData);
$informacion = array('nickname' => $inputData);
$regla = array('nickname'=>'required|unique:usuarios|alpha_num|min:6|max:15');
if($request->ajax()){
$usuarios = Usuarios::Usuarios();
$validar = Validator::make($informacion,$regla);
if($validar->fails()){
return Response()->json(array(
'fail' => true,
'errors' => $validar->getMessageBag()->toArray()));
}
else{
return Response()->json(array('success' => true, "message" => "Nombre de Usuario Disponible"));
}
}
My Script
$( "#validar" ).click(function( event ) {
var dato = $('#nickname').val();
var route = $('#form-sign-up').attr('action');
var tipo = $('#form-sign-up').attr('method');
var token = $('#form-sign-up #token').val();
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{nickname: dato},})
.fail(function(data){
$('#nickname-msj').html(data.errors);
$('#nickname-msj').fadeIn();
})
.done(function(data) {
$('#nickname-msj').html(data.message);
$('#nickname-msj').fadeIn();
});
});
.done works, but .fails not, and i need display that information to my user, because so they can know what is the problem, if someone can help me will be great.
I am using Laravel 5.2
Thank you.
The fails function of Ajax is triggered with a code different from 200. So you can return
if($validar->fails()) {
return response()->json($arrayHere, 400); //HTTP 400 error for bad request
}
So, just basically add 400 after your array, inside of json() function. When you don't specify the code, it defaults to 200.
Maybe also change your ajax request ? Or not
$.ajax({
url: route,
headers: {'X-CSRF-TOKEN': token},
type: tipo,
dataType: 'json',
data:{
nickname: dato
},
success: function (data) {
console.log(data);
},
error: function (data) {
console.log('Error:', data);
}
});

Json responseText empty and statusText as error

From mvc 4 action:
[HttpPost]
public ActionResult DoStuff(string str)
{
// Do some things
Response.ContentType = "application/json;charset=utf-8";
Response.StatusCode = someCondition == true ? HttpStatusCode.OK : HttpStatusCode.NotFound);
Response.TrySkipIisCustomErrors = true;
return Json(
new {
object1 = 1,
object2 = someArray[0],
object3 = someArray[1],
object4 = someValue == 4 ? 1 : 0
}
);
}
In jquery ajax:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
var _response = $.parseJSON(data);
}, function (data) {
var _response = $.parseJSON(data.responseText);
});
data.responseText is empty ("") and statusText is "error". It is not always happening. I have observed that it is happening randomly. Why?
Your data is already being converted to an object from JSON, so you do not need to parse it again. Try this:
ajax({
url: '/Ctrler/DoStuff/',
data: { str: someString },
type: 'POST',
dataType: 'json'
}).then(function (data) {
// use data here...
alert(data.object1);
}, function () {
alert('request failed');
});