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
Related
I want to pass a value from HTML page to child function from parent function.
HTML Page:
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type your message here..." />
</div>
<div class="send_message">
<div class="icon"></div>
<div class="text">Send/div>
</div>
</div>
Parent Function Call:
$('.send_message').click(function (e) {
return [sendMessage(getMessageText()),sendMessage1(getMessageText1())];
});
$('.message_input').keyup(function (e) {
if (e.which === 13) {
return [sendMessage(getMessageText()),sendMessage1(getMessageText1())];
}
});
here getMessageText1 is child function.
Child Function:
getMessageText1 = function () {
var result="";
var id = Parent_FUNC_INPUT;
$.ajax({
url:"func.php",
type: 'POST',
data: ({id:id}),
async: false,
success:function(data) {
result = data;
}
});
I want to populate [[id]] variable in child function from parent function.
First, I'll do my best to clean up the HTML:
<div class="bottom_wrapper clearfix">
<div class="message_input_wrapper">
<input class="message_input" placeholder="Type your message here..." />
</div>
<div class="send_message">
<div class="icon"></div>
</div>
<div class="text">Send</div>
</div>
Using proper indentation will make things far easier to read. And while we're on the subject, you may want to use dashes - instead of underscores _ in your class names, as that's the common convention.
On to your question, it seems like what you want to do is simply pass an argument to getMessageText1 from within (as you refer to it) a "parent" function bound to an event listener.
So you'd define this "child" function with a single parameter:
function getMessageText1(Parent_FUNC_INPUT) {
...
var id = Parent_FUNC_INPUT;
...
}
And then you can just call it with getMessageText1(value) where value is whatever you want to pass in.
One more note: for readability's sake I recommend you do not name your functions the way you have. Having two functions getMessageText and getMessageText1 will just be a source of confusion later on. Instead, think of something more descriptive, ala getMessageTextFromID.
Hopefully I answered the question you meant to ask. Let me know.
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>
I have a problem related on passing my data came from database to another function in jquery. I want to pass two of my data from the loop of my ajax from database on a button click function. My problem is, when i go pass the value , instead of the true value of my check_up_id = 1-0/1-1, when i passed it to other function and alert it or output it, it becomes only 0 and 1. I tried to console.log the value but i don't know why it gives me a wrong value.
Please take a look in this code inside my for loop from the first function:
<button onclick="add_bill('+data[i]['check_up_id']+','+data[i]['patient_id']+')
Here is my code:
function show_finished_check_up() {
$("#bill_queue").empty();
$.ajax({
url: siteurl+"billing/bill_list",
type: "GET",
dataType: "JSON",
success: function(data) {
if(data.length>0) {
for(i=0;i<data.length;i++) {
$("#bill_queue").append('<div class="col-sm-10">'+'<div class="panel-group">'+'<div class="panel panel-info">'+'<div class="panel-heading">'
+'<h4>'+data[i]['check_up_id']+' '+data[i]['patient_lname']+', '+data[i]['patient_fname']+' <button onclick="add_bill('+data[i]['check_up_id']+','+data[i]['patient_id']+')" class="btn btn-success btn-sm pull-right"><span class="fa fa-plus"></span> Add bill</button></h4>'
+'</div><!-- panel-heading -->'+'</div><!-- panel -->'+'</div><!-- panel-group -->'+'</div><!-- col-sm-10 -->');
console.log(data[i]['check_up_id']);
};
}
});
}
function add_bill(check_up_id, patient_id) {
$('#add_bill').modal('show');
// $('.modal-body #patient_id').val(patient_id);
// $('.modal-body #check_up_id').val(check_up_id);
alert(check_up_id);
alert(patient_id);
}
now the problem, when i passed it from add_bill function the patient_id returns a true value but my check_up_id value returns only 0 instead of 1-0
I also already put a console.log below the loop and when i saw the value from database it gives me 1-0, now when i passed it from the function add_bill it gives me 0 value instead of 1-0.
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.
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);
}});
}