Cannot access data of deserialized json - 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.

Related

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

Delete Objects in Bucket with jQuery

How do i selete an object in a bucket through a jQuery-Call. The following Code shows my example for uploading the file. The goal is to have the deleting in a similar way. Thanks
function uploadFile(node) {
$('#hiddenUploadField').click();
$('#hiddenUploadField').change(function () {
if (this.files.length == 0) return;
var file = this.files[0];
switch (node.type) {
case 'bucket':
var formData = new FormData();
formData.append('fileToUpload', file);
formData.append('bucketKey', node.id);
$.ajax({
url: '/api/forge/oss/objects',
data: formData,
processData: false,
contentType: false,
type: 'POST',
success: function (data) {
$('#appBuckets').jstree(true).refresh_node(node);
}
});
break;
}
});
}
You could expose the necessary part on the server side (just like it is done for the /api/forge/oss/objects endpoint which uploads a file to a given bucket) which then could be called from the client side in a similar way.
Server side:
router.delete('/buckets/:id', function (req, res) {
var tokenSession = new token(req.session)
var id = req.params.id
var buckets = new forgeSDK.BucketsApi();
buckets.deleteBucket(id, tokenSession.getOAuth(), tokenSession.getCredentials())
.then(function (data) {
res.json({ status: "success" })
})
.catch(function (error) {
res.status(error.statusCode).end(error.statusMessage);
})
})
Client side:
function deleteBucket(id) {
console.log("Delete bucket = " + id);
$.ajax({
url: '/dm/buckets/' + encodeURIComponent(id),
type: 'DELETE'
}).done(function (data) {
console.log(data);
if (data.status === 'success') {
$('#forgeFiles').jstree(true).refresh()
showProgress("Bucket deleted", "success")
}
}).fail(function(err) {
console.log('DELETE /dm/buckets/ call failed\n' + err.statusText);
});
}
Have a look at this sample which has both file upload and bucket deletion implemented: https://github.com/adamenagy/oss.manager-nodejs
Ah great, thank you. And how would you solve it on the server side with C# ? Rigth now the Upload on server-side looks like:
[HttpPost]
[Route("api/forge/oss/objects")]
public async Task<dynamic> UploadObject()
{
// basic input validation
HttpRequest req = HttpContext.Current.Request;
if (string.IsNullOrWhiteSpace(req.Params["bucketKey"]))
throw new System.Exception("BucketKey parameter was not provided.");
if (req.Files.Count != 1)
throw new System.Exception("Missing file to upload");
string bucketKey = req.Params["bucketKey"];
HttpPostedFile file = req.Files[0];
// save the file on the server
var fileSavePath = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data"),
file.FileName);
file.SaveAs(fileSavePath);
// get the bucket...
dynamic oauth = await OAuthController.GetInternalAsync();
ObjectsApi objects = new ObjectsApi();
objects.Configuration.AccessToken = oauth.access_token;
// upload the file/object, which will create a new object
dynamic uploadedObj;
using (StreamReader streamReader = new StreamReader(fileSavePath))
{
uploadedObj = await objects.UploadObjectAsync(bucketKey,file.FileName,
(int)streamReader.BaseStream.Length, streamReader.BaseStream,"application/octet-
stream");
}
// cleanup
File.Delete(fileSavePath);
return uploadedObj;
}

ng-options is not displayed all the time in AngularJS

I have a small problem when I load my page. Sometimes, my ng-options has blank values. I don't understand why. I can load the page 10 times without problem, but I can load the page with blank values.
However, JSON returned is not blank. Always the same result :
SERVICE :
myApp.factory('GenericService', function ($http, $q) {
var data;
function getDataIfNeeded(the_action) {
the_action = the_action || 'default';
if (data !== undefined) {
return $q.when(data);
}
return $http({
url: "php/functions.php",
method: "GET",
params: {
action: the_action
}
}).then(function(response) {
data = response.data;
return data;
});
}
return {
getData: getDataIfNeeded
};
});
CONTROLLER :
GenericService.getData("get_leaders").then(function (data) {
$scope.leaders = data;
});
...
GenericService.getData("get_experts_ux").then(function (data) {
$scope.experts_ux = data;
});
JSON :
[
{"lead_technique_id":1,"lead_technique_name":"Delphine ____"},
{"lead_technique_id":2,"lead_technique_name":"Thierry ____"}
]
HTML :
<select ng-model="newProject.lead_technique_id" ng-options="leader.lead_technique_id as leader.lead_technique_name for leader in leaders" required></select>

Json query result not getting set

I am trying to use a Json request to get data from a login screen. But no matter if the login request is valid or not, I am always getting returned to my home screen. I think I am checking the result incorrectly?
Basically, in my Twitter-Bootstrap enabled site, I have a modal popup that takes the user to a login form.
The values are passed via a json query, to my MVC4 controller. A breakpoint shows I am getting good data.
Here's the scrip that sends the data:
<script type="text/javascript">
$(document).ready(function () {
$('.btnSubmit').on('click', function () {
var data = { username: $('.txtUsername').val(), password: $('.txtPassword').val(), rememberMe: $('.cbRemember').val() };
$.ajax({
url: '#Url.Action("LoginUser", "User")',
type: "POST",
contentType: "application/json",
data: JSON.stringify(data),
cache: false,
async: true,
success: function (result) {
if (result['success'] == 'true') {
alert("true");
window.location = '#Url.Action("Index", "Home")';
} else {
alert("BAD");
}
},
error: function () {
alert("Error in input");
}
});
});
});
</script>
And here is the controller method:
[HttpPost]
public JsonResult LoginUser(string username, string password, string rememberMe)
{
string success = "false";
string message = "Not set";
if (username == string.Empty || password == string.Empty)
{
success = "false";
message = "Invalid Username/Password";
}
else
{
if (ModelState.IsValid)
{
var us = new UserService();
var reply = us.Authenticate(username, Security.EncryptText(password));
if (reply == 0)
{
success = "false";
message = "Invalid Username/Password";
}
if (reply != 0)
{
var p = us.GetPerson(reply);
FormsAuthentication.SetAuthCookie(p.Id.ToString(CultureInfo.InvariantCulture), rememberMe == "on");
Session["UserDisplay"] = string.Format("{0} {1} - ({2})", p.Firstname, p.Surname, p.Email);
success = "true";
message = "Login Success";
}
}
}
var result = new { Success = success, Message = message };
var r = new JsonResult
{
Data = result
};
return r;
}
However, I always get the 'BAD' alert. Never the 'true'.
Can I check the result the way I am? Am I attempting to do this the right way? Basically, if I get 'BAD', I don't want the screen to refresh. Infact, I will want to show a message saying what ever is in the 'message' parameter.
Edit: I think 'result' is NULL.

is there any way to increase the limit of data using Get method in MVC4?

in MVC4 ,i am sending ajax call to server that holds much data :
$.ajax({
contentType: 'application/json; charset=utf-8',
method: 'get',
url: "Gateway/DB_Rola?count="+(n+1),
data: things[n],
success: function (Data) {
},
error: function () {
alert("ERROR: can't connect to Server this time :"+n+" "+things[n].verse);
return false;
}
});
sometimes it gives error due to massive data. is there anyway to increase the limit of data using get request ?
Try this, It's just an example,I have same problem
public JsonResult GelAllProductManagement()
{
var data = _taskProduct.GetAllProductListManagement(null);
var jsonResult = Json(data, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
This is my ajax request controller, add this line in your controller for massive records
var jsonResult = Json(data, JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
This will handle your massive request.