In my HTML :
<input type="text" ng-model="data.price" placeholder="Position" required/>
<button type="submit" ng-click="validate(data)">Save</button>
In my controllers.js :
$scope.validate = function(data){
$http.post(
'http://mysitename.com/folder/controller/method',
{
price: data.price
}
)
.success(function(res){
console.log(res);
})
.error(function(res){
console.log("Error: " + res);
});
}
In my Controller.php :
public function method() {
if($postdata = file_get_contents("php://input")) {
$this->form_validation->set_rules(??????, 'Price', 'required|is_money|trim');
if ($this->form_validation->run() == FALSE)
{
echo json_encode(validation_errors());
} else {
echo json_encode("working");
}
}
}
What should I put in my $this->form_validation->set_rules(??????, ' Price', 'required|is_money|trim'); ?
Any help is highly appreciated. Thanks :)
Related
this.row is Generating form input into JSON Array which I'm trying to post via submit function using Axios but unable to the value please help what's wrong ??
Axios postcode
axios.post('/submit', this.rows).then(response => {
this.rows; //Clear input fields.
this.loaded = true;
Here is my complete code
<template>
<form #submit.prevent="submit">
{{ /* These are 3 buttons which are calling 3 different function to create input boxes */ }}
<div class="d-flex mt-5"><div>
<label>Add A</label>
<button type="button" #click="addRow">01</button>
</div>
<div> <label>Add B</label>
<button type="button" #click="addRow1">02</button>
</div>
<div> <label>Add c</label>
<button type="button" #click="addRow3">03</button>
</div>
</div>
{{ /* this section calls button-counter template from script code */ }}
<div v-for="row in rows" :key="row.id">
<button-counter :name ="row.name" :id="row.id" :value.sync="row.value"></button-counter>
</div>
<div>
<button type="submit" class="btn btn-primary">Add Points</button>
</div>
<div v-if="success" class="alert alert-success mt-3">
Message sent!
</div>
</form>
</template>
<script>
Vue.component("button-counter", {
props: {
value: {
default: "",
}
},
/* This is my template which gets called fro the addition of new inputs ...guess here I need to add v-model so that dynamically generated fields will be posted but I'm unable to get it posted */
template: '<input class="form-control" id= id.row name=row.name type="number" style="margin-top: 10px;" :value="value" #change="$emit(\'update:value\', $event.target.value)">'
});
export default {
props: ['gameId','userId'],
mounted() {
console.log('Component mounted.')
},
data() {
return {
gamex: this.gameId,
rows: [],
count: 0,
fields: {},
errors: {},
success: false,
loaded: true,
};
},
computed: {
total() {
if (this.rows.length) {
return this.rows.reduce((acc, row) => acc += parseInt(row.value), 0);
}
return 0;
}
},
methods: {
addRow: function() {
var txtCount = 1;
let id = "txt_" + txtCount;
this.rows.push({ name:'zero',value:100, description: "textbox1", id });
},
addRow1: function() {
var txtCount = 1;
let id = "txt2_" + txtCount;
this.rows.push({name:'one',value:200, description: "textbox2", id });
},
addRow3: function() {
var txtCount = 1;
let id = "txt3_" + txtCount;
this.rows.push({name:'two',value:300, description: "textbox3", id });
},
submit: function() {
if (this.loaded) {
this.loaded = false;
this.success = false;
this.errors = {};
axios.post('/submit', this.rows).then(response => {
this.rows; //Clear input fields.
this.loaded = true;
this.success = true;
}).catch(error => {
this.loaded = true;
if (error.response.status === 422) {
this.errors = error.response.data.errors || {};
}
});
}
},
followUser() {
axios.post('/chklet/' + this.userId)
.then(response => {
return response.data ;
});
}
},
mounted () {
this.followUser();
}
};
</script>
You can use JSON.stringify(array_to_convert_in_string_to_send_in_ajax) but you will have to json_decode it also in backend server
In server section for example laravel:
$result = json_decode($request->your_array);
Can you guys tell me what i'm doing wrong here in my code? I tried to post the data inside these checkboxes to database
here is the view.php
(more code)
<div class="form-group">
<label class="control-label col-md-3">Infection</label>
<div class="col-md-9">
<input type="checkbox" name="infectionType[]" value="vap"> VAP
<input type="checkbox" name="infectionType[]" value="hap"> HAP
<input type="checkbox" name="infectionType[]" value="isk"> ISK
<input type="checkbox" name="infectionType[]" value="iad"> IAD
</div>
</div>
and this is my controller.php
public function insert_surveilance(){
$data=array(
(more code)
'vap' => $this->input->post('vap'),
'hap' => $this->input->post('hap'),
'isk' => $this->input->post('isk'),
'iad' => $this->input->post('iad'),
(more code)
);
$data[]=
$insert = $this->surveilance_model->insert_surveilance($data);
echo json_encode(array("status"=>TRUE));
}
then this is my model.php
public function insert_surveilance($data){
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
this is the save function
...
function save(){
var url;
if(save_method == 'add'){
url="<?php echo site_url('surveilance/insert_surveilance')?>";
} else {
url="<?php echo site_url('surveilance/edit_surveilance')?>";
}
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
//if success close modal and reload ajax table
$('#modal_form').modal('hide');
location.reload();// for reload a page
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Failed adding data');
}
});
}
First of all var_dump($this->input->post()) in your controller, if it shows post data then try replacing below code.
public function insert_surveilance(){
$request_params = $this->input->post('infectionType');
$data=array(
(more code)
'vap' => $request_params[0],
'hap' => $request_params[1],
'isk' => $request_params[2],
'iad' => $request_params[3],
(more code)
);
$data[]=
$insert = $this->surveilance_model->insert_surveilance($data);
echo json_encode(array("status"=>TRUE));
}
I try to push an object into an Array in mongoose, but whenever i do it, it puts its length like this(mongoose, the attribute is schoolComment at the bottom), I am using mlab.com for database.
{
"_id": {
"$oid": "58e17ee3e24dfb1f70d76460"
},
"schoolName": "Koc Universitesi",
"schoolIlce": "Sariyer",
"schoolSehir": "Istanbul",
"schoolId": 981299,
"__v": 5,
"schoolComments": [
3
]
}
this is my code in node JS (The comments are not appearing in html because of this reason)
app.post('/comment', function(req, res){
if(req.session.user && req.session){
User.findOne({email: req.session.user.email}, function(err, user){
if(err) {
res.send('error');
}
if(user){
if(req.session.user.password === user.password){
var thisID = user.userid;
Universite.findOne({schoolName: req.body.collegeName}, function(err, college){
if(err) res.send('error');
if(college){
college.set({schoolComments: college.schoolComments.push({thisID: req.body.comment})}).save(function(err){
if(err){
res.render('errors', {error:'Error'});
}else{
res.locals.college = college;
res.locals.user = user;
res.render('universiteinfoUser');
}
});
}
});
}else{
res.render('login', {});
}
}
});
}
});
and this is HTML DOM Form for it. The comments are not appearing because of this reasons.
<form onkeypress="enterPress();" action="/comment" method="post">
<textarea maxlength="100" style="font-size: 25px;" name="comment" rows="3" cols="50" placeholder="Yorumunuzu yazin..."></textarea><br>
<input style="display: none; visibility: hidden;" type="text" name="collegeName" value="<%=college.schoolName%>"></input>
<button type="submit" name="commentSubmit">Comment Submit</button>
</form>
<div class="userCommentDisplay">
<ul>
<%college.schoolComments.forEach(function(item, i){%>
<%var k = college.schoolComments[i]%>
<%for(key in k){%>
<%if(key === user.userid){%>
<li><%=k[key]%> Same</li>
<%}else{%>
<li><%=k[key]%></li>
<%}%>
<%}%>
<%})%>
</ul>
</div>
You may want to use findOneAndUpdate and build your comment item dynamically (to set the dynamic field name) :
var item = {};
item[user.userid] = req.body.comment;
Universite.findOneAndUpdate({
schoolName: req.body.collegeName
}, {
$push: {
"schoolComments": item
}
}, { new: true }, function(err, college) {
if (err) {
res.render('errors', { error: 'Error' });
} else {
res.locals.college = college;
res.locals.user = user;
res.render('universiteinfoUser');
}
});
Note that I've aded { new: true } in order to return the modified document college instead of the unaltered one.
FYI, in your code, you have used JS method Array.prototype.push() that will return the new length of the array by using college.schoolComments.push
I was looking for a working solution to get autocomplete/typeahead with angularjs&bootstrap on elasticsearch server.
This is a working solution, not a question, but I want to share it hope it will help:
the html code to call the autocomplete function :
<input required type="text"
popover-trigger="focus"
placeholder="recherche globale"
class="form-control"
ng-model="simplequeryInput"
ng-model-onblur focus-on="focusMe"
ng-click="searchSimple=true" ng-keyup="$event.keyCode == 13 ? submitSimple() : null"
typeahead="item for item in autocomplete($viewValue) | limitTo:15 "
typeahead-on-select="simplequeryInput=$model"
/>
Include the elasticsearch (v2.4.0) script
available here
my elasticsearch service
interfaceApp.service('elasticQuery', function ($rootScope,esFactory) {
return esFactory({ host: $rootScope.elastic_host}); //'localhost:9200'
});
angularjs code querying elasticsearch :
'use strict';
var searchModules = angular.module('searchModules', ['ngRoute','ngDialog']);
searchModules.controller('searchCtrl', function (ngDialog,$scope, $http,$rootScope, elasticQuery) {
...
$scope.autocomplete = function(val) {
var keywords = [];
keywords.push(val);
// THIS RETURN IS VERY IMPORTANT
return elasticQuery.search({
index: 'YOUR_INDEX_NAME',
size: 15,
body: {
"fields" : ["T_FAMILY","T_GENUS","T_SCIENTIFICNAME"], // the fields you need
"query" : {
"bool" : {
"must" : [
{
"query_string" : {
"query" : "T_FAMILY:"+val // i want only source where FAMILY == val
}
}
]
}
}
}
}).then(function (response) {
for (var i in response.hits.hits) {
var fields = (response.hits.hits[i]).fields;
var tmpObject = fields["T_FAMILY"] +" " + fields["T_GENUS"] + " ( "+fields["T_SCIENTIFICNAME"] + " )";
keywords.push(tmpObject);
}
return keywords;
});
}
});
hope it helps
Im working on a small project, and i have a problem with model binding. I'm using the Backbone.ModelBinder plugin for binding a model.
I'm checking changes on inputs, and get the name of the model attribute from the input data-name field. After that i check the changed data and do some stuff on the model. I have a function ChangeGuest and inside that im checking my model's (Nyiltnap.Reg) changes.
The problem is, this Nyiltnap.Reg.on("change:"+field ...){ ... } function runs as many times as many changes were made on the field named input.
Maybe i'm doing something wrong, or i missed something.
ItemView:
define(['text!templates/FormCompositeView.html', 'text!templates/EventIsFull.html', 'text!templates/ThankYou.html', 'models/RegModel'], function(Template, FullTemplate, ThankYou, Model) {
var FormCompositeView = Backbone.Marionette.ItemView.extend({
_modelBinder:undefined,
initialize: function() {
this.members = parseInt(Nyiltnap.Reg.get("members"));
this._modelBinder = new Backbone.ModelBinder();
var that = this;
Nyiltnap.Reg.on("change:name", function(r) { //HERE CHANGE TRIGGERS ONLY ONCE
if( ! _.has(r._previousAttributes, "name") ){
that.IncreaseMembers();
if(that.members < 10) that.$('.guest').attr("disabled", false);
if(that.$('#email').val() != '') that.$("#send-button").attr("disabled", false);
}
if( _.has(r._previousAttributes, "name") && r.changed.name == "" ){
that.DecreaseMembers();
Nyiltnap.Reg.unset("name");
that.$('.guest').attr("disabled", true);
that.$("#send-button").attr("disabled", true);
}
});
Nyiltnap.Reg.on("change:email", function(r) {
if( ! _.has(r._previousAttributes, "email") ){
if(that.$('#name').val() != '') that.$("#send-button").attr("disabled", false);
}
if( _.has(r._previousAttributes, "email") && r.changed.email == "" ){
that.$("#send-button").attr("disabled", true);
}
});
},
getTemplate: function() {
if( this.members < 10 ){
return _.template(Template);
}else{
return _.template(FullTemplate);
}
},
tagName: "ul",
id: "nyiltnap-form",
onRender: function() {
var MainBindings = {name : "[name=rname]", email : "#email", source : "#source", coupon : "#coupon", guest_1 : "#guest-1", guest_2 : "#guest-2", guest_3 : "#guest-3", guest_4 : "#guest-4", guest_5 : "#guest-5", guest_6 : "#guest-6", guest_7 : "#guest-7", guest_8 : "#guest-8", guest_9 : "#guest-9"};
if(this.members < 10) this._modelBinder.bind(Nyiltnap.Reg, this.el, MainBindings);
return this;
},
events: {
"change .guest" : "ChangeGuest",
"click #send-button" : "SendReg"
},
ChangeGuest: function(o) { //I WOULD LIKE TO MAKE THIS WORK
var that = this;
var field = $(o.target).data('name');
Nyiltnap.Reg.on("change:"+field, function(r) { //THIS RUNS AS MANY TIMES AS THE CONTENT OF THE 'field' HAS BEEN CHANGED
if( ! _.has(r._previousAttributes, field) ) {
that.IncreaseMembers();
that.AddInput(o);
}else{
if(_.has(r._previousAttributes, field) && _.result(r.changed, field) == ""){
that.DecreaseMembers();
}
}
});
},
IncreaseMembers: function() {
this.members++;
Nyiltnap.Reg.set("members", this.members);
Nyiltnap.vent.trigger("members:changed", this.members);
},
DecreaseMembers: function() {
this.members--;
Nyiltnap.Reg.set("members", this.members);
Nyiltnap.vent.trigger("members:changed", this.members);
},
AddInput : function(o) {
var target = $(o.target);
if(this.members < 9) target.next().next().slideDown();
}
});
return FormCompositeView;
});
Template:
<li>
<label for="guest1">My guests: </label>
<div id="guests">
<input name="guest-1" data-name="guest_1" id="guest-1" class="guest" type="text" disabled="disabled"/>
<input name="guest-2" data-name="guest_2" id="guest-2" class="guest" type="text" disabled="disabled"/>
<input name="guest-3" data-name="guest_3" id="guest-3" class="guest" style="display: none" type="text" />
<input name="guest-4" data-name="guest_4" id="guest-4" class="guest" style="display: none" type="text" />
<input name="guest-5" data-name="guest_5" id="guest-5" class="guest" style="display: none" type="text" />
<input name="guest-6" data-name="guest_6" id="guest-6" class="guest" style="display: none" type="text" />
<input name="guest-7" data-name="guest_7" id="guest-7" class="guest" style="display: none" type="text" />
<input name="guest-8" data-name="guest_8" id="guest-8" class="guest" style="display: none" type="text" />
<input name="guest-9" data-name="guest_9" id="guest-9" class="guest" style="display: none" type="text" />
<div class="clear"></div>
</div>
<div class="clear"></div>
</li>