jQuery .ready() function use in other event - javascript

Below is my .ready() function:
$(document).ready(function()
{
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
$('#display').html(data);
}
else
{
//error msg
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
});
This function will run when the page load, but I would like to use this function in other event like .click(). Do I need to rewrite the function?

Just create the function with a name, and use it everywhere! Example:
$(document).ready(function(){
function yourFunction(){
var Semester = $('#Semester').find(':selected').val();
var StudentID = "<?php echo $_GET['id'];?>";
$.ajax(
{
type: 'POST',
url: 'ajax_get_report_for_edit.php',
data: {Semester:Semester, StudentID:StudentID},
dataType: 'text',
success: function(data)
{
if(data['error'] == null)
{
if(data['no_result'] == null)
{
$('#display').html(data);
}
else
{
//error msg
}
}
else
{
alert("Error: " + data['error'])
}
},
error: function(ts)
{
alert("AJAX Error: \n" + ts.responseText);
}
});
}
yourFunction();
$('#element').click(function(){
yourFunction();
});
});

name the function and call that function on your click event.
sample:
<button id='btn'> click me </button>
$(document).ready(function(){
foo();
$("#btn").click(function(){
foo();
});
function foo(){
alert('data');
}
});
JSFIDDLE DEMO

This function will run when the page load, but I would like to use
this function in other event like .click().
Try using array of functions as parameter to .ready() , name first function in array , set named function to property of this:document within first array ; named function should be available at second function within array as property of this:document
$(document).ready([
function fn() {
this.fn = fn;
console.log(this)
},
function() {
$("div").click(this.fn)
}
])
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div>click</div>

First Create a function that will be called on your click event. Please see below example.
$(document).ready(function(){
$("#samplebutton").on("click",function(){
example();
});
function example(){
alert("clicked");
}
});

Related

jquery code execution is happening in other code block

I have made this custom ajax function to avoid writing ajax code multiple times. My issue is that if there is no option passed for failcmds variable & obj.status is "failure", then also code execution moves to the succcmds code block & execute available commands. e.g. reload(2500) in the example code.
Pls help me to identify the missing part.
Custom Ajax function
function gr(url, varr, succcmds, failcmds, divid, drestype) {
$.ajax({
url: url,
type: "POST",
data: varr,
beforeSend: function(){
$('#loadingDiv').show();
},
complete: function(){
$('#loadingDiv').hide();
},
success: function(response){
if(response){
var obj = $.parseJSON(response);
if(obj.status == "failure") {
console.log('failcmds : ' + failcmds);
if(obj.message) {
gm("e",obj.message);
}
if(typeof failcmds === "undefined") {
return;
}else {
$.each(failcmds,function(index, value) {
value;
});
}
}else if(obj.status == "success"){
if(obj.message) {
gm("s",obj.message);
}
if(succcmds && succcmds !== null) {
$.each(succcmds,function(ind, val) {
val;
});
}
if (divid && divid !== null){
if(drestype && drestype == "html"){
$("#"+ divid).html(obj.data);
}else{
$("#"+ divid).append(obj.data);
}
}
}
}else{
gm("e", "Invalid Request");
}
},
error: function(){}
});
}
Sample usage of function
$(document).on("click", '.xyz', function() {
var d = $(this).prop('id');
var data = 'd='+ $(this).prop('id') + '&typ=sts';
gm('c','Are you sure you want to do this?');
$(document).on("click", '#btnYes', function() {
var sarr = [reload(2500)];
gr(basepath + "deletereq?", data, sarr);
});
});
then also code execution moves to the succcmds code block & execute available commands
No it doesn't. You executed those commands before you even called your function:
var sarr = [reload(2500)];
This will execute reload(2500) and put the result of that execution in the sarr array.
Instead, wrap that in a function:
var sarr = [function () { reload(2500); }];
Then you can later execute that function where you like:
$.each(succcmds,function(ind, val) {
val();
});
Basically you want your "commands" to be executable functions, not the results of executed functions.

How do I make a function run and finish before a loop starts in JS

I've got a JS file that's automatically run through an HTML script. I want the console to print out "changing to true" before it prints out "starting toggle". The reason for this is because I want the function to call an API and change the toggle "checked" states before it loads. How do I do this?
$(document).ready(function(){
for (var i=0;i<Object.keys(obj).length;i++) {
var obj_name = Object.keys(obj)[i];
obj_id = "#"+obj_name;
$(obj_id).bootstrapToggle();
console.log("starting toggle")
}
})
$("#samplekey").ready(function() {
checkKey("#samplekey", power_toggles["samplekey"]);
})
function checkKey(obj_id, url1){
var http_verb = "GET";
$.ajax({
url: url1,
type: http_verb
}).done(function(data) {
if (data == 1234) {
$(obj_id).prop("checked", true);
console.log("changing to true")
}
else
{
$(obj_id).prop("checked", false);
}
}).fail(function(data,textStatus,errorThrown) {
alert(errorThrown);
});
}
You could made this change in your code:
$(document).ready(function() {
checkKey("#someUrl", "someUrl")
})
function checkKey(obj_id, url1) {
var http_verb = "GET";
$.ajax({
url: url1,
type: http_verb
}).done(function(data) {
for (var i = 0; i < Object.keys(obj).length; i++) {
var obj_name = Object.keys(obj)[i];
obj_id = "#" + obj_name;
$(obj_id).bootstrapToggle();
console.log("starting toggle")
}
if (data == 1234) {
$(obj_id).prop("checked", true);
console.log("changing to true")
} else {
$(obj_id).prop("checked", false);
}
}).fail(function(data, textStatus, errorThrown) {
alert(errorThrown);
});
}
$("#samplekey").ready(function() {
checkPOEPower("#samplekey", power_toggles["samplekey"]);
})
And remember that Javascript is Asynchronous, this means that the code never stops for external requests or others events.
You should make the ajax request sync. Add a property "async: false" in your codes
$.ajax({
url: url1,
type: http_verb,
async: false
}).done(function(data) {
if (data == 1234) {
$(obj_id).prop("checked", true);
console.log("changing to true")
}
else
{
$(obj_id).prop("checked", false);
}
}).fail(function(data,textStatus,errorThrown) {
alert(errorThrown);
});

Youtube Search js function

While i was searching at stackoverflow, i found the code below :
$(document).ready(function () {
$("#show").click(function () {
getYoutube($("#Search").val());
});
});
function getYoutube(title) {
$.ajax({
type: "GET",
url: yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + title + '&format=5&max-results=1&v=2&alt=jsonc',
dataType: "jsonp",
success: function (response) {
if (response.data.items) {
$.each(response.data.items, function (i, data) {
var video_id = data.id;
var video_title = data.title;
var video_viewCount = data.viewCount;
$("#result").html(video_id);
});
} else {
$("#result").html('false');
}
}
});
}
How can i edit the code to keep only the function?
I want to be able to use it like that : getYoutube(my_keywords);
Also, how can i save the function output to variable? something like :
var_name = getYoutube(my_keywords);
would be ok?
Thnx! ;)
yes, you can use it as without $(document).ready. No, function does not return anything
To "return" value from Ajax:
$.ajax({
...
success: function(dataFromServer) {
processServerOutput(dataFromServer);
}
});
function processServerOutput(someString) {
alert(someString);
}

Can't set HTML using jQuery

For some reason, my script isn't writing out the text after I remove the textbox element. Am I incorrectly using the .html or is something else wrong?
$('.time').click(function () {
var valueOnClick = $(this).html();
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove('.timebox');
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});
OK, thanks to the comments, I figured out I was referencing the wrong thing. The solution for me was to change the blur function as follows:
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
}
$(this).parent().html("8");
$(this).remove('.timebox');
});
$(this) in your success handler is refering to msg, not $('.timebox') (or whatever element that you want to append the html to)
$(this) = '.timebox' element but you have removed it already,
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88"); // This = msg
}
and
else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88"); // this = '.timebox' element but you have removed it already,
}
The value of this changes if you enter a function. So when u use this in the blur function handler, it actually points to '.timebox'
$('.time').click(function () {
var valueOnClick = $(this).html();
var $time=$(this);//If you want to access .time inside the function for blur
//Use $time instead of$(this)
$(this).empty();
$(this).append("<input type='text' class='input timebox' />");
$('.timebox').val(valueOnClick);
$('.timebox').focus();
$('.timebox').blur(function () {
var newValue = $(this).val();
var dataToPost = { timeValue: newValue };
$(this).remove(); //Since $(this) now refers to .timebox
if (valueOnClick != newValue) {
$.ajax({
type: "POST",
url: "Test",
data: dataToPost,
success: function (msg) {
alert(msg);
$(this).html("88");
}
});
} else {
// there is no need to send
// an ajax call if the number
// did not change
alert("else");
$(this).html("88");
}
});
});

jQuery MVC - Basic jQuery if else statement which CANT work?

I got an if-else script:
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
if (isFav(fid)) {
alert("Do you want to remove from favorite?");
}
else {
alert("Add to favorite?");
}
});
calling the isFav script function:
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { return result; }
});
}
which in turn calling my controller action:
public Boolean IsFav(int id)
{
var food = dbEntities.FOODs.Single(f => f.FoodID == id);
if (food.FavFlag == 1)
{
return true;
}
else
{
return false;
}
}
Everything seems works fine, I get a true from firebug, BUT i get the alert message from the else statement. The if statement just never being entered.
I cant get what is wrong here. Any idea?? Please help..
The ajax request in isFav is async and the isFav method will return before it is completed.
This is probably how I would solve it:
function isFav(fid, callback) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) { callback(result); }
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid,function(result){
if(result && result.toLowerCase() == "true"){
alert("Do you want to remove from favorite?");
} else {
alert("Add to favorite?");
}
});
});
You want to make sure that the code in the if-block is run after the ajax request is done. In this snippet this is solved by the callback method that is called when the ajax success function is executed.
You're not really returning true from within isFav function. Also ajax is asynchornous, so your code (if statement) actually continues to execute until ajax finishes, so at the moment of execution the result of isFav is undefined. So that's why else is being executed.
You're gonna need some remodeling.
function isFav(fid) {
$.ajax({
url: '/Stock/IsFav',
type: 'GET',
data: { id: fid },
success: function (result) {
if(result == 'favorite') alert("Do you want to remove from favorite?");
else alert("Add to favorite?");
}
});
}
$('#favitem').live('click', function () {
var fid = $(this).parent().attr('id');
isFav(fid);
});

Categories