jas jas - 24 days ago 6
Javascript Question

How to correctly update div during xhrHttpRequest using "this"

I'm trying to update value of divToUpdate in same parentDiv where Button is clicked upon successful xhrHttpRequest. I have passed this object as a parameter to the function that sends the xhrHttpRequest but I'm unable to update the div: divToUpdate

<div class="parentDiv" >
<div class="divToUpdate" style="display:none"></div>
<div class="btn-group">
<button class="button" type="button" >Update</button>
</div>
</div>
<div class="parentDiv" >
<div class="divToUpdate" style="display:none"></div>
<div class="btn-group">
<button class="button" type="button">Update</button>
</div>
</div>


JS Code (minimal sample code)

$(function()
{
function bindKeyPress()
{
$(document).keyup(function(event) {
switch(event.which) {
case 37: // left
//do something
break;
case 38: // up
send(url,data,this);
break;
}
});
}
});

function send (url,data,this)
{
var xhr = new XMLHttpRequest();
var instance = this;
xhr.open('POST', url, true);
xhr.onreadystatechange = function ()
{

if (xhr.readyState === 4 && xhr.status === 200)
{
var text = xhr.responseText;
var jsonResponse = JSON.parse(text);
var filename = jsonResponse.filename;
$(instance).closest('.parentDiv').children('.divToUpdate').text(filename);
}
}
xhr.send(data);
}


How can I update correct div corresponding to where button is clicked ?

Answer

You cannot name an argument this. Instead set the desired context with the use of .call(): that way send will have this defined as you intend:

   send.call(this, url, data);  
   // ...

function send (url, data) // no this here
// ... you can use `this` here...

If you want the clicked element to be the value of this then call send as follows:

   send.call(event.target, url, data);  
Comments