How can I pass this specific variable I'm using jquery-ajax - javascript

I want to pass the "passedThisValue" to my "start_battle" function and use the "start_battle" function in my "Rematch". But the modal just hangs why is this happening? what could be wrong? Please help! :) Thank you.
CODE:
function start_battle(){
$.ajax({
data: {
receivePassedValue: passedThisValue
},
success: function(data){
}
});
}
$("#start_battle").click(function() {
$.ajax({
success: function(data){
var toAppend = '';
if(typeof data === "object"){
var passedThisValue = '';
for(var i=0;i<data.length;i++){
passedThisValue = data[i]['thisValue'];
}
start_battle(); // can I still get the passedThisValue?
}
}
});
$("#battle").dialog({
modal:true,
buttons: {
"Rematch": function(){
start_battle(); // can I still get the passedThisValue?
}
}
});
$("#battle").show(500);
});

When you call a function, you don't use function start_battle();, you just use start_battle();.
When you pass a value to a function, you need to use this syntax: start_battle(param1, param2);.
When you want to get a value from a function, you need to return it in the function, like so:
function start_battle(param1) {
// Do something
return param1;
}
When you want to store a returned value from a function, you do something like: var returned = start_battle(param1);
And the fact that you don't know why the modal just hangs, means that you didn't check the browser's error console, which can hold some pretty important information on what's wrong. Try checking that and posting here so we can see the current problem

Your function declaration seems a little off. I think you should leave off the $ from function. Just do this
function start_battle() {
Also, when you're calling a function, you don't say function before it. And if you want to pass a value to the function, you have to put it inside the parenthesis, both when defining the function and when calling it. Like this
function start_battle(someValue) {
// do some stuff with someValue
}
// inside your .click, call start_battle like this
start_battle(passedThisValue);
Pretty basic stuff. But either one of those problems could be causing the hang, which was likely a javascript error.

Related

Javascript Not Passing Value to Function

Hi I am trying to pass 3 values into some Javascript. This works for the first function. All values are found to be correct here......
function handleClick(cb,colum,id) {
if (cb.checked == true){
var checked = 1;
} else {
var checked = 0;
}
sendHddToPHP2(checked,column,id);
}
But once the second function is called I get nothing....
function sendHddToPHP2(editableObj,column,id) {
window.alert(editableObj);
$.ajax({
url: "update/hdd.php",
type: "POST",
data:'column='+column+'&editval='+editableObj+'&id='+id,
success: function(data){
$(editableObj).css("background","#FDFDFD");
}
});
}
I added the alert to check if the variable was present and it didn't run. I can't see any typos and my knowledge isn't that great on Javascript. Is there something I have missed?
You have a typo: "colum" in the argument list.
Also, seems like you want to access the check box later in the Ajax callback, that will fail since you're trying to reference it via the "editableObj" value of the checkbox rather than the element.
As I understand you want your function to be like this:
function handleClick(cb,colum,id) {
var checked = (cb.checked)?1:0;//same as(cb.checked==true)1:0
sendHddToPHP2(checked,column,id);
}
but are you sure you want to return a 1 or 0? because in the second function you will be using $(1).css("background","#FDFDFD");
$(0).css("background","#FDFDFD");

How to create global variable in query and usable with javascript

$(document).ready(function ()
{
$.ajax(
{
url: "Bibliotheek.xml",
dataType: "xml",
success: function (data)
{
var song = $(data).find('key').filter(function ()
{
return $(this).text().indexOf('Name') != -1;
}).each(function()
{
window['globalVar']= $(this).next('string').text();
console.log(globalVar);
});
}
});
});
I want to use globalVar outside that each loop. But once i put de console.log outside the function. It tells my globalVar is undefined.Is it also possible to use that variable later on in javascript code?
This probably happens, because you loop over an empty list (i.e. it never enters the .each callback). This thing is wrong: .find('key'). It searches for a key tag (which is not HTML, unless you actually are not dealing with HTML?). Perhaps you were looking for .find('.key')?
EDIT: It seems that you want to put console.log outside of ajax call. If you do, then you're out of luck, since you are trying to log a variable that does not exist yet. That's because a in ajax stands for asynchronous, i.e. the piece of code will run later.
EDIT 2: Welcome to asynchronous programming! It seems that you are trying to force ajax to be synchronous, which is wrong and pure eveil. Don't do it. You're code should be similar to this:
var my_fn = function(clb) { // <-- this is callback to be called later
var els = [];
$.ajax({
url: "Bibliotheek.xml",
dataType: "xml",
success: function (data) {
var song = $(data).find('key').filter(function () {
return $(this).text().indexOf('Name') != -1;
}).each(function() {
var el = $(this).next('string').text();
els.push(el);
});
clb(els); // <-- call it now
}
});
};
$(document).ready(function() {
my_fn(function(els) {
console.log(els);
// do coding here
});
});
Define the globalVar outside of the functions...
var globalVar;
var song = {...
console.log(globalVar);//will work here
};
console.log(globalVar);//and, will work here

How to invoke function call if it is defined as var?

I'm getting data from server using JQuery and JSON. I defined getBooksDoneFunc
as variable because I need to be able to call this function not only once (when getBooks is done) . Unfortunately, I cannot call getBooksDoneFunc from inside of signInOK as window["getBooksDoneFunc"]();. Why? What is the best way to call this function?
function getBooks(){ return $.getJSON( "bookstore.json" ); }
var getBooksDoneFunc = function(json) {
$.each(json.books, function(i, json){ .......... });
}
getBooks().done(getBooksDoneFunc);
function signInOK(){
window["getBooksDoneFunc"]();
}
PS. The idea for window["getBooksDoneFunc"](); was taken from SO answer
UPDATE:
var booksJSON = {};
window["getBooksDoneFunc"](booksJSON);
getBooksDoneFunc must be called with parameters nevertheless the call to getBooksDoneFunc fails. signInOK is defined outside of $(document).ready(function(){ }); but called inside of it.
Try:
function getBooks(){
return $.getJSON( "bookstore.json" );
}
window.getBooksDoneFunc = function(json) {
$.each(json.books, function(i, json){ .......... });
}
getBooks().done(getBooksDoneFunc);
$(document)ready(function() {
function signInOK(){
var booksJSON = {};
window.getBooksDoneFunc(booksJSON);
}
});
If window["getBooksDoneFunc"](); works, then does getBooksDoneFunc(), the idea of using window is when you want to access a global function but you don't know the function name which is stored in a variable.
In your case, put a hardcoding string is mean less, just do getBooksDoneFunc() is the same, because you already store the function self (not the string of function name) in the variable.
The thing that won't work is that if the variable is not global, please check the scope.
I would do this a bit differently, although I do not really understand the signInOK() function. How will it receive the "json" data. I would reconstruct the getBooks function and rethink the signInOk function. Here's a start:
function getBooks() {
$.getJSON("bookstore.json").done(function (json) {
getBooksDoneFunc(json);
});
}
var getBooksDoneFunc = function(json) {
$.each(json.books, function(i, json){ .......... });
};
...
getBooks();
function signInOK(){
getBooksDoneFunc("some json data");
}

Load body of another html to jQuery and store as javascript var

What I want to do is to read a body content of another html and save it as a var in a javascript function. What I currently have, using jQuery, is $(id of this document).load(link goes here). For example:
$("#test").load("/form.cgi?A1=?")
The form only has a body that contains <body>some value</body>
<a id="test">hello</a> This method works great because I don't have to use DOM at all.
However, I would like to store the data into a javascript variable. So, I think I have half of this done. Could someone shed some light on how to do so?
Ideally, something like:
'function(test)
{
var x = $.load(test);
//manipulate x such as parseInt/parseFloat, etc
}
'
Thanks!
You might want to change your approach to this:
var myVar = '';
$.get('/form.cgi?A1=?', function(data) {
myVar = data;
});
alert(myVar);
It is not possible to access the value of myVar outside the callback function because this Ajax call is asynchronous meaning while the page is being loaded, and the callback function has not been called and the value of myVar has not be changed, the alert statement executes which is why you get empty data.
To retain this answer, make use of the myVar inside the callback function like this:
var myVar = '';
var externalVar = '<p>text</p>';
$.get('/form.cgi?A1=?', function(data) {
myVar = data;
//use myVar here for whatever purpose you want it for
var myNewVar = myVar + ' ' + externalVar;
});
You can use the value of myVar as soon as the callback function is complete which could be 5sec, 30sec etc after the ajax call
<input type="button" value="pol" onclick="alert(myVar);" /> //should work
For further information see the links I posted in the comments
var x = $("#test").load("/form.cgi?A1=?").html();
This should do it if you want the content of the html file as it is.
.load() is short for $.ajax(), so, you can just use a normal Ajax request like so:
jQuery:
var result;
$.ajax({
type: 'POST',
url: '/form.cgi?A1=?',
success: function(data) {
result = data;
},
async: false
// async to false so that we don't access an empty variable before the request is finished
});
Demo: http://jsfiddle.net/SO_AMK/wHXrM/
Building on what codingbiz provided, this is what I currently have. It's not pretty, but it sure does the trick:
$.get( /form.cgi?A1=?, function(data){
document.getElementById("value").innerHTML = data;
var y = parseFloat(document.getElementById("value").innerHTML);
alert(y);
});
The reason why I used document.getElementById("value").innerHTML is to remove the <body> tag that surrounds the desired value (i.e <body>value</body>). This is the only way I know so far on how to parseInt/parseFloat properly. If I don't do this, then it return NaN due to the body tag. If you have a better way, do let me know. Thanks

Variable scope in Javascript Object

I'm discovering the concept of "objects" in JavaScript. I'm making an RSS Parser, and I have an error (commented).
function MyParser (feed_url) { // Construct
"use strict";
this.feedUrl = feed_url;
this.pubArray = [];
if (typeof (this.init_ok) == 'undefined') {
MyParser.prototype.parse = function () {
"use strict";
var thisObj = this;
$.get(this.feedUrl, function (data, textStatus, jqXHR) {
if (textStatus == 'success') {
var xml = jqXHR.responseXML,
//lastBuildDate = new Date($(xml).find('lastBuildDate').text());
items = $(xml).find('item');
items.each(function () {
var pubSingle = thisObj.makeObj($(this).find('pubDate').text(),
$(this).find('link').text(),
$(this).find('title').text(),
$(this).find('description').text(),
$(this).find('encoded').text(),
$(this).find('commentRss').text(),
$(this).find('comments').last().text());
thisObj.pubArray.push(pubSingle);
});
console.log(thisObj.pubArray); // OK
}
}, 'xml');
console.log(this.pubArray); // Empty
return (this.pubArray);
};
MyParser.prototype.makeObj = function (pubDate, pubLink, pubTitle, pubDesc, pubContent, pubComCount, pubComLink) {
"use strict";
var pubSingle = {};
pubSingle.pubDate = new Date(pubDate);
pubSingle.pubLink = pubLink;
pubSingle.pubTitle = pubTitle;
pubSingle.pubDesc = pubDesc;
pubSingle.pubContent = pubContent;
pubSingle.pubComCount = pubComCount;
pubSingle.pubComLink = pubComLink;
return (pubSingle);
};
}
this.init_ok = true;
}
If you look at the console.log(), you'll see that the line // OK is outputting my array correctly.
But later, when returning from $.get, my array is empty.
Does anybody have an idea why, and how to correct that please?
This is not a problem with variable-scope. The problem here is that you're working with asynchronous flow and you're not thinking correctly the flow.
Let me explain:
When you do your .get, you fire a parallel asynchronous process that will request information from the browser, but your main program's flow keeps going, so when you get to your "return" statement, your array has not been filled yet with the response from your get method.
You should use your array from inside the get callback and not outside of it, since you can't guarantee that the array will have the information you need.
Does it make any sense?
Let me know!
Further explanation
According to your comments, you're still doing something like this:
var results = MyParser(feed_url);
//code that uses results.pubArray
And you cannot do that. Even though you're setting your "pubArray" inside your .get callback, you're trying to use pubArray right after you called MyParser and that's before the .get callback is called.
What you have to do, is call your next step on your program's logic from within the .get callback... that's the only way you can be sure that the pubArray is filled with proper data.
I hope that makes it clearer.
This is because your line
console.log(this.pubArray); // Empty
is being called directly after you issue your Ajax request; it hasn't had time to fetch the data yet. The line
console.log(thisObj.pubArray); // OK
is being called inside the Ajax callback, by which time the data has been fetched.
Thank you all, and particulary #Deleteman .
Here is what I did:
$.get(this.feedUrl, 'xml').success(function () {
thisObj.handleAjax(arguments[0], arguments[1], arguments[2]);
$(document).trigger('MyParserDone');
}).error(function () {
$(document).trigger('MyParserFailed');
});
Then, when i enter "HandleAjax", i'm back in my object context, so "this" refers to my object and the right properties. The only "problem" is that I have to set a listener (MyParserDone) to make sure the parsing is finished.

Categories

Resources