pass parameter in g:remoteLink as result of javascript function - javascript

in .gsp file i have javaScript function
<script type="text/javascript">
function getCurrentItemNumber(){
return document.getElementById('item_itemNumber').innerHTML.substr(6);
}
</script>
and in g:remoteLink I like to pass param using that function
something like following ...
<g:remoteLink id="remove_item_button" action="removeItem" update="itemBox"
params="[itemNumber:getCurrentItemNumber()]">- Remove Item</g:remoteLink>
How can I achieve that?

AS workaround I can suggest following
change g:remoteLink to simple link
"<"a id="remove_item_button" class="btn small primary" onclick="removeItem();">- Remove Item "<"/a>
Add javaScript function which will submit data via AJAX
function removeItem() {
$.ajax({type:'POST',
data:{'itemNumber':getCurrentItemNumber()},
url:'${createLink(action: 'removeItem')}',
success:function (data, textStatus) {
jQuery('#itemBox').html(data);
}});
}

Related

alert value of button by onClick

I have a page with a lots of buttons from PHP output with each buttons having different values:
<button class='add' value=".$row['cat_no']." onClick='addItem(value)'>Add To Cart</button>
$row['cat_no'] is data from mysql.
I want to check the button's value when I click it, so I use native JS below:
<script>
function addItem(value) {
alert("this.value");}
</script>
It is not working...it just return this.value. In this case I don't think it is suitable to assign Id to getElementbyId, Pls help to check my mistake or suggest solution. Thanks.
Pls: I dont want to use JQUERY, just native JS.
Use alert(elmt.value); like below. you should pass this to the function
<button class='add' value="test value" onClick='addItem(this)'>Add To Cart</button>
<script>
function addItem(elmt) {
alert(elmt.value);
}
</script>
the code below helps you retrieve the value of the element that triggered the event:
<button class='add' value="test value" onClick='addItem(this)'>Add To Cart</button>
<script>
function addItem(sender) {
alert(sender.value);
}
</script>
However, this is filled with code smells.
I would suggest doing the code below
<button id='add-to-cart' class='add' value="test value">Add To Cart</button>
On a separate JS file:
(function() {
function _onLoad() {
var addToCartButton = document.getElementById("add-to-cart");
addToCartButton.addEventListener("click", _onAddToCartClicked);
}
function _onAddToCartClicked() {
var sender = this;
alert(sender.value);
}
document.addEventListener("DOMContentLoaded", _onLoad, false);
})();
This approach ensures that:
Concerns are separated between HTML and JS
External JavaScript file would be cached which results to faster page load time.
UI would render faster since there are no inline scripts
Global namespace won't be polluted
You don't really need this in your function, just use value. And also remove double quotes, because you need to alert function's parameter, not string, like this:
function addItem(value) {
alert(value);
}
Here is the working example:
function addItem(value) {
alert(value);
}
<button class='add' value="yourValue" onClick='addItem(value)'>Add To Cart</button>
Or you can pass the element to function using this, and then get the needed attribute value from addItem method:
function addItem(item) {
alert(item.value);
}
<button class='add' value="yourValue" onClick='addItem(this)'>Add To Cart</button>

Call function inside onPaymentMethodReceived(obj) method of Braintree

I am trying to call the function in onPaymentMethodReceived:function (obj) method but I am getting an error the obj contains the payments nonce.
My JS code is
this.braintree.setup(this.clientToken, "dropin", {
container: "dropin-container",
onPaymentMethodReceived:function (obj) {
console.log("nonce "+obj.nonce);
this.ckeckoutClick(obj.nonce) //I want call this function which is post request to server//
}
})
my HTML is
<form id="checkout">
<div id="dropin-container"></div>
<input type="submit" value="Place Order">
</form>
Please tell me what I am doing wrong
Thank you
If you want to use this inside the function use () => instead of function ()
this.braintree.setup(this.clientToken, "dropin", {
container: "dropin-container",
onPaymentMethodReceived: (obj) => {
console.log("nonce "+obj.nonce);
this.ckeckoutClick(obj.nonce) //I want call this function which is post request to server//
}
})
otherwise this.checkoutClick() will call checkoutClick on braintree or from wherever the callback is called.

How to call a function by name within a setInterval/setTimeout function?

function loadDate()
{
$.ajax({
type : "POST",
url : "/ajax/date",
data : "text",
success : function(response)
{
$('#dateSection').html(response);
},
error : function(e)
{
alert('Ajax Request Failed: ' + e);
}
});
}
function loadPoop()
{
if(true)
$.ajax({
type : "POST",
url : "/ajax/poop",
data : "text",
success : function(response)
{
$('#poopSection').html(response);
},
error : function(e)
{
alert('Ajax Request Failed: ' + e);
}
});
}
This is essentially what I'm trying to do but nothing I try works beyond making one call
function ajaxCaller(function_name)
{
setInterval(window[function_name], 1000);
//or
setInterval(function_name, 1000);
}
html page
<button type="button" onclick="loadDate()">Date Button</button>
<div id="dateSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller(loadDate())">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller(loadPoop())">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>
Functions in JavaScript are first-class objects. That means that you can use them the same way you would use any other ordinary variable. If you loose the parentheses in your HTML code:
<button type="button" onclick="ajaxCaller(loadDate)">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller(loadPoop)">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>
You tell JavaScript not to call the function loadPoop or loadDate, but pass it directly to function ajaxCaller as a variable.
With the brackets () you are first running loadDate, after which you pass the result of loadDate to ajaxCaller. In this case both loadDate and loadPoop return nothing, so ajaxCaller will also recieve nothing, and no timeout gets set.
Samw's answer is correct - but I want to try and elaborate a bit on the matter.
In your code you're passing the return value of loadPoop() and loadDate() as a parameter to ajaxCaller(). Basically - first loadPoop() gets called, and then the value it returns (which is nothing in your case) gets passed on into ajaxCaller().
In Samw's answer a pointer to the functions loadPoop() and loadDate() is passed as a parameter, allowing you to later call the functions using function_name(). The same thing is happening with setInterval, where you pass a pointer to the function you want to invoke within setInterval as a parameter.
If you think of the parameters not as an object or a value but as addresses then this makes a bit more sense - basically what happens is that the execution of the code "jumps" to the memory address (a variable name is just what we humans call that specific memory address) - and since a function starts executing at that point in memory - it just carries on.
Now this might be a bit of an oversimplification, but hopefully it'll give you a better idea of why this is OK, and why your method didn't work.
Welcome to the world of pointers!
Since you're using jQuery I'd be inclined to rework the code a little bit to take advantage of it. You can separate out the inline code which is a good thing, and you can reduce the number of ajax functions to one by passing in the function parameter.
<button type="button" data-fn="default">Date Button</button>
<div id="dateSection">Ajax Me Bro!</div>
<button type="button" data-fn="date">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" data-fn="poop">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>
$(function () {
function loadAjax(fn) {
$.ajax({
type: "POST",
url: "/ajax/" + fn,
data: "text",
success: function (response) {
$('#' + type + 'Section').html(response);
},
error : function (e) {
alert('Ajax Request Failed: ' + e);
}
});
}
}
$('button').click(function () {
var fn = $(this).data('fn');
switch (fn) {
case 'date':
setTimeout(function () {
loadAjax('date');
}, 1000);
break;
case 'poop':
setTimeout(function () {
loadAjax('poop');
}, 1000);
break;
default:
loadAjax('date');
break;
}
});
});
Declaration :
function ajaxCaller(fn) {
setInterval(fn, 1000);
}
Usage :
ajaxCaller(loadDate) // instead of : ajaxCaller(loadDate())
ajaxCaller(loadPoop) // instead of : ajaxCaller(loadPoop())
Don't call fn yourself, let setInterval do this job.
i think the argument can't be a function !! anyway just use following
function ajaxCaller(value)
{
if (value=="loadPoop")
setInterval(function(){loadPoop()},1000);
if (value=="loadPoop")
setInterval(function(){loadDate()},1000);
}
and change arguments to be string
<button type="button" onclick="ajaxCaller("loadDate")">Poop Button</button>
<div id="poopSection">Ajax Me Bro!</div>
<button type="button" onclick="ajaxCaller("loadPoop")">Ajax Caller Button</button>
<div id="ajaxCallerSection">Ajax Me Bro!</div>
i think solution here is more dynamic though:
How to execute a JavaScript function when I have its name as a string

Unable to assign Model value to javascript variable

I use an autocomplete to introduce the description of a product and get the ProductID and the Price with a javascript function:
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#Description").change(function () {
$("#ProductID").val(Description_autocomplete_hidden.value);
$("#Price").load('#Url.Action("GetPrice", "Product")', { id: parseInt($("#ProductID").val()) });
});
});
});
</script>
The ProductID works fine, the action, e.g., “\Product\GetPrice\4” is correctly called but I am unable to assign the product price to the $(“#Price”).
The razor code:
<div class="row">
<div class="label">#Html.Label("Product")</div>
<div class="input">#Html.AutoComplete("Description","","Product","_Shared")</div>
</div>
<div id ="ProductID"></div>
<br />
<div class="row">
<div class="label">#Html.Label("Price")</div>
<div class="input">#Html.Editor("Price")</div>
</div>
The GetPrice() in the Product controller:
public string GetPrice(int id)
{
return unitOfWork.ProductRepository.GetByID(id).Pvp1.ToString();
}
#Carlos is Right! The .load() function tries to set the inner HTML which doesn't work for a text field. You need to set textBox's value to make it work. Simply replace your line $("#Price").load('#Url.Action("GetPrice", "Product")', { id: parseInt($("#ProductID").val()) });
});
With this:
$.get('#Url.Action("GetPrice", "Product")', { id: parseInt($("#ProductID").val()) },
function(result) {
//set the value here
$("#Price").val(result);
});
Look here:
http://api.jquery.com/load/
jQuery uses the browser's .innerHTML property to parse the retrieved
document and insert it into the current document.
According to what is written there, jQuery load method cannot be used to set value attribute of your input.
Please use this: http://api.jquery.com/jQuery.ajax/
It will give you more options. Also in success callback you can use returned value wherever you want, in your case to assign value to input:
$("#Price").val(data);
$(document).ready(function () {
$(function () {
$("#Description").change(function () {
$("#ProductID").val(Description_autocomplete_hidden.value);
$.ajax({
url: '#Url.Action("GetPrice", "Product")',
data: { id: parseInt($("#ProductID").val()) },
dataType: 'text',
type: 'get',
success: function (data) {
$("#Price").val(data); //
}
});
});
});
});
try this

How to display a input button and close the current window

I have a call to a service using ajax, i would like if everything goes well on the ajax call to enable or display an input (maybe in a div?) on my page that when clicked it will close the current window. What is the best way to do this using javascript?
Here is my function of a javascript class:
MyFunction.prototype.init = function(param1, param2) {
this.MyParams = new Hash();
this.MyParams.set("param1", param1);
this.MyParams.set("param2", param2);
new Ajax.Request('MyService.asmx/MyServiceFunction', {
method: 'post',
onSuccess: //how can i do what i mentioned here?,
onFailure: failureFunc,
onException: ajaxError,
parameters: this.MyParams
});
}
Any help would be much appreciated
On the onSuccess part you have to put something like this:
OnSuccess: function() {
$('div_to_show').show();
}
In the HTML part you will have this:
<div id="div_to_show">
<input type="button" name="close" id="close" value="close" onclick="javascript:window.close();" />
</div>
Of course you have to hide the div on document loading.

Categories