My angular can't get the value from html page - javascript

I have an angular function to call me rest service but it can't get the value from the html file. when i press submit the $scope.productForm is, although i still have value in my html page.
Main.js
$scope.products = [];
$scope.productForm = {
ID:1,
Name:"",
Description:"",
URL:""
};
_refreshProductData();
//Add or Update Product
$scope.submitProduct = function() {  
var method = "";
 
if ($scope.productForm.ID == -1) {
    method = "POST";
} else {
    method = "PUT";
}
 
$http({
    method: method,
    url: '/product',
    data: angular.toJson($scope.productForm),
    headers: {
        'Content-Type': 'application/json'
    }
}).then(_success, _error);
}
index.html
<form ng-submit="submitProduct()">
    <table border="0">
        <tr>
            <td>ProductID</td>
            <td>{{productForm.ID}}</td>
        </tr>
        <tr>
            <td>Product Name</td>
            <td><input type="text" ng-model="productForm.Name" /></td>
        </tr>
        <tr>
            <td>Product Description</td>
            <td><input type="text" ng-model="productForm.Description"  /></td>
        </tr>
<tr>
            <td>Product URL</td>
            <td><input type="text" ng-model="productForm.URL"  /></td>
        </tr>
        <tr>
            <td colspan="2">
                <input type="submit" value="Submit" class="blue-button" />
            </td>
        </tr>
   </table>
</form>
data: angular.toJson($scope.productForm) can have value from index.html

Like others have said, you have a number of things you need to address.
main.js doesn't have a function _refreshProductData defined. I'm assuming this is breaking your script and why $scope.submitProduct() isn't executing.
When defining your _refreshProductData function, you need to attach it to the controller's $scope(i.e. $scope._refreshProductData = function(){//refresh data} if you want it to be accessible to the html template. Otherwise, you wouldn't need to attach $scope to it. You would need to update your call to this function based on the approach you take.

$scope._refreshProductData();--> you should call your function this way.
_refreshProductData();-->_refreshProductData is not defined(F12)
I have assumed that the function was created in my previous answer.
1)create your function in main.js
$scope._refreshProductData() = function()
{
write codes here...
}
then call the function in place
2) $scope._refreshProductData();

Related

JSON data fetched using API not being displayed using JQuery and Handlebars

So, I am creating this webapp that utilizes the BetterDoctor's API to fetch a list of doctors related to a particular practice (like cardiology).
I am using Handlebars, JQuery, HTML, and JS to do this.
A screenshot of what the code looks like in the browser
When I try and run the code on the browser, the data can't be seen in the template as defined in the HTML page under the {{#data}} tag. Whilst inspecting the page and taking a look at the browser console, I couldn't find anything wrong since the console.log was returning the correct url that had the required JSON data from which data was meant to be fetched from.
Any help regarding this issue would be of great help and very much appreciated.
Here's a pen containing the code:https://codepen.io/sandeeprao/pen/OzbQJY?editors=1010
You can see the error
Here's my HTML
<div>
name a speciality: <input type="text" id="speciality">
<br></br>
enter state (in short form): <input type="text" id="state">
<br></br>
lattitude: <input type="text" id="lat" value="">
longitude: <input type="text" id="lon" value="">
</div>
<div id="content-placeholder"></div>
<script id="docs-template" type="text/x-handlebars-template">
<table>
<thead>
<th>Name</th>
<th>Title</th>
<th>Bio</th>
</thead>
<tbody>
{{#data}}
<tr>
<td><p>{{profile.first_name}} {{profile.last_name}}</p><br>
<td>{{profile.title}}</td>
<td>{{profile.bio}}</td>
</tr>
{{/data}}
</tbody>
</table>
</script>
Here is the JS file for it:
var base_url = 'https://api.betterdoctor.com/2016-03-01/practices?';
function go2(){
var speciality = document.getElementById('speciality').value;
var state = document.getElementById('state').value;
var url_search = {
name: speciality,
location: state,
user_location: '',
skip: 0,
limit: 10,
user_key: 'CODE_SAMPLES_KEY_9d3608187'
}
console.log(speciality);
console.log(state);
var url = base_url + jQuery.param( url_search );
console.log(url)
$.get(url, function (data) {
// data: { meta: {<metadata>}, data: {<array[Practice]>} }
var template = Handlebars.compile(document.getElementById('docs-
template').innerHTML);
document.getElementById('content-placeholder').innerHTML = template(data);
});
}
The issue has been sorted out. I figured out that there was a problem in the handlebars code and interpreting the JSON format of the API's result.
<td>{{#doctors}}
{{profile.first_name}}{{profile.last_name}}{{/doctors}}</td>
<td>{{doctors.profile.first_name}} {{doctors.profile.last_name}}</td>
That's the fix!

Javascript function reference error

I am trying to call a Javascript function through a command button on my Rails app.
function fetchpurchases() {
var startDate = $('#histStart').val();
var endDate = $('#histEnd').val();
$('#histMainFrame').empty();
$.ajax({
url: '/transHistory/confirm?start_date=' + startDate + '&end_date=' + endDate,
type: 'get',
beforeSend: function() {
$('#mainContDiv').append('<img id=\'spinner\' src=\'/assets/spinner_green.gif\'>');
},
success: function(output) {
$('#spinner').remove();
$('#histMainFrame').html(output);
$('#transPurTab').DataTable({
destroy: true,
lengthChange: false,
pageLength: 50,
paging: true,
stripeClasses: ['oddStrip','evenStrip']
});
}
});
}
A button is defined with the onclick event calling the Javascript function.
<div id="histToolbar">
<div id="errorDiv"><p class="bigRedBright"></p></div>
<table id="histTools">
<tr>
<th>Start Date</th>
<th>End Date</th>
<th></th>
</tr>
<tr>
<td><input type="text" class="datepicker" id="histStart" placeholder="Start Date..."></td>
<td><input type="text" class="datepicker" id="histEnd" placeholder="End Date..."></td>
<td><button onclick="fetchHistory()" id="histSubmit">Submit</button></td>
<td><button onclick="fetchpurchases()" id="deliverSubmit">Confirm Delivery</button></td>
</tr>
</table>
</div>
I can navigate to the page I created by typing it manually into the browser. The MySQL query I wrote works correctly, but when I try to navigate using the button, I get reference error: fetchpurchases is not defined.
Additionally (may not be related), the function does not show up in the DOM window when I try to debug the error using Firebug.
I would do something like so
// Create a namespace for your code
var App = App || {};
(function() {
App.fetchpurchases = function() {
//Your code here
};
})();
If you don't want to use JS or jQuery to bind the function to an event you can change your HTML to:
<td><button onclick="App.fetchpurchases()" id="deliverSubmit" type="button">Confirm Delivery</button></td>
Of course wherever you place that javascript needs to be added to application.js or loaded into the page manually.

Can't fetch single record in Angular js/HTML

Hope you are doing good..
I'm trying to fetch single record from datasource by Id in UI via Angular-js.
Using Web-API for retrieving values from DB.
To make it simple : HTML-->Angular-->WebAPI-->DB
When i'm trying it says Id passed is Null..Don't know how to rectify.
hope i've missed to fill hole in somewhere....below snippets fr ref.
(Also can u verify/correct me the way i've coded in html is right way to display values fetched by Id)
HTML :
<div ng-controller="SingleController">
<input type="text" ng-model="_Id" />
<input type="button" value="search" ng-click="search()" />
<table>
<tr>
<td>MovieId</td>
<td>{{MovID}}</td>
</tr>
<tr>
<td>Title</td>
<td>{{Movtitle}}</td>
</tr>
<tr>
<td>Genre</td>
<td>{{Movgnre}}</td>
</tr>
<tr>
<td>Classification</td>
<td>{{Movcls}}</td>
</tr>
<tr>
<td>ReleaseDate</td>
<td>{{Movdate}}</td>
</tr>
<tr>
<td>Rating</td>
<td>{{Movrate}}</td>
</tr>
<tr>
<td>Cast</td>
<td>{{Cast}}</td>
</tr>
</table>
</div>
Controller.JS
app.controller('SingleController', function ($scope, MyService) {
var Id = $scope._Id;
$scope.search = function (Id) {
var promiseGetSingle = MyService.getbyId(Id);
promiseGetSingle.then(function (pl) {
var res = pl.data;
$scope.MovID = res._movieId;
$scope.Movtitle = res._title;
$scope.Movgnre = res._genre;
$scope.Movcls = res._classification;
$scope.Movdate = res._releaseDate;
$scope.Movrate = res._rating;
$scope.Cast = res._cast;
// $scope.IsNewRecord = 0;
},
function (errorPl) {
console.log('failure loading Employee', errorPl);
});
}
});
service.js
this.getbyId = function (Id) {
return $http.get("/api/values/" + Id);
};
Please ignore this lengthy snippets.
Could you please help me on this.
Your search function is expecting you to pass a value when it is invoked on ng-click:
<input type="button" value="search" ng-click="search(_Id)" />

How to redirect on another page and pass parameter in url from table?

How to redirect on another page and pass parameter in url from table ?
I've created in tornato template something like this
<table data-role="table" id="my-table" data-mode="reflow">
<thead>
<tr>
<th>Username</th>
<th>Nation</th>
<th>Rank</th>
<th></th>
</tr>
</thead>
<tbody>
{% for result in players %}
<tr>
<td>{{result['username']}}</td>
<td>{{result['nation']}}</td>
<td>{{result['rank']}}</td>
<td><input type="button" name="theButton" value="Detail"
></td>
</tr>
</tbody>
{% end %}
</table>
and I would like when I press detail to be redirect on /player_detail?username=username
and show all detail about that player.
I tried with href="javascript:window.location.replace('./player_info');" inside input tag but don't know how to put result['username'] in.
How to do this ?
Set the user name as data-username attribute to the button and also a class:
HTML
<input type="button" name="theButton" value="Detail" class="btn" data-username="{{result['username']}}" />
JS
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name != undefined && name != null) {
window.location = '/player_detail?username=' + name;
}
});​
EDIT:
Also, you can simply check for undefined && null using:
$(document).on('click', '.btn', function() {
var name = $(this).data('username');
if (name) {
window.location = '/player_detail?username=' + name;
}
});​
As, mentioned in this answer
if (name) {
}
will evaluate to true if value is not:
null
undefined
NaN
empty string ("")
0
false
The above list represents all possible falsy values in ECMA/Javascript.
Do this :
<script type="text/javascript">
function showDetails(username)
{
window.location = '/player_detail?username='+username;
}
</script>
<input type="button" name="theButton" value="Detail" onclick="showDetails('username');">
Bind the button, this is done with jQuery:
$("#my-table input[type='button']").click(function(){
var parameter = $(this).val();
window.location = "http://yoursite.com/page?variable=" + parameter;
});
Here is a general solution that doesn't rely on JQuery. Simply modify the definition of window.location.
<html>
<head>
<script>
function loadNewDoc(){
var loc = window.location;
window.location = loc.hostname + loc.port + loc.pathname + loc.search;
};
</script>
</head>
<body onLoad="loadNewDoc()">
</body>
</html>
HTML - set an id attribute
<input type="button" id="go-another-page" name="theButton" value="Detail">Go to another page with parameters</td>
JS - Create an action listener for redirecting
const anotherPackage = document.getElementById('go-another-page');
anotherPackage.addEventListener('click', (event) => {
event.preventDefault();
// After ? mark set your key and variable eg: payment=order-consulting
// For multiple parameters you can use & eg: payment=order-consulting&amount=20
window.location.replace('/payment.html?payment=order-consulting');
});
Retrieve parameters from another page (In this case, payment.html)
// payment.js - this is javascript of your another page
document.addEventListener('DOMContentLoaded', (event) => {
const parameters = new URLSearchParams(window.location.search);
const payment = parameters.get('payment');
console.log(payment);
event.preventDefault();
});

Weird javascript problem

i'm building a page that is dinamically loaded with ajax.
This is what the '$.get' jQuery function calls (this is located on an external HTML page):
<script type="text/javascript">
$(function()
{
$('button').sb_animateButton();
$('input').sb_animateInput();
$('#settings_security_error').hide();
});
function check_passwords(password, password_confirm)
{
$('#settings_security_error').show();
alert('I\'m in funcion!'); // This works...
if(password.length < 4) // ... this doesn't
{
$('#settings_security_error').innerHTML = 'Password too short';
}
else
{
password = hex_md5(password);
password_confirm = hex_md5(password_confirm);
$.get('/engine/ajax/check_password.php?password=' + password + '$password_confirm=' + password_confirm,
{language: "php", version: 5},
function(result)
{
$('#settings_security_error').innerHTML = result;
},
'html');
}
}
</script>
<div class="title">Security</div>
<table class="sub_container">
<tr>
<td><label>Old password</label></td>
<td class="td_input"><input type="password" name="old_password"/></td>
</tr>
<tr>
<td><label>New password</label></td>
<td class="td_input"><input type="password"
name="new_password"
id="settings_security_new_password"
onkeyup="check_passwords(this.value, getElementById('settings_security_password_confirm').value)"/></td>
</tr>
<tr>
<td><label>Confirm password</label></td>
<td class="td_input"><input type="password"
name="new_password_confirm"
id="settings_security_password_confirm"
onkeyup="check_passwords(getElementById('settings_security_new_password').value, this.value)"/></td>
</tr>
<tr>
<td class="td_error" id="settings_security_error"></td>
</tr>
</table>
And this is where the external HTML is placed...:
<div id="settings_appearance">
</div>
... from this javascript snippet:
function get_page_content(page, target_id)
{
$.get('engine/ajax/get_page_content.php?page=' + page,
null,
function(result)
{
$("#"+target_id).html(result); // Or whatever you need to insert the result
},
'html');
}
Well... the problem is that the javascript in the first snippet is executed when it's loaded by the $.get function, but i still can't understand the reason why when i type into the input boxes nothing happen. It should write the output of the javascript function check_passwords(password, password_confirm) in <td class="td_error" id="settings_security_error"></td>.
Thanks for helping.
Silvio
One problem will be this:
$('#settings_security_error').innerHTML = 'Password too short';
$('#settings_security_error') is a jQuery object; not a DOM element. You're meaninglessly setting the innerHTML property on a jQuery object; which won't do anything useful.
If you want to set the DOM elements innerHTML directly, do either:
$('#settings_security_error')[0].innerHTML = 'Password too short';
Or
$('#settings_security_error').get(0).innerHTML = 'Password too short';
Or you can use the jQuery .html() or .text() functions (text() being the quickest):
$('#settings_security_error').text('Password too short');
Or
$('#settings_security_error').html('Password too short');

Categories