Jquery callback function variables always local? - javascript

Why cant i set the $('#temizle').innerHTML to string 'Temizlendi';
The code blow just doesnt work. But in the line before end i can set it. I'm confused.
$('#temizle').click(function(){
$.post('OdbcConnection.php',
{islem: 'Temizle'},
function(data, status){
if(status == 'success'){
alert(status);
$('#temizle').innerHTML = 'Temizlendi';
}else{
this.innerHTML = 'Hata Var';
}
});
//this.innerHTML = 'Temizlendi';
});

The short answer is because innerHTML is a native DOM node method, not a jQuery method, therefore calling it on a jQuery object such as $('#temizle') does nothing but set a new innerHTML property in the jQuery object. It works outside of your $.post call because this inherits a native DOM node, not a jQuery object.
Try using the $.html() method instead of innerHTML:
$('#temizle').html('Temizlendi');
Alternatively, outside of the scope of your $.post could also be re-written from this.innerHTML to $(this).html(), as wrapping this would convert it into a jQuery object.
If you absolutely have to use innerHTML rather than the jQuery method, as mentioned in other answers you can also get a DOM node from a jQuery object by using the get() method or accessing the node at the 0 index of the jQuery object:
$( '#temizle' ).get(0).innerHTML = 'Foo';
$( '#temizle' )[0].innerHTML = 'Bar';
Although that would sort of defeat the purpose of using jQuery.
Another thing to remember is that the value of this depends on the current scope, so this will not be equal to your element when it is called inside of your $.post. To get around this, you could cache your element outside of the scope of your post call so you can easily refer back to it within the callback:
$('#temizle').click(function(){
var $el = $( this );
$.post('OdbcConnection.php',
{islem: 'Temizle'},
function(data, status){
if(status == 'success'){
alert(status);
$el.html( 'Temizlendi' );
}else{
$el.html( 'Hata Var' );
}
});
//$el.html( 'Temizlendi' );
});
To get a better understanding of this, I'd highly recommend checking out the MDN reference on it here.

Is alert(status) getting called? If not this simply means your POST request failed.
If it indeed fails, check if the path to the php file is right. What you have now is a relative path, maybe you need to turn it to an absolute one,
ie.: change 'OdbcConnection.php' to '/OdbcConnection.php' or '/{SOME_FOLDER}/OdbcConnection.php'

first you have to write
$('#temizle').html('Temizlendi') //not $('#temizle').innerHTML='Temizlendi'
or you can use
$('#temizle')[0].innerHTML ='Temizlendi'
second:you used
this.innerHTML = 'Hata Var';
but "this" is for function not for $('#temizle') element

When you use $('#temizle').InnerHTML, you're calling the method innerHTML, which belongs to DOM objects, but not the jQuery objects. In this case you should use the html() method of jQuery:
$('#temizle')html('Temizlendi');

Related

Access "this" in Fuel UX placard onAccept function

I have several Fuel UX placards on a page, with a single jQuery selector to initialize them all. I need to write a custom onAccept function to handle placard confirmation.
It seems like I should be able to access $(this) from within the onAccept to access the element being initialized, but it just points to the window object.
How can I go about accessing the current element in a placard onAccept function?
Here's my code for reference:
$(".select-user-placard").placard({explicit: true, onAccept: function (helpers) {
DMSC.UpdateUser(DMSC.SelectedForm.Id, $(this).data("field-type"), helpers.value);
}});
I need to call this function passing a parameter that is retrieved from a data-attribute on the element, but I'm not sure how I can access the current element without the use of this.
I guess I was kind of thrown by the no access to this and I couldn't think of the obvious solution:
$(".select-user-placard").each(function (index, element) {
var $element = $(element);
$element.placard({explicit: true, onAccept: function (helpers) {
DMSC.UpdateUser(DMSC.SelectedForm.Id, $element.data("field-type"), helpers.value);
}});
});
Instead of calling placard on the jQuery selector, I iterate over each using jQuery's each and just use the jQuery iterator to select that element's data.

Use $.post to append to html before adding an attribute

I am using $.post to get an html page. I then need to take this data and append it to the current DOM. However, I need to modify the attributes first, before appending:
I tried the following, but it didn't work:
$.post(link, function (data) {
$(data).css('display', 'none');
$('#page').append(data);
});
data is a string value, when you use $(data) it returns a jQuery object for the given markup but the changes made in the jQuery object will not get reflected in the string referred by data. So when you use data again in the append() operation the changes done before is lost.
As a solution you can store the reference to the jQuery object reference you created in the first step and then use that reference in the append() operation.
$.post(link, function (data) {
var $data = $(data);
if (somecondition) {
$data.css('display', 'none');
}
$('#page').append($data);
});

load() API call function callback scope

I have been coding in JS for a while now, but somehow I always get a bit of a 'scratch head' type of problem. I think that I need to do some digging in, but in the meanwhile can someone help with this one?
So here is the problem:
I am passing through the item (got by $(this)) into the callback function. This code does not work - when I really think it should. Since I have placed the $(this) into a variable (cloning the data?) and then passed it into the callback through a function, surely it should not loose the data? But it does, and horribly
// Allow hrefs with the class 'ajax' and a rel attribute set with a selector to load via ajax into that selector.
$(".ajax").unbind("click").click
(
function(e)
{
var locationhint = $(this).attr("rel");
var $location = $(locationhint);
$location.html ("<img src='images/blockloading.gif' />");
$location.load($(this).attr("href").replace("index.php", "ajax.php"), '', function($location){dready($location);});
e.preventDefault();
}
);
Now that doesn't work.
This one works:
$(".ajax").unbind("click").click
(
function(e)
{
$("#myspecificdiv").load($(this).attr("href").replace("index.php", "ajax.php"), '', function(){dready($("#myspecificdiv"));});
e.preventDefault();
}
);
I take it it's a scope problem, but I have also done this, which should work because it's exactly the same as the 'static' one above, essentially, because it's passing the text ID of the element. This one also breaks:.
$(".ajax").unbind("click").click
(
function(e)
{
var locationhint = $(this).attr("rel");
var $location = $(locationhint);
$location.html ("<img src='images/blockloading.gif' />");
var locationid = "#" + $location.attr("id");
$location.load($(this).attr("href").replace("index.php", "ajax.php"), '', function(locationid){dready($(locationid));});
e.preventDefault();
}
);
The broken ones, when I console.log locationid, return the internal HTML of the target DIV. $location.attr("id"); can't return raw HTML when there is no call to it anywhere else surely? So it's scope I take it? But then how is it getting the internal HTML to spit out?
Any solutions?
Update:
12 seconds after I posted this it occurred to me that function($location){dready($location);} the internal function on the callback might automagically pass the AJAX call response through? But why?
You cannot do this function($location){dready($location);} but you do not need to since the outer scope has $location defined the callback func will understand this var without trying to pass it into the callback funcion so in this instance
function(){dready($location);}
will work.
Another way to conquor scoping issues is to use $.proxy. This allows you to set the this context under which the function will be called. jQuery.proxy( dready, $location ) returns a function that can be used as a callback which when invoked will call the method dready with this set to to $location.
e.g
$location.load($(this).attr("href").replace("index.php", "ajax.php"), '', jQuery.proxy( dready, $location );});

Javascript scope help

I am relatively new to javascript so please be patient if what i am asking is completely stupid!
I am trying to make a simple module. Inside the module i want to have a config object that holds settings for the module. I am also using jquery. The jquery selectors work only when in a function directly in the main object/module.
I understand that javascript has functional scope so I am suprised that I cannot use the jquery selectors anywhere inside the module.
EDIT:
I want to be able to directly set all of my configs inside the configs object using jquery selectors. This way i keep all the messy stuff inside one place and can then access configs.whatever throughout the rest of the module. At the moment jquery selectors do not work inside the configs module.
var OB = function() {
var configs = {
'mode' : 'test',
'numOfSelects' : $('.mySelect').find('select').length, // This doesnt work
}
var getMode = function() {
return configs.mode;
}
function init() {
alert(configs.numOfSelects); // This alerts 0 until the following line
alert($('.mySelect').find('select').length); // This correctly alerts 2
};
var handlers = {
successHandler : function() {
alert("Success");
},
errorHandler : function() {
alert("error");
}
}
return {
init : init,
getMode : getMode
}
}( );
$(document).ready(function(){
OB.init();
});
It isn't that jQuery isn't in scope — that's that the code isn't executing when you think it is. The variable config is defined when that anonymous function (var OB = function() {}()) is executed. The DOM isn't ready yet, so that DOM traversal doesn't find anything. When you do the DOM traversal in init(), that isn't executed until it's explicitly called inside the $(document).ready() handler, at which point that DOM is set up. That's the difference you're seeing.
OB() needs to be called after the DOM has completely loaded. Hence the answer by Marcelo, which calls OB() in the ready() method.
EDIT: It's funny that my original answer below was incorrect because I didn't notice two little parentheses at the end of the definition of OB, and it turns out that these are the culprit. You define and then immediately invoke OB, which is before the DOM has been fully loaded. Remove those parentheses and make the change I suggest below.
Calling OB() returns an object with init and getMode, but you haven't called OB(), you've only referred to OB. Try this instead:
$(document).ready(function(){
OB().init();
});
Also, I assume you want to later refer to getMode. In particular, you will to get the copy of getMode that has access to the same local scope that your init() call had access to. To achieve this, you will need to store the result of calling OB() for later use:
var ob;
$(document).ready(function(){
ob = OB();
ob.init();
});
function some_other_function() {
... ob.getMode() ...;
}

How can I create functions in jQuery and call it on event and pass variable to it?

$(".addcart").click(function(){
$("input[name='items']:checked").each(function() {
//doing something
});
});
I'm trying to create a common class onclick of which I'm doing something. Is there a way I can make "items" a variable, I mean Can I pass checkbox name to this event.
Try this and see if it works out:
$("input[name='items']:checked").each(function() {
alert(this.attr("name"));
});
I think I've used like this somewhere.
[EDIT]
The thing with this is that jQuery passes the current item to the foreach as the context of the variable.
Use bind instead of click
$(".addcart").bind("click", {name: "items"}, function(event){
$("input[name='" + event.data.name + "']:checked").each(function() {
//doing something
});
});
edit:
"How can I create functions in jQuery
and call it on event and pass variable
to it"
That will still be the same procedure. Use bind to attach an event handler, pass it an object with the needed stuff for your function. In your event handler call your function and pass it the object from event.data
$(".addcart").bind("click", {foo: "hello world"}, function(event) {
DoSomethingOnClick(event.data);
});
function DoSomethingOnClick(obj) {
obj = obj || {};
if (obj.hasOwnProperty('foo'))
alert(obj["foo"]);
else
alert("no foo here");
}
You know that all checked items will have a name of items, so that's not very interesting, but maybe you want to retrieve the value of each of the items:
$(".addcart").click(function(){
$("input[name='items']:checked").each(function() {
// To access an attribute of this item use the form $(this).attr(...)
alert( this.value );
});
});
The above uses this to access the element being iterated over. Take a look at the properties of a DOM element to see what properties of this you can access.
You can create a jQuery object out of this using the form $(this) then you can use .attr() to access the attributes of this. For example to get the class/es of this you can use either this.className or $(this).attr("class").
It is faster to directly access the DOM element's properties. But for some more complex manipulations it is good to know that $(this) is also available.

Categories

Resources