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

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);
}

Related

Cannot access data of deserialized json

I'm using ajax to send data to my controller, here's how I do it
var formData = JSON.stringify( $('#SubmitForm').serializeArray() );
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
data: {formData},
url: '{{route("fileController.sendFiles")}}',
success: function(response) {
console.log(response);
},
error: function(response){
console.log(response);
}
});
Here's the route
Route::post('/sendFiles', ['uses' => 'FileController#sendFiles'])->name('fileController.sendFiles');
And the controller
public function sendFiles(Request $request)
{
//$data = json_decode($request->input('formData'), true);
//return $request->input('allFiles');
$data = json_decode($request->input('formData'), true);
return $data['allFiles'];
}
However, I get this error
"message": "Undefined index: allFiles"
When I check the contents of $request, I can see that allFiles array is clearly there, but how do I access it?
P.S. I've tried changing the second param when decoding to false, there's no difference.
$request data array
First of all your request data is simple array of objects. So you cannot index it with "allFiles".
Second since we have multiple objects with attribute name="allFiles[]", what you can do is filter those objects and return the values of it. (I don't know how are you going to use it, but this is how the code looks)
public function sendFiles(Request $request)
{
//$data = json_decode($request->input('formData'), true);
//return $request->input('allFiles');
$data = json_decode($request->input('formData'), true);
//filter all allFiles object
$allFiles = array_filter($data, function($obj){
if(isset($obj->name)){
return $obj->name=="allFiles[]";
}
return false;
});
//get values for all the filtered objects
$allFilesValues = array_map(function($obj){ return $obj->value; }, $allFiles);
return $data['allFiles'];
}
Let me know if this works for you.

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 Error In Laravel Ajax

I'm Use Laravel 5.2 And Ajax For Crud
Insert to Database is Correct But When Laravel Response The Browser Show Below Error In Console
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Laravel Code:
return response()->json('ok');
Jquery Code:
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success: function (data) {
....
error: function(data){// Error...
var errors = $.parseJSON(data.responseText); console.log(errors);
$.each(errors, function(index, value) { $.gritter.add({
title: 'Error',
text: value
});
});
}
RedyState=4
Staus = 200
Can you paste your all controller code related to this error? Make sure you're not echoing anything before returning json response.
For example,
Route::get('/', function () {
echo "hi";
return response()->json('ok');
});
It would cause parse error.
With the Json response, what if you try something like.
return response()->json(['status'=>'ok']);
You javascript code should be
$.ajax({
type: type,
url: my_url,
data: formData,
dataType: 'json',
success:function (xhr){
var data = xhr.data;
},
error: function (error){
}
});
And why are you using var errors = $.parseJSON(data.responseText); ? Your response will be always json, no?

Returning JSONP from Symfony2 controller using AJAX call

I'm trying to return JSONP from Symfony2. I can return a regular JSON response fine, but it seems as if the JSON response class is ignoring my callback.
$.ajax({
type: 'GET',
url: url,
async: true,
jsonpCallback: 'callback',
contentType: "application/json",
dataType: 'jsonp',
success: function(data)
{
console.log(data);
},
error: function()
{
console.log('failed');
}
});
Then in my controller:
$callback = $request->get('callback');
$response = new JsonResponse($result, 200, array(), $callback);
return $response;
The response I get from this is always regular JSON. No callback wrapping.
The Json Response class is here:
https://github.com/symfony/symfony/blob/master/src/Symfony/Component/HttpFoundation/JsonResponse.php
As the docs says:
$response = new JsonResponse($result, 200, array(), $callback);
You're setting the callback method as the $headers parameter.
So you need to:
$response = new JsonResponse($result, 200, array());
$response->setCallback($callback);
return $response;
The JsonResponse's constructor doesn't take the callback argument. You need to set it via a method call:
$response = new JsonResponse($result);
$response->setCallback($callback);
return $response;