Handeling JSON in Laravel controller - json

I'm new to Laravel and kinda new to JQuery too so bear with me please. So in one of my views I have a form :
<table id="tblAShip" class="report table table-condensed table-hover table-sorter">
<thead class="no-sort">
<tr>
<th>Height</th>
<th>Width</th>
<th>Length</th>
<th>Weight</th>
<th>Create parcel</th>
</tr>
</thead>
<tbody>
<tr>
<td><input id="height" name="height" type="number" /></td>
<td><input id="width" name="width" type="number" /></td>
<td><input id="length" name="length" type="number" /></td>
<td><input id="weight" name="weight" type="number" /></td>
<td><input type="button" name ="creatShip" id="creatShip" value="Ajouter"></td>
</tr>
</tbody>
Then this form is handled by a JS that makes an Ajax call
function creerParcel(){
var docNum = $("#commandeNum").val();
var hei = $("#height").val();
var wid = $("#width").val();
var len = $("#length").val();
var wei = $("#weight").val();
$.ajax({
type: "POST",
url: "/EasyPostNetBanks/Shipment/"+docNum,
contentType: "application/json; charset=utf-8",
processData: false,
data: {
"Parcels":[{
"length": len,
"width": wid,
"height": hei,
"weight": wei }]
},
error: function(jqXHR, textStatus, errorThrown)
{
},
success: function(data){
}
});
then in my controller I try go retreive this data to create a shipment with the parcel information i got from my Ajax call
foreach(\Input::get('Parcels') as $parcelInfo)
{
$parcel = $this->CreateParcel($parcelInfo);
$shipment = Shipment::create(array(
"to_address" => $to,
"reference"=>$idCommande,
"from_address" => $from,
"parcel" => $parcel,
"options" => array("label_format" => "ZPL")
));
$ship = \Shipments::creer($shipment);
$shipments[] = $ship;
}
but my \Input::get('Parcels') is always NULL\n. How is it possible? I've tried almost everything i could find online but to no avail so here I am (first post BTW. Hi all!).

Have you tried viewing the network tab in a browser, to see if everything is being sent up to the server in the way you're expecting? For example, in Chrome open the inspection panel, usually right click and then choose "Inspect Element". Then look in the "Network" tab to see exactly what is being sent to the server.
If the ajax post looks correct, then it will help narrow down exactly where the problem lies. If it's not the front end, try die and dump dd($variable) on the entire post results.
You can do that by using the following somewhere in the controller.
dd(Input::all());

OK, turns out it was my processData: false, that caused the problem, silly me.

Related

How to convert json string to ko.observableArray([]), array of objects?

I have a ViewModel works with knockout framework and ajax. I can save new items to the database with ajax.Save but I have problem when I want to retrieve the saved data. Here are the codes.
Codes in ViewModel:
self.Categories = ko.observableArray([]);
self.Message = ko.observable("");
elf.GetCategories = function () {
$.ajax({
url: "/Admin/Categories",
cache: false,
type: "GET",
datatype: "json",
contenttype: "application/json;utf8"
}).done(function (data) {
self.Categories(ko.mapping.fromJS(data));
}).error(function (err) {
self.Message("Error! " + err.status);
});
}
console.log(JSON.stringify(data)); returns:
{"categories":[{"Id":1,"Name":"Learning","UrlSlug":"0-learning","Description":"learning"},
{"Id":2,"Name":"Topics","UrlSlug":"0-topics","Description":"posts"},
{"Id":3,"Name":"Shares","UrlSlug":"category-shares","Description":"shares"},
{"Id":4,"Name":"Projects","UrlSlug":"category-projects","Description":"project"}]}
Codes in controller is:
[HttpGet]
public ContentResult Categories()
{
var categories = _weblogServices.Categories();
return Content(JsonConvert.SerializeObject(new {categories}), "application/json;utf8");
}
and the problem is the self.Categories = ko.observableArray([]); is always empty without any data. I also tried these items too, but nothing changed:
ko.mapping.fromJS(data, self.Categories);
self.Categories(ko.mapping.fromJS(data));
self.Categories(ko.mapping.fromJSON(data));
ko.mapping.fromJS(data, {}, self.Categories);
I have a simple table in view :
<table id="tblCategory" class="table table-striped table-bordered
table-responsive table-condensed table-hover">
<thead>
<tr>
<th class="text-center">Name</th>
<th class="text-center">Url Slug</th>
<th class="text-center">Description</th>
</tr>
</thead>
<tbody data-bind="foreach: Categories">
<tr>
<td><span data-bind="text: Name"></span></td>
<td><span data-bind="text: UrlSlug"></span></td>
<td><span data-bind="text: Description"></span></td>
<td><button type="button" class="btn glyphicon glyphicon-pencil"
title="Edit" data-bind="click:$data.GetSelected"></button></td>
<td><button type="button" class="btn glyphicon glyphicon-trash"
title="Delete" data-bind="click:$data.DeleteSelectedCategory">/button></td>
</tr>
</tbody>
</table>
So, the question is how can I convert JSON data to observableArray([])?
UPdate: Chrome debugger says: data and Categories are not available.
You don't need to use mapping at all.
In your ajax call .done, you simply have to do this:
self.categories(data.categories);
As an observable array, categories expect an array as parameter. And according to the result of console.log(JSON.stringify(data)) being: {"categories":[{...}, {...}, ...], the array is on the categories property of the received data.
You don't need to use mapping because you simply need to show the objects inside the array, and you don't want to edit their properties. So they can be left as regular JavaScript objects, without observable properties.

Inserting data into database by WEB API in angular JS

I am new into angular JS and web api world. Recently facing difficulty in sending data into database through web api and angular. I am able to load json data from webapi.Any help will be highly appreciated.
My html:
<div class="container-fluid" ng-controller="SubmitDataCtrl">
<div class="container text-center" style="margin-bottom:5px">
<div id="divTables">
<table id="tbl_SMDetails" class="display responsive nowrap aleft" cellspacing="0" width="100%">
<thead>
<tr>
<th class="all">Name</th>
<th class="all">CTSID</th>
<th class="all">FDID</th>
<th class="all">Name of the Project</th>
<th class="all">Effort Hour</th>
<th class="all">Month</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="showData in loadData">
<td>{{showData.EmpName}}</td>
<td>{{showData.EmpCognizantID}}</td>
<td>{{showData.FDID}}</td>
<td><input id="Text1" type="text" />{{showData.projectName}}</td>
<td><input id="Text1" type="text" />{{showData.effortHour}}</td>
<!--<td>{{date | date:'MM-dd-yyyy}}</td>-->
<td>{{showData.date}}</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
<a ng-href='#SubmitData' class="btn btn-default" ng-click='go()'>Submit</a><span></span>
<a ng-href='#SubmitData' class="btn btn-default" ng-click=''>Reset</a>
</div>
</div>
My service page looks like:
var request = $http({
method: method_args,
url: myConfig.ServiceURL + url,
data: JSON.stringify(input_data),
Accept: 'application/json',
headers: {'Content-Type':'application/json'},
xhrFields: {
withCredentials: true
}
});
}
and my controller is
App.controller("SubmitDataCtrl", function($scope, ajaxService) {
//login user
ajaxService.MakeServiceCall("employee/GetTeamMember? superVisiorCogniID=256826", "GET", "")
.then(function effortData(data)
{
// alert(data);
$scope.date = new Date();
$scope.loadData = data;
showData = $scope.loadData;
for (var i = 0; i < showData.length; i++)
{
//alert(showData[i].EmpName + showData[i].EmpCognizantID + showData[i].FDID);
}});
$scope.go = function()
{
//alert('clicked');
ajaxService.MakeServiceCall("effort/SaveTeamEfforts?hourLoadDate=08/20/2015&hourLoadByCogniID=256826&forMonth=July", "POST", Employee).then(function save() {
var Employee =
{
"EmpCogniID": showData[i].EmpCognizantID,
"FDTimeCardHour": showData[i].effortHour,
"HourLoadDate": 08/11/2015,
"HourLoad`enter code here`By": "256826",`enter code here`
"ForMonth": "july"
}
}).success(function (Employee)
{
$scope.showData[i] = Employee;
});
alert(Employee); }});
It's hard to answer without knowing what the API POST call should do.
Can you confirm that the POST you are making to effort/saveTeamEfforts works by executing it using a REST tester in the browser?
if that is working, you should add an .error function to your API call and see what error is returned as dan has sugested above
L

checking a single checkbox per html row using angular js

i have a table that loads multiple checkboxes and selectboxes.when i click on one checkbox or select box it automatically selects every other box on the table .i want to have the option to choose either one checkbox or select box per row on it own.
<tr id="TableBody" ng-repeat="code in Register.RegisterDetails">
<td>{{$index+1}}</td>
<td ng-bind="code .CodeID"><input type="text" ng-model="Register.CodeID" /></td>
<td ng-bind="code .name"><input type="text" ng-model="Register.Firstname" /></td>
<td ng-bind="code .Lastname"><input type="text" ng-model="Register.Lastname" /></td>
<td><input type="checkbox" ng-model="Register.Presentstatus" id="PresentCheckbox" name="PresentCheckbox" /></td>
<td><select id="reasons" name="reasons" ng-model="Register.Category" ng-disabled="Register.Presentstatus" ng-clicked="Register.Presentstatus && O" ></td>
</tr>
my module that gets my data
function Register(){ self.RegisterDetails = function () {
var params = { pass params here };
return $http.get
{
url: GetRegisterDetails,
params: params,
success: function (data) {
self.RegisterDetails = data.data;
}
});
}
my controller
ngAppModule.controller('RegisterController',['$scope','$http',function($scope,$http)
{
var self = this;
$scope.Register = new Register($http);
}]);
all the above code works fine. i just dont know how to check a single box per row.sorry im new to this site
The main problem you're running into is you are binding to the wrong this inside your ng-repeat.
Your HTML currently repeats a checkbox for every code, but binds that to the same object property Register.Presentstatus.
<tr id="TableBody" ng-repeat="code in Register.RegisterDetails">
<td>{{$index+1}}</td>
....
<td><input type="checkbox" ng-model="Register.Presentstatus" .../></td>
</tr>
You'll need to bind this to a row-specific (code-specific) property if you want each row to have independent check boxes. Perhaps you are looking for something that binds the checkbox to an element in an array:
<tr id="TableBody" ng-repeat="code in Register.RegisterDetails">
<td>{{$index+1}}</td>
....
<td><input type="checkbox" ng-model="Register.Presentstatus[$index]" .../></td>
</tr>
or actually binds to a property of the code object
<tr id="TableBody" ng-repeat="code in Register.RegisterDetails">
<td>{{$index+1}}</td>
....
<td><input type="checkbox" ng-model="code.Presentstatus" .../></td>
</tr>
Since youur ng-model="Register.Presentstatus" is repeating and is same for all so you have same binding for all rows. you can alter them to have different binding

Syntax error in jquery ajax call

My HTML is like this
<tbody>
<tr>
<td ><img src="" alt="close" /></td>
<td><input type="hidden" name="addproducts" value="141420">141420</td>
<td class="prd"><strong></strong></td>
<td><a rel="prettyPhoto" href=""><img src="" alt="Product"></a></td>
</tr>
<tr>
<td ><img src="" alt="close" /></td>
<td><input type="hidden" name="addproducts" value="1213143">1213143</td>
<td class="prd"><strong></strong></td>
<td><a rel="prettyPhoto" href=""><img src="" alt="Product"></a></td>
</tr>
<tr>
<td ><img src="" alt="close" /></td>
<td><input type="hidden" name="addproducts" value="242424">242424</td>
<td class="prd"><strong></strong></td>
<td><a rel="prettyPhoto" href=""><img src="" alt="Product"></a></td>
</tr>
</tbody>
I want select all hidden inputs with name addproducts from this and add to an ajax call.
The problem is that I can't predict how many elements will be there before the code execute.
The ajax url i am trying to make will be like this
http://mydomain.com?addproducts=141420&q141420=16&addproducts=X945X2MG&qX945X2MG=1&addproducts=8382355&q8382355=10&addproducts=146353&q146353=3
my usual code for specific parameters in url will be some thing like this
ajaxManager.add(({
type: 'GET', url: '/ajaxhandler', data: { addproducts: X945X2MG,qX945X2MG:1}
but here i can't use this because of unpredictable parameters.
any way i had made some try which ended up in syntax error.code is this
ajaxManager.add(({
$(this).parent().parent().find(".antal").find("input:hidden[name='addproducts']").map(function () {
return
type: 'GET', data: {addproducts:this.value,'&q'+$(this).val():$(this).next().val()}
EDIT:from Alnitak's post i have tried to edit this .
new code
var data = $(this).parent().parent().find(".antal")
.find("input:hidden[name='addproducts']").map(function () {
return
{ addproducts: this.value}
data['q' + $(this).val()] = $(this).next().val();
}).get().join(',')
ajaxManager.add(({
type: 'GET', data: data
but unfortunatedly it ended up my ajax call comes like this
http://mydomain.com?_=1365768440633
I am sure I have made some thing terribly wrong.Cany one help me on this
You should create an object literal with the known keys, and then use obj[key] syntax for the variable keys:
var data = { 'addproducts[]': [] };
$(this).parent().parent().find(".antal")
.find("input:hidden[name='addproducts']")
.each(function () {
data['addproducts[]'].push(this.value);
data['q' + this.value] = $(this).next().val();
});
$.ajax({
...,
data: data
});
Note the use of addproducts[] to allow encoding of an array of values for that particular parameter. Note that there's not actually a defined standard for passing multiple values with the same key for x-www-form-urlencoded data, but this works with PHP. You should consider changing the way your products are added - perhaps a comma-separated list?

Retrieving values from a table cell <td> to a controller

I'm trying to get a specific value from a table cell and pass is to a controller. But it doesn't seem to be working. I show you some of my codes:
This is in the controller:
def searchUser = {
String abc = request.getParameter("harrow")
println(abc)
}
This is in the html page:
<form>
<div style="height: 250px; overflow: scroll; width: 100%;">
<table id="normal">
<g:each in = "${result}">
<tr id="btn">
<td width=10% >${it.ID}</td>
<td width=25% id="harrow">${it.username}</td>
</tr>
</g:each>
</table>
</div>
<input type ="submit" name ="abc" id="opener">
</form>
EDIT
AJAX:
$("#edittable").on('click', function() {
$.ajax({
url: URL,
data: $(this).serialize(),
type: "POST",
success: function(html){
//do something with the `html` returned from the server here
$("#edit1").html(html).dialog("open")
},
error: function(jqXHR, textStatus, errorThrown){
alert('error: ' + textStatus + ': ' + errorThrown);
}
});
return false;//suppress natural form selection
});
I can get the value to pass to the controller, but right now it only retrieves the first row of values rather than the other. Is there something wrong with my AJAX codes? Thank you guys so much.
So to show details of the row, one of the approaches can be:
CONTROLLER METHODS
def rows = [
[id:1, name:'name1'],
[id:2, name:'name2'],
[id:3, name:'name3']
]
def show(){
[results:rows]
}
def showLine(Long id){
render rows.find {it.id == id }
}
VIEW
<html>
<head>
<g:javascript library="jquery" />
<r:layoutResources />
</head>
<body>
<table>
<thead>
<tr>
<th>Action</th>
<th>Id</th>
<th>Name</th>
</tr>
</thead>
<tbody>
<g:each in="${results}" status="i" var="r">
<tr>
<td><g:remoteLink value="Details" id="${r.id}" action="showLine" update="lineDetails">Details</g:remoteLink></td>
<td>${r.id}</td>
<td>${r.name}</td>
</tr>
</g:each>
</tbody>
</table>
<div id="lineDetails">
</div>
</body>
</html>
Basically you call showLine method using AJAX and passing row object id. Then you search for the object and render it back. Rendered data is put into div under the table. It's up to you if you use onclick, button or link in the table. It's also up to you how to show details on results page - use jquery dialog, or something else. Hope it helps