I am new to angular and trying to develop an application having nested
ng-repeat and after submitting the form it should hit the rest api.
I have been using $http to make rest api calls. The code gets submitted
with normal data but does not get submitted with nested ng-repeat when i
click the save button. Below I have provided the code with details.
The whole data should be shown in the console. I might have made some
mistake somewhere.Thanks in advance.
JS
$scope.saveVenFormData = function(vendet){
console.log($scope.vendet);
$scope.venFullAddress.push({
'vendorName': $scope.name,
'panNum': $scope.panNum,
'personName': $scope.venBusDetails.personName,
'mobileNum': $scope.venBusDetails.mobileNum,
'workNum': $scope.workNum,
'emailid': $scope.emailid,
'addressLine1': $scope.addressLine1,
'addressLine2': $scope.addressLine2,
'city': $scope.city,
'state': $scope.state
});
var dataObj = $scope.venFullAddress;
// console.log($scope.dataObj);
$http.get('/showVendors').success(function(data){
console.log(angular.toJson(data));
});
var res = $http.post('http://localhost:8080/dman/mm', dataObj);
res.success(function(data, status, headers, config) {
$scope.message = data;
});
res.error(function(data, status, headers, config) {
alert( "failure message: " + JSON.stringify({data: data}));
});
};
JSON structure:
{
"vendor": {
"vendorName": "",
"panNum": "",
"venBusDetails": [{
"personName": "",
"mobileNum": "",
"workNum": "",
"emailid": "",
"venContDetails": [{
"addressLine1": "",
"addressLine2": "",
"city": "",
"state": ""
}]
}]
}
}
https://plnkr.co/edit/nP8R92KNkz8JEHpvH56S?p=catalogue
For convenience I have added a json structure. I need to access all the
data from the form and hit the rest api.
The above is the link to the plunker. Thank you.
Try this
$scope.dataObjToPost = {
"vendor": {
"vendorName": $scope.vendet.vendorName,
"panNum": $scope.vendet.panNum,
"venBusDetails": [{
"personName": $scope.venBusDetails[0].personName,
"mobileNum": $scope.venBusDetails[0].mobileNum,
"workNum": $scope.venBusDetails[0].workNum,
"emailid": $scope.venBusDetails[0].emailid,
"venContDetails": [{
"addressLine1": $scope.venContDetails[0].addressLine1,
"addressLine2": $scope.venContDetails[0].addressLine2,
"city": $scope.venContDetails[0].city,
"state": $scope.venContDetails[0].state
}]
}]
}
} //And send this data to POST method
You used $scope.name in JS file but in HTML view you used ng-model="vendet.vendorName". Thats why it is always undefined.
UPDATED ANSWER Plunk LINK IS HERE
Related
I am working on a project using Laravel and yajrabix/laravel-datatables. I am having an issue when trying to access a column using columndefs. The column is supposed to be JSON data. Nothing is working to work with the data in that column. Is there a way to send the data unmodified for that column?
Bottom line, I would like to be able to access the data from the json stored in the results column. No matter what I do, it doesnt work.
Here is the code in my blade view. Everything else works on the datatable.
<script type="text/javascript">
$(function () {
var table = $('.table').DataTable({
processing: true,
serverSide: false,
ajax: "/admin/logs/datatable/lookup-ip",
columns: [
{data: 'id', name: 'id'},
{data: 'ip_address', name: 'ip_address'},
{data: 'results', name: 'results'},
{data: 'created_by', name: 'created_by'},
{data: 'created_at', name: 'created_at'},
],
columnDefs: [
{
targets: "_all",
className: 'nk-tb-col tb-col-mb'
},
{
targets: 2,
render: function (data, type, row, meta) {
return 'ISP: ' + data.ip;
}
}
],
});
});
</script>
This is the function in the controller serving the datatable.
public function datatable($log)
{
switch($log)
{
case 'activity':
$table = config('activitylog.table_name');
break;
case 'lookup-ip':
$table = IPLookup::getModel()->getTable();
break;
case 'lookup-phone':
$table = PhoneLookup::getModel()->getTable();
break;
}
$query = DB::table($table);
return DataTables::of($query)->toJson();
}
This is the data that is stored in the database.
{"ip": "8.8.8.8", "asn": "AS15169", "isp": "Google LLC", "org": "Google LLC", "city": "Ashburn", "type": "IPv4", "region": "Virginia", "country": "United States", "success": true, "currency": "US Dollar", "latitude": "39.0437567", "timezone": "America/New_York", "continent": "North America", "longitude": "-77.4874416", "country_code": "US", "country_flag": "https://cdn.ipwhois.io/flags/us.svg", "timezone_gmt": "GMT -5:00", "country_phone": "+1", "currency_code": "USD", "timezone_name": "Eastern Standard Time", "continent_code": "NA", "currency_rates": "1", "country_capital": "Washington", "currency_plural": "US dollars", "currency_symbol": "$", "completed_requests": 29, "country_neighbours": "CA,MX,CU", "timezone_dstOffset": "0", "timezone_gmtOffset": "-18000"}
The model of the IP log has casts setup.
protected $casts = [
'results' => 'array',
];
Okay so it figures after posting the question... I figure it out.
According to yajrabox:
By default, Laravel DataTables protects us from XSS attack by escaping all our outputs. In cases where you want to render an html content, please use rawColumns api.
So I modified the code in the controller returning the datatable and now it works as expected and I can parse the JSON and use it as an object in javascript.
return DataTables::of($query)
->rawColumns(['results'])
->toJson();
One thing I've notice is that the data stored on your database, according to your example, isn't wrapped into the array brackets ([ ]) and you're using a cast on the Module. That could be the cause of the problem.
Try going to your database and manually wrapping your JSON on array brackets and give it a shot!
I am creating a mean stack project i want to display array of objects values in a edit form so the problem is when i recieve data from all tables from backend it will work fine and show data in forms but when any of table table data is not present http request patch value method dosnt work and it show a empty form
json structure
"data": {
"id": 7,
"location": "Bikaner",
"empId": "ct141",
"firstName": "mahendra",
"lastName": "chauhan",
"dateOfBirth": "1984-09-11",
"gender": "male",
"emp_Edus": [
{
"id": 2,
"university": "MGSU",
"degree": "bca",
"eduStart": "2012-06-06",
"eduEnd": "2015-06-02",
],
"emp_Pre_Job_Details": [
{
"id": 2,
"company": "I tech",
"designation": "Manager",
"preJobStart": "2016-08-11",
"preJobEnd": "2020-02-12",
}
],
"emp_Current_JobSta": [
{
"id": 2,
"jobStatus": "Contractual",
"start": "2020-02-02",
"end": "2023-02-02",
"jobTitle": "Manager",
"accessReq": "1",
"supervisor": "",
}
]
}
patch value request
loadEmpData(id)
{
const formData = new FormData();
formData.append("id", id);
console.log("formData" + formData);
this.cs.empprofile(id).subscribe(response => {
if (response.status == 1) {
this.empData = response.data;
this.empEdusData = response.data.emp_Edus;
this.empcurrentJob = response.data.emp_Current_JobSta;
this.empPreJobData= response.data.emp_Pre_Job_Details;
this.editEmpForm.patchValue({
photograph: response.data.photograph,
empId: response.data.empId,
firstName: response.data.firstName,
lastName:response.data.lastName,
gender: response.data.gender,
university: response.data.emp_Edus[0].university,
degree: response.data.emp_Edus[0].degree,
eduStart: response.data.emp_Edus[0].eduStart,
eduEnd: response.data.emp_Edus[0].eduEnd,
company: response.data.emp_Pre_Job_Details[0].company,
designation: response.data.emp_Pre_Job_Details[0].designation,
preJobStart:response.data.emp_Pre_Job_Details[0].preJobStart,
preJobEnd: response.data.emp_Pre_Job_Details[0].preJobEnd,
jobTitle: response.data.emp_Current_JobSta[0].jobTitle,
start: response.data.emp_Current_JobSta[0].start,
end: response.data.emp_Current_JobSta[0].end,
jobStatus: response.data.emp_Current_JobSta[0].jobStatus,
supervisor : response.data.emp_Current_JobSta[0].supervisor
});
In your case you are getting data from backend, you can verify it in the network it will be there.
In the patch you are trying to retrieve table data using 0 index as response.data.emp_Edus[0], but if the response doesn't have data in the 0'th index then it will throw an error.
what you need to do is! before retrieving particular table data, just verify whether emp_Edus is not null, and length > 0, then retrieve it. Same validation you need to do for other two tables.
try in the below way!
let myForm = {};
myForm = {
photograph: response.data.photograph,
empId: response.data.empId,
firstName: response.data.firstName,
lastName:response.data.lastName,
gender: response.data.gender
};
if(response.data.emp_Edus != null && response.data.emp_Edus.length>0){
myForm.university= response.data.emp_Edus[0].university;
myForm.degree= response.data.emp_Edus[0].degree;
myForm.eduStart= response.data.emp_Edus[0].eduStart;
myForm.eduEnd= response.data.emp_Edus[0].eduEnd;
}
if(response.data.emp_Pre_Job_Details != null && response.data.emp_Pre_Job_Details.length>0){
myForm.company= response.data.emp_Pre_Job_Details[0].company;
myForm.designation= response.data.emp_Pre_Job_Details[0].designation;
myForm.preJobStart=response.data.emp_Pre_Job_Details[0].preJobStart;
myForm.preJobEnd= response.data.emp_Pre_Job_Details[0].preJobEnd;
}
if(response.data.emp_Current_JobSta != null && response.data.emp_Current_JobSta.length>0){
myForm.jobTitle= response.data.emp_Current_JobSta[0].jobTitle;
myForm.start= response.data.emp_Current_JobSta[0].start;
myForm.end= response.data.emp_Current_JobSta[0].end;
myForm.jobStatus= response.data.emp_Current_JobSta[0].jobStatus;
myForm.supervisor = response.data.emp_Current_JobSta[0].supervisor;
}
});
this.editEmpForm.patchValue(myForm);
I am new to both Angular and Firebase. Still trying to learn the ropes so I am hoping really bad that someone can help me out. I have tried looking through documentations and watching videos but honestly, I still don't get it.
I was able to retrieve my data from firebase using Angular's HTTPCLIENT service. However, it is in the below format:
{
"test01": {
"title": "News",
"descr": "Amazing!"
}
},
"test02": {
"title": "Panda",
"descr": "Amazing!"
}
}
But the problem is that I want to use ngFor to loop through my data so that it will display all the titles and descriptions (regardless of the id) in my homepage. Is there anyway to restructure the data I retrieved into the below format instead so I can loop through it and display the data as it is?
favItems = [{id: "test01", title: "News", descr: "Amazing!" }, {id: "test02", title....}]
Thank you!
You can use Object.keys - docs:
let obj = {
"test01": {
"title": "News",
"descr": "Amazing!"
},
"test02": {
"title": "Panda",
"descr": "Amazing!"
}
}
let arr = Object.keys(obj).map((k) => {
return { ...obj[k],
id: k
}
})
console.log(arr)
I have an json object coming from a $.post in jquery.
In order to loop through and store the data clientside I would like to add it to an array. For each search results that comes back I would like to "append" the array so it grows.
This is my json:
{
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
} ]
}
This is what I have come up with so far were data is the json
comming back fron the post ajax request. Obj is just an object holding the array
which I declared further up in my code. obj.companies = new Array();
obj.companies.push(data['companies']);
The next part I need to loop out the array. Trying to do it like this.
$.each(obj.companies, function(i, item) {
// Does not alert correctly.
alert(item.header);
});
So I need to push the full json object into the array. But I cannot alert the item.header within the loop, how can I accomplish this?
EDIT:
Thanks everyone. Sorry if my question wasnt detailed enough.
I ended up doing this:
getcompanies: function() {
obj = this;
$.post('api/finder/result.php', {}, function(data) {
$.each(data.companies, function(i, item) {
obj.companies.push(item);
});
obj.loadcompanies();
}, "json");
},
loadcompanies: function() {
$.each(this.companies, function(i, item) {
alert(item.header);
}
}
I believe there is a issue with your server side code which is responsible for building JSON object which is getting returned via Ajax. The Correct JSON should be as follows:
{
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
}
]
}
Please note that there is only single key with name "companies" which holds an array of objects. Please correct your server side code to get such valid JSON. You can use free online JSON validator tools such as http://jsonlint.com/ to validate your JSON objects.
Now once you get such response from server; you just need to do following steps to get the companies array (following code will go into $.post success handler):
var jsonResp = JSON.parse(postResponse); //postResponse is the success resp of $.post
var companiesArray = jsonResp.companies;
$.each(companiesArray , function (index, valueObj){
var compId = valueObj.companyid;
var isSaved = valueObj.saved;
});
I hope this will help you a bit.
if you want to append new company into your companies array you should
var json_obj = {
"companies": [
{
"companyid": "115",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
},
{
"companyid": "116",
"saved": false,
"orgnumber": "010101010",
"companyname": "TestCompany",
"header": "header info"
} ]
};
//adding new company into your companies array
json_obj.companies.push({
"companyid":"117",
"saved" : false,
"orgnumber": "20120313",
"companyname":"anotherCompany",
"header":"another header info"
});
//if you want to loop through your companies list you can:
json_obj.companies.map(function ( obj ){
console.log(obj.companyid);
console.log(obj.companyname);
etc..
});
Apologies in advance - I am new to this and so other answers have not been able to help me.
I have used AJAX to send data to a PHP script (part of a 3rd party API). The PHP script returns the results as JSON, but I have no idea how to format these on my HTML page.
Ultimately, I would like to save the JSON results as an array and then use JS/Jquery to format them on the page.
I am not sure how to modify the PHP and AJAX scripts to achieve this. Can anyone point me in the right direction?
My AJAX:
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
success: function(data) {
<!--NOT SURE WHAT TO PUT HERE-->
}
})
PHP (after the calculator does its thing - not sure if it needs to be changed):
$serviceTypesJSON = json_decode($rawBody);
echo json_encode($serviceTypesJSON);
The expected JSON results should look like:
{
"services": {
"service" : [
{
"code": "AUS_PARCEL_REGULAR",
"name": "Parcel Post (your own packaging)",
"speed": 2,
"price": 6.95,
"max_extra_cover": 5000,
"extra_cover_rule": "100,1.5,1.5",
"icon_url": "http://test-static.npe.auspost.com.au/api/images/pac/regular_post_box.png",
"description": "Based on the size and weight you've entered",
"details": "Check our ",
"delivery_time": "Delivered in up to 3 business days",
"ui_display_order": 1,
"options": {
"option": [
{
"code": "AUS_SERVICE_OPTION_STANDARD",
"name": "Standard Service",
"price": "0.00",
"price_type": "static",
"option_type": "optional",
"ui_display_order": 1
},
{
"code": "AUS_SERVICE_OPTION_SIGNATURE_ON_DELIVERY",
"name": "Signature on Delivery",
"price": 2.95,
"price_type": "static",
"option_type": "optional",
"tooltip": "Signature on Delivery provides you with the peace of mind that your item has been delivered and signed for.",
"ui_display_order": 2,
"suboptions": {
"option": {
"code": "AUS_SERVICE_OPTION_EXTRA_COVER",
"name": "Extra Cover",
"option_type": "optional",
"price_type": "dynamic",
"tooltip": "Extra Cover provides cover for loss, damage or theft of your item and will fully compensate you to the value specified for your item.",
"ui_display_order": 1
}
}
}
]
}
},
You can do two things, if the return data is JSON use dataType: "json" in the AJAX call.
Edit 1
If you are using dataType: "json". Which is more preferred if you are sure the data return is JSON string. data variable in the success will directly give you the JSON object. I think you can access it like data['services'].
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services;
}
Or you can just get the data then use jQuery.parseJSON() to parse the data string into JSON object.
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {
toPostcode: toPostcodeValue,
parcelLengthInCMs: parcelLengthInCMsValue,
parcelHeighthInCMs: parcelHeighthInCMsValue,
parcelWidthInCMs: parcelWidthInCMsValue,
parcelWeightInKGs: parcelWeightInKGsValue
},
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services; //or jsonObj["services"]
}
})
Your success function will never be called if you are using
echo json_encode(); in your php script.
You should add dataType:'json' after type:'POST' and then your success function will get called and will get the result returned by server in data