So I'm using angularjs/SQL technique to retrieve data from a database like so:
$http.get("retrieveData.php").then(function(response){
$scope.tasks = response.data.tasks;
})
Then I have a function that allows me to use a form to insert new data into a database:
$scope.submitTask = function(){
var description = document.getElementById("typeDescription").value;
var todayDate = document.getElementById("todayDate").value;
try{
reminder = document.getElementById("reminder").value;
}
catch(err){
reminder = "NONE";
}
var status = document.getElementsByName("selectStatus");
var statusValue;
for(i=0;i<status.length;i++){
if(status[i].checked){
statusValue = status[i].value;
}
}
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("msg").innerHTML = this.responseText;
}
};
xhttp.open("POST", "enterTask.php");
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("desc="+description+"&status="+statusValue+"&reminder="+reminder+"&todayDate="+todayDate);
}
I'm sure my first problem is that I'm using JavaScript's AJAX instead of Angular's? But I don't know how to convert it.
Even so, I don't know how to then update the $scope.tasks.
I've looked online how to POST using Angular and haven't been able to find much. Just the tutorial on how to get.
Please don't give any JQuery. I am using pure JavaScript, thank you.
Thanks to some help I've restructured my code a bit (still mixing JavaScript but I plan to research Angular forms). Here is what I have now.
$http.get("retrieveData.php").then(function(response){
$scope.tasks = response.data.tasks;
})
$scope.submitTask = function(){
var description = document.getElementById("typeDescription").value;
var todayDate = document.getElementById("todayDate").value;
try{
reminder = document.getElementById("reminder").value;
}
catch(err){
reminder = "NONE";
}
var status = document.getElementsByName("selectStatus");
var statusValue;
for(i=0;i<status.length;i++){
if(status[i].checked){
statusValue = status[i].value;
}
}
var task = {
desc:description,
status:statusValue,
reminder:reminder,
todayDate: todayDate
}
$http.post('enterTask.php', task).then(
function(response){
$scope.tasks.push(task);
}
);
}
});
For some reason though, my $scope.tasks is still not updating after I add to the element. If I add an element to an empty database I get an angular error in my console.
TypeError: Cannot read property 'push' of undefined
Sooo. Not sure why this is.
When I alert the $scope.tasks after the push, it alerts 1 less than it should actually contain after push (once there is 1 or more elements in database to not produce above error).
Here is my HTML, maybe it has something to do with it?
<ul>
<li ng-repeat="x in tasks" ng-bind="x.Description"></li>
</ul>
<form>
<input type="text" value="{{today}}" id="todayDate">
<textarea rows="15" cols="100" name="typeDescription" id="typeDescription"></textarea>
<input type="checkbox" ng-model="setReminder" name="setReminder">Set Reminder
<input type="date" name="reminder" id="reminder" ng-if="setReminder"><br>
<input type="radio" name="selectStatus" value="CR">Client Response
<input type="radio" name="selectStatus" value="IR">Internal Response
<input type="radio" name="selectStatus" value="BD">BD Control
<input type="radio" name="selectStatus" value="OC">On Calendar<br>
<input type="submit" ng-click="submitTask();">
</form>
Also my php...
<?php
/*$description = json_decode($_POST['desc']);
$reminder = json_decode($_POST['reminder']);
$todayDate = json_decode($_POST['todayDate']);
$status = json_decode($POST['status']);*/
$data = json_decode(file_get_contents("php://input"));
$description = $data->desc;
$reminder = $data->reminder;
$todayDate = $data->todayDate;
$status = $data->status;
require 'databaseConnect.php';
$query="INSERT INTO TaskTracker (DATESTAMP,STATUS,DESCRIPTION,REMINDER) VALUES ('$todayDate','$status','$description','$reminder')";
mysql_query($query) or die(mysql_error());
?>
The commented out part wasn't working so then I used the file_get_contents bit.
In angular js posting data is very easy and it can be done in just 2 to 3 lines of code.
//first lets collect your data in an Object
var data = {
desc: description,
status: statusValue,
reminder: reminder,
todayDate: todayDate
}
//then send collected data using $http service
$http.post('enterTask.php',data).then(function(response){
$scope.tasks.push(data);//After successful HTTP request you push the data to your $scope.task array
})
You have to "tackle" some points to get the submitTask function into an angular way of thinking.
Use ng-model data binding from the input elements to the $scope. There are several tutorials out there. By using this you can get rid of the whole getElementById stuff.
Use $http.post to send the data over the wire.
Update the $scope.tasks array by simply adding/removing elements. The two way data bindung of angular will do the update for you in e.g. via ng-repeat
For the last to points I sketched the JavaScript code for you.
$scope.submitTask = function(){
var description = document.getElementById("typeDescription").value;
var todayDate = document.getElementById("todayDate").value;
try{
reminder = document.getElementById("reminder").value;
}
catch(err){
reminder = "NONE";
}
var status = document.getElementsByName("selectStatus");
var statusValue;
for(i=0;i<status.length;i++){
if(status[i].checked){
statusValue = status[i].value;
}
}
var task = {
desc: description,
status: statusValue,
reminder: reminder,
todayDate: todayDate
}
$http.post('enterTask.php', task).then(
function (response) {
$scope.tasks.push(task);
}
);
}
Related
enter image description hereWhat I'm trying is fetching columns from the user to which the user entered, The Good thing is Columns are getting fetched and the bad thing is the columns that I had applied conditions are not working.Can anyone help me out? I want a query that works for the filter option as in many websites to filter any product or something.
Newbie here!!!
routes.post('/FilterCandidate',function(req,res){
var fetchparameter={};
var dynamicquery={author : req.user.username};
if(req.user.username){
if(req.body.ConsultantName){
fetchparameter["ConsultantName"] = req.body.ConsultantName;
}
if(req.body.Location){
fetchparameter["Location"] = req.body.Location;
}
if(req.body.JobRole){
fetchparameter["JobRole"] = req.body.JobRole;
}
if(req.body.Skills){
fetchparameter["Skills"] = req.body.Skills.split(',');
}
if(req.body.VisaStatus){
fetchparameter["VisaStatus"] = req.body.VisaStatus;
}
if(req.body.BillingRate){
fetchparameter["BillingRate"] = req.body.BillingRate;
}
if(req.body.experience){
fetchparameter["experience"] = req.body.experience;
}
if(req.body.jobtype){
fetchparameter["jobtype"] = req.body.jobtype;
}
if(req.body.Availability){
fetchparameter["Availability"] = req.body.Availability;
}
if(req.body.experience){
fetchparameter["Salary"] = req.body.Salary;
}
if(req.body.Salarytype){
fetchparameter["Salarytype"] = req.body.Salarytype;
}
}
/* This below code for conditions is not working*/
for(var key in fetchparameter){
if (key== "Salary" ){
dynamicquery[key] = {$gte :fetchparameter[key]};
}
if(key == "Skills"){
dynamicquery [key] = {$in : fetchparameter[key]};
}
if(key == "experience"){
dynamicquery[key] = {$gte :fetchparameter[key]};
}
else{
dynamicquery[key] = fetchparameter[key];
}
}
console.log(dynamicquery);
Candidate.aggregate([ {$match : dynamicquery }],(err,docs) =>{
res.render('FilteredCandidate',{'Candidates' : docs});
});
});
This is what I'm getting output to refer to the attached image
i think you should make a match object array it will make your code more neat and hoping that it will solve your problem
Ex:
var match = {$and:[]};
if(any condition satisfy){
match.$and.push({}) //condition
}
and most important do check if match.$and array must not be empty if it is then delete match.$and. this procedure will help you to maintain your query better provides more flexibility.
I am working on a Javascript that aims to return then manipulate an object from a clicked button. I am now stuck how can i get its object then process it on a post method. On my button I have this:
<button type="submit" name="submit" form="form-add" id="export-btn" class="btn btn-small" style="border-radius: 0;"><i class="fas fa-save"></i><span class="button-save"></span>Save</button>
and i have this javascript method:
<script type="text/javascript">
var $TABLE = $('#table');
var $BTN = $('#export-btn');
var $EXPORT = $('#export');
...
// A few jQuery helpers for exporting only
jQuery.fn.pop = [].pop;
jQuery.fn.shift = [].shift;
$BTN.click(function () {
var $rows = $TABLE.find('tr:not(:hidden)');
var headers = [];
var data = [];
// Get the headers (add special header logic here)
$($rows.shift()).find('th:not(:empty)').each(function () {
headers.push($(this).text().toLowerCase());
});
// Turn all existing rows into a loopable array
$rows.each(function () {
var $td = $(this).find('td');
var h = {};
// Use the headers from earlier to name our hash keys
headers.forEach(function (header, i) {
h[header] = $td.eq(i).text();
});
data.push(h);
});
// Output the result
$EXPORT.text(JSON.stringify(data));
return data;
});
</script>
and on top of my page I have this:
if(isset($_POST['submit'])){
echo "Test";
// Process here the object
}
but How can i access those data, since $EXPORT.text(JSON.stringify(data)); output a JSON, that looks like this [{"id":"1","Val":"Sample","data":"Sample Date"}] on my paragraph tag.
You can't post data from paragraph.
Create hidden input in the form and assign the data to it.
$(this).append($("<input />", { name : "foo", value : data, type : "hidden" }))
How can I receive the values of the radio buttons and a select list and put it on the file name?
This is the function that will be using the values :
router.get('/import', function(req, res, next) {
var csvStream = fastCsv()
.on('data', function(data) {
var report = new csvUploads({
jirakey: data[0],
status: data[1],
priority: data[2],
validity: data[3],
type: data[4],
month: data[5],
defectCategory: data[6],
defectSubCategory: data[7]
});
report.save(function(error) {
console.log(report);
if (error) {
throw error;
}
});
}).on('end', function() {});
const request = req.body;
let month = req.month;
let team = req.team;
const filename = month + ' - ' + team + '.csv';
console.log(res.send(filename));
const csvFilePath = "./uploads/" + filename;
var stream = fs.createReadStream(csvFilePath);
stream.pipe(csvStream);
res.json({
success: 'Data imported successfully',
status: 200
});
});
Currently this is what I have tried, it returns undefined in both the radio button and select list value
instead of
const request = req.body;
let month = req.month;
let team = req.team;
try
const request = req.body;
let month = request.month;
let team = request.team;
I would suggest that you simply serve the view (importer.html) and use it as as a client for your server (using POST), that way you may interact with the server and display the changes/retrieved data back in the client.
You will be needing :
GET route for displaying the "client".
POST route for using the "client submitted data and crafting an
adecuate response".
Client logic for doing something when the server replies.
Hope this proof-of-concept (working example) will help you understand better :
SERVER CODE
const express = require('express'); global.app = express()
const bodyParser = require('body-parser')
/* SETUP SERVER CONFIG OPTIONS */
const CONF = {
"htmlDir":__dirname+"/",
"port":3000
}
//----------------------------------------------------------
//.: Server StratUp : Setup Event Handling :.
function InitializeServer(){
console.log("[~] starting ...")
//:[EXPRESS]:MiddleWare
app.use(bodyParser.urlencoded({extended:false}))
app.use(bodyParser.json())
//:[EXPRESS]:Router (GET Requests)
app.get("/",RenderImport)
//:[EXPRESS]:Router (POST Requests)
app.post("/import",ImportRequest)
//:[EXPRESS]:Start
app.listen(CONF.port,onSuccessfullStartup)
}
/* Callback example for express successfully listening */
const onSuccessfullStartup=()=>{
console.log("[i] ready & listening","\n http://localhost:"+CONF.port+"/")
}
//----------------------------------------------------------
/* ROUTER EVENT FUNCTIONS : */
const RenderImport=(req,res)=>{res.sendFile(CONF.htmlDir+"importer.html")}
const ImportRequest=(req,res)=>{
console.log("[POST] /import")
console.log(req.body)
if(req.body.stringExample&&req.body.selectExample&&req.body.radioExample){
console.log(" > valid POSTData")
var doSomethingNow={"status":"OK","data":[1,2,3,4,5]}
res.json(doSomethingNow)
}else{
console.log(" > invalid POSTData")
res.json({"status":"ERROR"})
}
}
//----------------------------------------------------------
InitializeServer() // We can now start the server
CLIENT CODE (importer.html)
<html><head><title>INDEX</title></head><body>
<center>
<h1>SEND DATA TO SERVER</h1>
<form name="theForm">
<!-- String Example -->
<input name="stringExample" type="text"></input>
<!-- Select Example -->
<select name="selectExample">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<select>
<!-- Radio Example -->
<input type="radio" name="radioExample" value="a" checked> One
<input type="radio" name="radioExample" value="b" > Other
<input type="radio" name="radioExample" value="c" > Another
</form>
<button onclick="SEND()">SEND</button>
</center>
<script>
function SEND(){
var newXHR = new XMLHttpRequest();
newXHR.addEventListener("load",RequestDone);
newXHR.open("POST","/import");
newXHR.setRequestHeader('Content-Type', 'application/json;charset=UTF-8')
//Fetch Form Data
var form = document.theForm;
var inputx = form.elements["stringExample"];
var select = form.elements["selectExample"];
var radios = form.elements["radioExample"];
//Data for POST
var JSONObj = {}
JSONObj.stringExample = inputx.value
JSONObj.selectExample = select.value
JSONObj.radioExample = radios.value
console.log(JSONObj);
//Format Data for POST
var POSTData = JSON.stringify(JSONObj);
newXHR.send(POSTData);
}
function RequestDone(req){
var res = JSON.parse(req.target.response); console.log(res)
if(res.status=="OK"){alert("Succesfully Sent & Retrieved Data :\n"+res.data.toString())}
else if(res.status=="ERROR"){alert("The server received unexpected data or is missing important parameters")}
else{alert("Unexcpected Error!")}
}
</script>
</body></html>
I'm trying to bind my JSON object to a HTML div but none of the bindings seem to work. This is my current try on the subject. But I have tried using the template binding already. That resulted in an undefined error , but the object is correctly loaded because i always get it in the console.
$(document).ready(function () {
var submissionViewModel = new SubmissionModel();
submissionViewModel.getSubmission().done(function () {
ko.applyBindings(submissionViewModel, document.getElementById("submission"));
})
});
var SubmissionModel = function () {
var self = this;
//self.loading = ko.observableArray();
self.Submission = ko.observable(null);
self.getSubmission = function () {
// Let loading indicator know that there's a new loading task that ought to complete
//self.loading.push(true);
return $.getJSON('/Submission/GetSubmission',
function (data) {
console.log("submission loading")
console.dir(data);
self.Submission = ko.mapping.fromJSON(JSON.stringify(data));
}
);
}
}
HTML
<div id="submission" data-bind="with: Submission">
<span data-bind="text: SubmissionTitle"></span>
</div>
JSON
"{"
SubmissionID":"1be87a85-6d95-43aa-ad3c-ffa047b759a5",
"SubmissionTitle":"nog wat sliden",
"SubmissionDescription":"////",
"SubmissionFile":"TESTFILE ",
"CreatedOn":"2015-09-02T21:10:54.913",
"SubmissionPoolID":"5af408f5-515c-4994-88dd-dbb2e4a242a2",
"SubmissionTypeID":1,
"CreatedBy":"a028a47d-3104-4ea4-8fa6-7abbb2d69bbd
"}"
I have been chewing on this problem for a few days now an I can't seem to get it to work. Could any of you point me in the right direction ?
In java-script to decode object inside string you need to use JSON.parse and make sure your object is not structured in such way double quote inside double quote .
viewModel:
var json = '{"SubmissionID":"1be87a85-6d95-43aa-ad3c-ffa047b759a5","SubmissionTitle":"nogwatsliden","SubmissionDescription":"--","SubmissionFile":"TESTFILE ","CreatedOn":"2015-09-02T21:10:54.913","SubmissionPoolID":"5af408f5-515c-4994-88dd-dbb2e4a242a2","SubmissionTypeID":1,"CreatedBy":"a028a47d-3104-4ea48fa67abbb2d69bbd"}'
var ViewModel = function () {
this.Submission = ko.observable();
this.Submission(ko.mapping.fromJS(JSON.parse(json)));
//you can also use ko.mapping.fromJSON(json) as jeroen pointed out
};
ko.applyBindings(new ViewModel());
working sample here
I have a page where a user can select if the transaction type is an inter accounts transfer, or a payment.
The model I pass in had two lists.
One is a list of SelectListItem
One is a list of SelectListItem
One of the lists is populated like this:
var entities = new EntityService().GetEntityListByPortfolio();
foreach (var entity in entities.Where(x=>x.EntityTypeId == (int)Constants.EntityTypes.BankAccount))
{
model.BankAccounts.Add(new SelectListItem
{
Value = entity.Id.ToString(CultureInfo.InvariantCulture),
Text = entity.Description
});
}
If the user selects 'Inter account transfer', I need to:
Populate DropdownA with the list from Accounts, and populate DropdownB with the same list of Accounts
If they select "Payment", then I need to change DrowdownB to a list of ThirdParty.
Is there a way, using javascript, to change the list sources, client side?
function changeDisplay() {
var id = $('.cmbType').val();
if (id == 1) // Payment
{
$('.lstSource'). ---- data from Model.ThirdParties
} else {
$('.lstSource'). ---- data from Model.Accounts
}
}
I'd prefer not to do a call back, as I want it to be quick.
You can load the options by jquery Code is Updated
Here is the code
You will get everything about Newton Json at http://json.codeplex.com/
C# CODE
//You need to import Newtonsoft.Json
string jsonA = JsonConvert.SerializeObject(ThirdParties);
//Pass this jsonstring to the view by viewbag to the
Viewbag.jsonStringA = jsonA;
string jsonB = JsonConvert.SerializeObject(Accounts);
//Pass this jsonstring to the view by viewbag to the
Viewbag.jsonStringB = jsonB;
You will get a jsonstring like this
[{"value":"1","text":"option 1"},{"value":"2","text":"option 2"},{"value":"3","text":"option 3"}]
HTML CODE
<button onclick="loadListA();">Load A</button>
<button onclick="loadListB();">Load B</button>
<select name="" id="items">
</select>
JavaScript Code
function option(value,text){
this.val= value;
this.text = text;
}
var listA=[];
var listB=[];
//you just have to fill the listA and listB by razor Code
//#foreach (var item in Model.ThirdParties)
//{
// <text>
// listA.push(new option('#item.Value', '#item.Text'));
// </text>
// }
//#foreach (var item in Model.Accounts)
// {
// <text>
// listA.push(new option('#item.Value', '#item.Text');
// </text>
// }
listA.push(new option(1,"a"));
listA.push(new option(2,"b"));
listA.push(new option(3,"c"));
listB.push(new option(4,"x"));
listB.push(new option(5,"y"));
listB.push(new option(6,"z"));
function loadListA(){
$("#items").empty();
listA.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
function loadListB(){
$("#items").empty();
listB.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
NEW Javascript Code fpor Json
var listA=[];
var listB=[];
var jsonStringA ='[{"val":"1","text":"option 1"},{"val":"2","text":"option 2"},{"value":"3","text":"option 3"}]';
var jsonStringB ='[{"val":"4","text":"option 4"},{"val":"5","text":"option 5"},{"value":"6","text":"option 6"}]';
//you just have to fill the listA and listB by razor Code
//var jsonStringA = '#Viewbag.jsonStringA';
//var jsonStringB = '#Viewbag.jsonStringB';
listA = JSON.parse(jsonStringA);
listB = JSON.parse(jsonStringB);
function loadListA(){
$("#items").empty();
listA.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
function loadListB(){
$("#items").empty();
listB.forEach(function(obj) {
$('#items').append( $('<option></option>').val(obj.val).html(obj.text) )
});
}
Here is the fiddle http://jsfiddle.net/pratbhoir/TF9m5/1/
See the new Jsfiddle for Json http://jsfiddle.net/pratbhoir/TF9m5/3/
ofcourse you can so that
try
var newOption = "<option value='"+"1"+'>Some Text</option>";
$(".lstSource").append(newOption);
or
$(".lstSource").append($("<option value='123'>Some Text</option>");
Or
$('.lstSource').
append($("<option></option>").
attr("value", "123").
text("Some Text"));
Link for reference
B default, I don't think the concept of "data-source" means something in html/javascript
Nevertheless, the solution you're looking for is something like knockoutjs
You'll be able to bind a viewmodel to any html element, then you will be able to change the data source of your DropDownList
see : http://knockoutjs.com/documentation/selectedOptions-binding.html