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.
Related
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();
I have some complication with service removing. I have function that removes service on the server but I have to reload page to update table. I found way how to remove row by click-binding but there is the issue beacuse I can only remove row or get ID for delete service from server NOT both. :/
This is example of code that removes service on the server but doesn't remove table row.
HTML:
<table id="serviceView" class="fixed_header" border: 1>
<thead>
<tr>
<th>Name</th>
<th>Adress</th>
<th>Notification</th>
</tr>
</thead>
<tbody data-bind="foreach: services">
<tr>
<td data-bind="text: name"></td>
<td data-bind="text: address"></td>
<td data-bind="text: serviceId"></td>
<td ><button data-bind="click: $parent.DeleteService.bind(this, serviceId)">Remove</button></td>
</tr>
</tbody>
</table>
JS:
self.services = ko.observableArray([]);
self.lastCheck = ko.observable();
$.getJSON("http://localhost:55972/api/status", function (data) {
self.services(data.services);
self.lastCheck = data.lastCheck;
}); //////This is loading data to the table from server
self.DeleteService = function (serviceId) {
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
self.services.remove(serviceId)
})
};
This is example of code that removes table row
When I use click-binding like this:
<button data-bind="click: $parent.DeleteService">Remove</button>
And change delete function to this:
self.DeleteService = function (serviceId) {
self.services.remove(serviceId)
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
// here I want to remove row but i doesnt goes here without service ID.
})
};
It removes row but instead serviceId I got [object, object] in the URL.
Can you help me with it ? I got idea to use jquery to just update the table but it's seems unnecessarily complicated for me when I can use knockout.
I know the solution is not that hard but I'am just unable to solve it..... -_-
I'am sorry for taking time with this bullshit but this is my first real project and I'am so desperate at this point beacuse I have lot of things to do and I'am stucked on this.
In your Js code, you can try this:
self.services = ko.observableArray([]);
self.lastCheck = ko.observable();
$.getJSON("http://localhost:55972/api/status", function (data) {
self.services(data.services);
self.lastCheck = data.lastCheck;
}); //////This is loading data to the table from server
var serviceIdRemoved;
self.DeleteService = function (serviceId) {
serviceIdRemoved = serviceId; // now you can do whatever you need more with this value
$.ajax({
type: "GET",
url: "http://localhost:55972/api/services/remove/" + serviceId,
}).done(function () {
self.services.remove(serviceId)
})
};
With this way of work you can user the content of the variable and don´t loose it. Also if you get [Object, Object], you can:
console.log(serviceId) // to see the content in the console.
JSON.stringify(data) //to see the content in html
This source could help you to understand it better.
The [object, object] you are seeing is actually the data and event objects which are secretly added to the JS function parameters by Knockout. If you want to add your own parameter to the click binding then you should do it like this:
<button data-bind="click: function(data, event) { $parent.DeleteService(serviceId, data, event) }">Remove</button>
You can then define your JS function as follows:
self.DeleteService = function (serviceId, data, event) {
[code here...]
}
You can read up on the exact details of it in the excellent Knockout documentation here:
http://knockoutjs.com/documentation/click-binding.html
It's about half-way down under the heading that reads Note 2: Accessing the event object, or passing more parameters
JSP file
<div class="container">
<table id="headerTable" class="table table-bordered">
<thead>
<tr>
<th colspan="2">Header</th>
</tr>
</thead>
<tbody>
<c:forEach items="${headerList}" var="field">
<tr>
<th>${field}</th>
<td><input id="${field}" type="text" class="form-control "></td>
</tr>
</c:forEach>
</tbody>
</table>
Javascript
$('#parseBtn').click(function() {
var parseMsg = $('#msgText').val();
alert("parse message is " + parseMsg);
$.ajax({
type: "GET",
url: "/parseMessage",
data: {
"msg": parseMsg
},
success: function(data) {
//data format looks like Object {SubsystemChannel: "F", MessageNumber: "200257", DebugQueue: " ", WorkStationNumber: "023", FrontEndNumber: "0000"…}
$('#headerTable input').each(function() {
var id = $(this).attr('id');
var field = data.id;
$(this).val(field);
});
}
});
});
What I am going to do is, go through the $('#headerTable input'), set the value(from data) in it. So, I get the each input id first, then get the value from data using id, but it failed.... Could you help me on this? thank you very much
You should use Bracket notation instead of dot notation to access properties using id variable
$('#headerTable input').each(function () {
var field = data[$(this).attr('id')];
$(this).val(field);
});
I have the following code in a Twig template:
<table class="table">
<thead>
<tr>
<th>License ID</th>
<th>Quote ID</th>
</tr>
</thead>
<tbody>
{% for key,value in data %}
<tr>
<td>{{ value.id }}</td>
<td>
<select class="form-control select2" data-placeholder="--Select One--"></select>
</td>
</tr>
{% endfor %}
</tbody>
</table>
The code above translate into one or more SELECT elements depending on the data coming from the backend.
Each of those will need to run a really BIG and slow query to get the data that should be there.
What I am thinking is to render them just empty (no values at all, just the initial placeholder) and when I open each of them then populate it's data so I run just one query at a time (thru AJAX).
I should also - although don't know if it's a good idea (you tell me) - on close destroy all the SELECT values.
Note: I should say the Select2 elements are contained in a jQuery UI dialog but this shouldn't be a problem.
This is how my code looks like:
addtoquoteDialog.dialog({
autoOpen: false,
modal: true,
width: 800,
height: 600,
resizable: false,
buttons: {
"Cancel": function () {
$(this).dialog('close');
},
"Add to Quote": function () {
$(this).dialog('close');
}
},
open: function (event, ui) {
var $select2selector = $('.select2');
$select2selector.select2();
$select2selector.on('select2:open', function (e) {
var id = $(this).data('id');
$select2selector.select2({
ajax: {
url: Routing.generate('quote_select_data', {id: id}),
dataType: 'json'
}
});
}).on('select2:closing', function (e) {
// Destroy the select values
});
}
});
But I am raising the Cannot read property 'query' of null famous error message and the AJAX call is not being triggered.
I've seen a lot of issues like this (this one for example) but none seems to be like mine so I am completely lost.
Can any tell me what I am missing in my code?
I am seeing this example but this happen when the SELECT get's initialized, I am right?
What is the right way to handle this?
This question already has an answer here:
How to call an AJAX function on anchor tag?
(1 answer)
Closed 8 years ago.
My code snippet from smarty template is as follows:
<form name="transaction_form" id="transaction_form">
<table class="trnsction_details" width="100%" cellpadding="5" >
<tbody>
<tr>
<td width="150"><b>Transaction Status : </b></td>
<td class="view_details">
<select name="transaction_status_update" id="transaction_status_update">
{if $transaction_status_array}
{foreach from=$transaction_status_array item="status"}
<option value="{$status}" {if $status == $user_transaction_details.transaction_status}selected="selected" {/if}>{$status|capitalize:true}</option>
{/foreach}
{/if}
</select>
</td>
<td width="150">
</td>
</tr>
<tr>
<td valign="top"><b>Remark : </b></td>
<td><textarea name="transaction_remark" cols="30" rows="5"></textarea></td>
<td><a class="edit_user_transaction_status" href="{$control_url}{$query_path}?op=edit_user_transaction&page={$page}&txn_no={$user_transaction_details.transaction_no}&transaction_data_assign={$user_transaction_details.transaction_data_assign}&user_id={$user_id}{if $user_name!=''}&user_name={$user_name}{/if}{if $user_email_id!=''}&user_email_id={$user_email_id}{/if}{if $user_group!=''}&user_group={$user_group}&{/if}{if $user_sub_group!=''}&user_sub_group={$user_sub_group}{/if}{if $from_date!=''}&from_date={$from_date}{/if}{if $to_date!=''}&to_date={$to_date}{/if}{if $transaction_status!=''}&transaction_status={$transaction_status}{/if}{if $transaction_no!=''}&transaction_no={$transaction_no}{/if}">Update</a></td>
</tr>
</tbody>
</table>
</form>
Now I want to call the following jQuery-AJAX function upon clicking on the anchor tag, but I couldn't. I tried to print the alert at the beginning of the function but that is also no getting printed. Can you help me in calling the function upon clicking the hyperlink? Thanks in advance.
$(document).ready(function() {
//This function is use for edit transaction status
$(".edit_user_transaction_status").click(function(e) { alert("Hello");
e.preventDefault();
//for confirmation that status change
var ans=confirm("Are you sure to change status?");
if(!ans) {
return false;
}
var post_url = $(this).attr('href');
var transaction_status_update = $('#transaction_status_update').val();
$.ajax({
type: "POST",
url: post_url+"&transaction_status_update="+transaction_status_update,
data:$('#transaction_form').serialize(),
dataType: 'json',
success: function(data) {
var error = data.login_error;
$(".ui-widget-content").dialog("close");
//This variables use for display title and success massage of transaction update
var dialog_title = data.title;
var dialog_message = data.success_massage;
//This get link where want to rerdirect
var redirect_link = data.href;
var $dialog = $("<div class='ui-state-success'></div>")
.html("<p class='ui-state-error-success'>"+dialog_message+"</p>")
.dialog({
autoOpen: false,
modal:true,
title: dialog_title,
width: 500,
height: 80,
close: function(){
document.location.href =redirect_link;
}
});
$dialog.dialog('open');
}
});
});
});
It looks like you are using Smarty
You need to add JavaScript block between
{literal}
// your javascript or jquery code
{/literal}