I would like the function located in my ajax call to have access to the variable "this" in the scope it's being called from. I would like to avoid as much hard coding as possible and thus I have to ask for help. Here are some ideas though.
- add an optional parameter in the ajax function that will be sent as an argument in the callback call. It won't be pretty but it will surely work.
- Send the object reference with the ajax, receive it with php and send it back, and then access it through the response. This would spare the ajax function but pass the mess to the backend.
// Working ajax function | The problem is below this
function ajax(protocol = "GET", url = "", callback = function(response){ console.log(response); }, data = null){
// Build data
var formData = null;
if(data !== null){
formData = new FormData();
for(var instance in data){
formData.append(instance, data[instance]);
}
}
// Build essential ajax components
var xhr = new XMLHttpRequest();
xhr.open(protocol, url, true);
// Check for state updates
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
callback(xhr.responseText);
}
else{
callback("Error code: " + xhr.status);
}
}
}
// Send it!
xhr.send(formData);
}
// My class
function MyClass(el){
this.target = el;
this.fetch(); // Call the fetch method
}
MyClass.prototype.fetch(){
this; // "This" works perfectly in this scope as it refers to myInstance in this example
ajax("POST", "target/path.php", function(response){
var newEl = document.createElement("div");
newEl.innerHTML = response;
// HERE's THE RPOBLEM
this.target.appendChild(newEl); // "this" refers to the window object..
}, {data: "data"});
}
var myTarget = document.getElementById("myTarget");
var myInstance = new MyClass(myTarget);
<div id="myTarget"></div>