How to submit ng-repeat data in angularjs - javascript

I need to submit the form which comes under the ng-repeat directive.I m getting the proper data in JSON format but when i execute the insert query it prints the last data.
For example: Take a view to my code
In view :
<div class="row" ng-init="get_membershipPlans()">
<div class="col-md-4" ng-repeat="x in plans" >
<div class="table-columns">
<form method="post" ng-submit="insert_data()">
<ul class="price height-price">
<li class="grey" ng-model="planDetails.price = x.price">${{x.price}}/ year</li>
<li ng-repeat="y in x.plansdetails">
{{y.feature_name}}
</li>
{{planDetails | json}}
</ul>
</form>
</div>
</div>
</div>
In angular controller :
$scope.insert_data = function () {
Data.insertData($.param($scope.planDetails)).success(function (data) {
$scope.planDetails = data;
});
};
In services :
this.insertData = function($data) {
return $http.post(site_url + "FunctionalController/inserttData" , $data);
};
In FunctionalController :
public function inserttData() {
$tablename = 'ult_book_camp';
$rs = $this->db->insert($tablename, $_POST);
if ($rs) {
echo json_encode(array('status' => '1','msg' => 'You have booked camps successfully'));
} else {
echo json_encode(array('status' => '0', 'msg' => 'No Result Found'));
}
}
In view,using ng-repeat it display three blocks when i print the data in json format ,get result like this {"plan_id": "1", "price": "10" } {"plan_id": "2", "price": "100" } {"plan_id": "3", "price": "105" } but when i submit a parrticular block related to plan_id =1 it submitted the plan_id = 3 in database which is the id of last element.
Whereas in database i have two fields plan_id and price. And i need to insert data in these field for each individual block.
Please help me to get this.Any help will be appreciated.
Thanks in advance.
Please check error:
Error: can't assign to properties of (new String("\r\n<pre>Array\n(\n [plan_id] => 3\n [price] => 120\n)\n</pre>")): not an object
fn#http://localhost/ultimate/angular-js/bower_components/angular/angular.min.js line 236 > Function:4:371
hh</<#http://localhost/ultimate/angular-js/bower_components/angular/angular.min.js:293:156
$digest#http://localhost/ultimate/angular-js/bower_components/angular/angular.min.js:144:43
$apply#http://localhost/ultimate/angular-js/bower_components/angular/angular.min.js:147:76
l#http://localhost/ultimate/angular-js/bower_components/angular/angular.min.js:98:419
D#http://localhost/ultimate/angular-js/bower_components/angular/angular.min.js:103:105
ug/</w.onload#http://localhost/ultimate/angular-js/bower_components/angular/angular.min.js:104:77

Related

Console.log shows my element as an array instead of an element

I'm doing a view where the customer is able to edit items, it comes with a filter so he/she can select between the options given. Everytime I edit it and save it works, however, if I return to the edit section the text box is empty and even though it was saved. If i use the inspect tool, the Console shows this:
impuestos_compra: Array [ {…} ]
If I open it, this is the information displayed:
impuestos_compra: (1) […]
"$$hashKey": "object:87"
0: Object { id: 2, empresa_id: 6, nombre: "IVA", … }
​​
length: 1
​​
<prototype>: Array []
This is the <DIV> label where I display this:
<div class="form-group col-md-6">
<label>
Impuestos de Mario
</label>
<select ng-model="articulo.impuestos_compra" name="impuestos_compra" class="form-control input-lg" required>
<option value="">Seleccione impuesto de compra</option>
<option ng-repeat="item in impuestos_compra" value="#{{ item.abreviacion }}">#{{ item.abreviacion }}</option>
</select>
</div>
In my try to iterate it, I did this code:
impuestos_compra = ['IVA' , 'IVAT0' ];
impuestos_compra.forEach(function(impuestos_compra) {
console.log(impuestos_compra);
});
And, finally, the controller from Laravel with the edit function looks like this:
public function edit($id)
{
$articulo = Articulo::with('sat_producto:clave,descripcion', 'sat_unidad:clave,descripcion')->findOrFail($id);
return view('panel.configuracion.articulo', [
'id' => $id,
'presentaciones' => Presentacion::select('nombre')->get()->toArray(),
'impuestos_compra' => Impuesto::select('abreviacion')->where('tipo' , 'compra')->get(),
]);
What am'I doing wrong? I tried ->get()->toArray() and it works neither.
Thanks in advance.
I think the problem is in your impuestos_compra initialization. You can try pluck instead of select. Pluck returns the value of the column as a collection. Try the following code.
public function edit($id)
{
$articulo = Articulo::with('sat_producto:clave,descripcion', 'sat_unidad:clave,descripcion')->findOrFail($id);
return view('panel.configuracion.articulo', [
'id' => $id,
'presentaciones' => Presentacion::select('nombre')->get()->toArray(),
'impuestos_compra' => Impuesto::where('tipo' , 'compra')->pluck('abreviacion')->toArray(),
]);
}

Trying to get property of non-object when display value of json response in Laravel

i try to display the value of json response . Its work well when I dd #php dd( $user->irel__com_access_level->ID); #endphp inside blade view but when i try to display at table it return error which is
Trying to get property of non-object
My code display in table
#foreach($content as $user)
<td>{{ $user->irel__com_access_level->ID }}</td>
#endforeach
Here is my json response ....i want to display ID which is inside irel__com_access_level
{
"data": [
{
{
"ID": "banana",
"PWD": "W6ph5Mm5Pz8GgiULbPgzG37mj9g=",
"NICK_NAME": "BANANA NANA NA",
"PWD_INVALID_HIT": "0",
"PWD_CREATE_DT": "2019/09/06 16:44:40",
"INSTITUTION_ID": "C01",
"ACL_ID": "L03",
"LOGIN_DT": " ",
"LOGIN_STS_ID": "N",
"STS_ID": "C03",
"TYPE_ID": "U00",
"UPD_ID": "asmidah",
"UPD_DT": "2019/09/06 16:44:40",
"EMAIL_ID": "banana#gmail.com",
"PHONE_NO_ID": "0",
"HP_ID": "0101234567 ",
"CRT_DATE_DELETED": "2019/09/06 16:44:40",
"irel__com_access_level": {
"ID": "L03", // i want to display this
"DESCRIPTION": "2NDLEVEL",
"IS_CREATE": "N",
"IS_READ": "Y",
"IS_UPDATE": "Y",
"IS_DELETE": "N",
"STS_ID": "R01",
"UPD_ID": "shukrimb",
"UPD_DT": "2012/09/13 13:28:25"
}
my controller
private $client;
public function __construct(){
$this->client = new Client(['base_uri' => 'http://172.19.52.6/api/configuration/getUserIndex']);
}
public function index()
{
$response = $this->client->get('getUserIndex');
$content = json_decode($response->getBody());
return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data]);
i want to display ID which is inside irel__com_access_level in json response
Try this
return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data->first()]);
or
return view('configuration.comuserprofiles.ComUserProfilesList', ['content' => $content->data()->first()]);
Just already solved this answer by adding isset
<td> #if(isset($user->irel__com_access_level))
#if(trim($user->ACL_ID) == trim($user->irel__com_access_level->ID))
{{ $user->irel__com_access_level->DESCRIPTION }}
#endif
#endif
</td>

Angular, connect objects and display right information

I'm creating an angular webapp, listing different cars in a sidebar and some information about the specific car in a informationbox.
The purpose is to show the right information in the box when clicking the different cars.
I have two different arrays(two API-endpoints), where the first array lists the car name, and the other one got the information about the car. But I have no idea how to connect the objects with the primary key and the foreign key, and how I'm supposed to output the right information after clicking the car.
app.js:
angular.module('myApp', [])
.controller('MyController', function($scope, $http) {
function fetch() {
$http({method : 'GET',url : 'http://*cars*'})
.success(function(data) {
$scope.cars = data;
});
$http({method : 'GET',url : 'http://*information*'})
.success(function(data) {
$scope.information = data;
});
}
fetch();
})
html:
<div id="sidebar">
<ul>
<li ng-repeat="name in cars">{{ name.displayName }}</li>
</ul>
</div>
For now all I have done is that I've fetched the data and outputed the cars in the sidebar. But now I've been googling and trying to connect the cars to the information with loops and functions for hours, but stil clueless.
Yes, I'm new to this. Any kind of help would be great! Thanks
You can deal with this with the ng-route. You can do something like :
In your route definition:
.when(/cars/:Id), {
name: 'cars',
templateUrl : 'ayourtemplate.html',
controller : 'yourCtrl'
})
In your html:
<div id="sidebar">
<ul>
<li ng-repeat="name in cars">{{ name.displayName }}</li>
</ul>
</div>
The Id will be your key tou will just have to match the right key in your $scope.information
It depends on what information those arrays contains.
If you're sure, that every element corresponds to other, you can just use $index in the html.
<li ng-repeat="name in cars">
{{ name.displayName }}
<p>{{ information[$index] }}</p>
</li>
However, if elements in array aren't ordered, you will have to check primary keys of objects in arrays. Let's assume, that data in arrays looks like this:
cars:
[
{ id: "1", name: "Carrera GT" },
{ id: "2", name: "DB 11" },
... and so on
]
information:
[
{ id: "2", info: "Lorem ipsum" },
{ id: "1", info: "Dolor sit amet" },
...
]
Then I'd suggest using loops and constructing new array using ids.
var carinfo = [];
cars.forEach(car => {
obj["id"] = car.id;
obj["name"] = car.name;
obj["info"] = ""; // Placeholder
info.forEach(c => {
if (c.id === car.id) {
obj["info"] = c.info;
}
});
carinfo.push(obj);
});
$scope.carInfo = carinfo;
Then you can use $scope.carInfo in the html file.
<li ng-repeat="car in carInfo">
{{ car.name }}
<p>{{ car.info }}</p>
</li>

Yii2 Assigning Selected value on Dependant Dropdown

In Yii2 i have a form with 2 dependant dropdowns on selection of both a div containing details displays. I have to assign selected value if it is provided and i have assigned one of the dropdown with it, Question is how to assign the second dropdown with selected value.
<div class="col-sm-6">
<?= $form->field($SasModel, 'all_batch_id')->dropDownList(ArrayHelper::map(app\modules\course\models\Batches::find()->where(['is_status' => 0])->all(),'batch_id','batch_name', 'batchCourse.course_name'),
[
'options' => [$_GET['batchid'] => ['Selected'=>'selected']],
'prompt'=>'Select Batch',
'onchange'=>'
$.get( "'.Url::toRoute('subjectsallocatesem/studsection').'", { id: $(this).val() } )
.done(function( data ) {
$( "#'.Html::getInputId($SasModel, 'semester_id').'" ).html( data );
}
);
'
]);
?>
</div>
<div class="col-md-6">
<?= $form->field($SasModel, 'semester_id')->dropDownList(
[ 'prompt'=>'---Select Semester---' ],
[ 'onchange'=>'this.form.submit()' ]
); ?>
</div>
Create method in Semester model:
public static function getBatchSemster( $batch_id = NULL)
{
if(!empty($batch_id)) {
$semester = self::find()->andWhere(['batch_id_in_semester_model' => $batch_id])->all();
$results = yii\helpers\ArrayHelper::map($semester, 'sem_id', 'sem_name');
return $results;
}
else {
return $results[];
}
}
Change Form:
<div class="col-md-6">
<?= $form->field($SasModel, 'semester_id')->dropDownList(SemesterModel::getBatchSemster($SasModel->all_batch_id),
[ 'prompt'=>'---Select Semester---' ],
[ 'onchange'=>'this.form.submit()' ],
); ?>
</div>

Populating HTML with JSON data using jQuery

I am trying to dynamically create a list of applicants in my HTML. I have a list of applicant saved in JSON format that I am reading in. I have an HTML template of the applicant "tile" that I read in, populate and then append to the page for each applicant.
My template:
<div>
<div class="name"></div>
<div class="age"></div>
<div class="gender"></div>
<div class="email"><i class="fa fa-envelope"></i></div>
</div>
My JSON data:
{
"applicants" : [
{
"name" : "John Smith",
"email" : "email#gmail.com",
"gender" : "Male",
"age" : "22"
}
]
}
My jQuery:
$.get("applicants.json", function(json) {
json.applicants.forEach(function(applicant) {
var newApplicant = $(templates).find("#applicant").html();
$(newApplicant).find(".name").append(applicant.name);
$(newApplicant).find(".email").append(applicant.email);
$(newApplicant).find(".gender").append(applicant.gender);
$(newApplicant).find(".age").append(applicant.age);
$(newApplicant).appendTo(".applicant-list");
});
});
After running this code, I am just getting the template back without the JSON information.
I have tried placing a console.log() after appending applicant.name but there is still no change to newApplicant.
Something else I tried was console.log($(newApplicant).find(".name").append(applicant.name).html()); which showed me that the .name is being populated but those changes are not persisting.
Can anyone see what I am doing wrong?
Thanks.
I am not sure if forEach would be a right one. You can use jQuery's $.each function to loop in an array with this being referred as the current iterated object:
$.each(json.applicants, function () {
var newApplicant = $("body").find("#applicant > div").clone();
newApplicant.find(".name").append(this.name);
newApplicant.find(".email").append(this.email);
newApplicant.find(".gender").append(this.gender);
newApplicant.find(".age").append(this.age);
$(newApplicant).appendTo(".applicant-list");
});
Snippet
$(function () {
json = {
"applicants" : [
{
"name" : "Nicholas Robinson",
"email" : "ntrpilot#gmail.com",
"gender" : "Male",
"age" : "22"
}
]
};
$.each(json.applicants, function () {
var newApplicant = $("body").find("#applicant > div").clone();
newApplicant.find(".name").append(this.name);
newApplicant.find(".email").append(this.email);
newApplicant.find(".gender").append(this.gender);
newApplicant.find(".age").append(this.age);
$(newApplicant).appendTo(".applicant-list");
});
});
<script src="https://code.jquery.com/jquery-1.9.1.js"></script>
<div id="applicant">
<div>
<div class="name"></div>
<div class="age"></div>
<div class="gender"></div>
<div class="email"><i class="fa fa-envelope"></i></div>
</div>
</div>
<div class="applicant-list"></div>
In the question you omitted two HTML elements that instead you mention in the jQuery code, so according to the latter, and correct me if I'm wrong, the HTML should look like that
<div class="applicant-list">
<div class="applicant">
<div class="name"></div>
<div class="age"></div>
<div class="gender"></div>
<div class="email"><i class="fa fa-envelope"></i></div>
</div>
</div>
Then, in the jQuery you should either use your $.get() function and then parse or use instead $.getJSON()
$.getJSON("applicants.json", function(json) {
json.applicants.forEach(function(applicant) {
var newApplicant = $('body').find(".applicant").clone();
$(newApplicant).find(".name").append(applicant.name);
$(newApplicant).find(".email").append(applicant.email);
$(newApplicant).find(".gender").append(applicant.gender);
$(newApplicant).find(".age").append(applicant.age);
$(newApplicant).appendTo(".applicant-list");
});
});

Categories