To pass parameters to Result handler function in javascript - javascript

I am making XMLHttpRequest to call Google search API URL. And on getting the response I want to call another result Handling function. But I also want to pass the parameter to it.
request = new XMLHttpRequest();
if(request) {
var url = "http://localhost:8080/final_project/SearchService";
url += "?user_query=" + getQueryString();
request.onreadystatechange = handleSearchResult;
request.open("GET", url, true);
request.send(null);
}
Here handleSearchResult is resultHandler and I want to pass parameter to this function. But if I do so the function gets called directly.
What can be done to solve this problem?

Surround it using a closure:
request.onreadystatechange = function() {
handleSearchResult(yourParameter);
}

Related

Call MVC Controller Method from TypeScript/JavaScript without jquery

Is it possible to call MVC Controller Method with Ajax call in Type Script/JavaScript without Jquery? if not How I can Call Controller Method from JavaScript/Type Script file?
Consider a method that is calling Controller method to sort and send a sort column to it:
This is function in ts file:
function SortData()
{
.... call Controller method and send sortCriteria (FullName) to it
}
and this is Controller method:
[Route("sortbycolumn")]
public ActionResult SortByColumn(string sortCriteria)
{
.... Do the sort retun back json result
}
Of course you can. In fact, jQuery is library based on javascript and it is not an independent language. Here is what you have to do:
function SortData(){
// Every ajax call is an XMLHttpRequest
var xhttp = new XMLHttpRequest();
// It means that your request is processed asynchronously.
// So we need to define the method that has to be run once the response is received,
xhttp.onreadystatechange = function() {
// status 200 means that your request has been processed successfully.
if (this.readyState == 4 && this.status == 200) {
// Change your html here
}
};
// Setting your request
xhttp.open("POST", "mycontroller/myaction", true);
// Send your request when everything is set.
xhttp.send();
}
If you need more to know, check out this link: https://www.w3schools.com/xml/ajax_intro.asp
I've included an example of a GET and a POST + submitting/receiving data using vanilla JS & AJAX below.
For further info, give this a read.
Good luck.
function SortData() {
var data;
//Post Example
var xhttp = new XMLHttpRequest();
xhttp.open("POST", "/Controller/Action", true);
xhttp.setRequestHeader("Content-Type", "application/json");
//There are two options for using xhttp.send(): Only keep the ONE that applies to you
//Option 1: Submit data to the server
xhttp.send(JSON.stringify(params));
//OR
//Option 2: Nothing to submit to the server
xhttp.send();
xhttp.onload = function(response) {
if(response.target.status == 200) {
data = JSON.parse(response.target.response);
}
};
//Get Example
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "/Controller/Action", true);
xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
//There are two options for using xhttp.send(): Only keep the ONE that applies to you
//Option 1: Submit data to the server
xhttp.send(JSON.stringify(params));
//OR
//Option 2: Nothing to submit to the server
xhttp.send();
xhttp.onload = function(response) {
if(response.target.status == 200) {
data = JSON.parse(response.target.response);
}
};
}

Multiple http requests by same js file

i have a problem with my file js that call multiple http requests.
I have a button that call the function VisualizzaReport that is in my file visualizzaReport.js
Here is the function VisualizzaReport(select is the ID of the user)
function visualizzaReport(select){
reportUtente(select)
loadPianificazione(select)
}
Here the function reportUtente(select)
function reportUtente(select) {
var url = "../loadReportUtenteServlet?";
url += "type=perso_atti&value=" + select.value;
xmlhttp.onreadystatechange = handlerForReportUtente;
xmlhttp.open("GET", url);
xmlhttp.send("");
}
Here the function loadPianificazione(select)
function loadPianificazione(select) {
var url = "../loadPianificazione2Servlet?";
url += "type=pianificazioni&value=" + select.value;
xmlhttp.onreadystatechange = handlerForPianificazioneUtente;
xmlhttp.open("GET", url);
xmlhttp.send("");
}
my problem is that the function reportUtente is launched but has not effect because it seems that it is substitute by loadPianificazione function.
How can i call loadPianificazione only when reportUtente has finished his execution?
In your case I suggest you use either jQuery or AngularJs for this purposes.
jQuery example:
$.get('url1.com', function(){
$.get('url2.com');
})
You will request url2.com only when first request has finished.
You appear to be using a single, global xmlhttp variable.
Then you call two functions which do things with it. The second one will overwrite xmlhttp.onreadystatechange before the first request has finished so the second function you put there will be called for each request.
Don't do that. Create a new instance of XMLHttpRequest for each request, and keep it in a local scope so that it doesn't interfere with other instances.
function reportUtente(select) {
var url = "../loadReportUtenteServlet?";
url += "type=perso_atti&value=" + select.value;
var xmlhttp = new XMLHttpRequest(); // New instance here
xmlhttp.onreadystatechange = handlerForReportUtente;
xmlhttp.open("GET", url);
xmlhttp.send("");
}
You haven't shared handlerForReportUtente but it should look something like:
function handlerForReportUtente() {
alert(this.responseText); // Use `this` to get the right XHR object
}

Returning ajax data to different functions corresponding to different links

I'm at peak-frustration trying to resolve my mental block re: callbacks. I've read How to return value from an asynchronous callback function? and How to return the response from an Ajax call? (among many other posts), and indeed the latter was helpful with another problem. However what I'm trying to do now is just slightly different and I'm losing my mind trying to adapt it to my code. Maybe my approach is entirely wrong/fundamentally flawed (and not just immature, which I can live with)?
The essence of my problem is that rather than simply returning ajax result to a callback function, I need the resulting json to be available to different functions, corresponding to different events, i.e.:
linkOne.onclick = invoke ajaxReq + getJsonData, then call functionOne with getJsonData result as an argument
linkTwo.onclick = invoke ajaxReq + getJsonData, then call functionTwo with getJsonData result as an argument
linkThree.onclick = invoke ajaxReq + getJsonData, then call functionThree with getJsonData result as an argument
Can't this be done with the link.onclick definition? Why doesn't this work:
linkThree.onclick = functionOne(getJsonData);
Here's my code:
function ajaxReq() {
var request = new XMLHttpRequest();
return request;
}
function getJsonData() {
var request = ajaxReq();
request.open("GET", "/myJSON.json", true);
request.setRequestHeader("content-type", "application/json");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
var myJsonString = JSON.parse(request.responseText);
var myJsonArray = myJsonString["An Array in myJSON.json"];
// functionOne(myJsonArray); // callback: what if I need to pass this value to various functions?
return myJsonArray; // ... 'cause this ain't doin' it, and I don't know why
}
}
} // onreadystatechange
} // getJsonData
function functionOne(myJsonArray) {
var myJsonArray = getJsonData(); // why doesn't this work, since, in getJsonData, var request = ajaxReq(); returns an ajax request ?
}
And why, if var request = ajaxReq(); invokes ajaxReq function and returns its result to getJsonData, does var myJsonArray = getJsonData(); in functionOne not do the same?
Any help with this is much appreciated. (p.s. seeking a pure javascript fix, not jQuery.)
svs
As it has been answered in the links you have specified, that we cannot return value from asynchronous call to use it in a synchronous function call. So here is the trick -
Assign all the onclick listeners a common function.
link1.onclick = someCommonfunction;
link2.onclick = someCommonfunction;
link3.onclick = someCommonfunction;
And define the common function like following, which will have json data in the callback, and you can pass that data to any function call.
function someCommonfunction(e) {
/* this is the function which will be finally executed with json data after clicking */
var callback = function(jsonData) {
var myJsonArray = jsonData;
//do some condition check and call functionOne, functionTwo or functionThree
};
getJsonData(callback);
}
I modified getJsonData to call callback with the response data.
function getJsonData(callback) {
var request = ajaxReq();
request.open("GET", "/myJSON.json", true);
request.setRequestHeader("content-type", "application/json");
request.send(null);
request.onreadystatechange = function() {
if (request.readyState === 4) {
if (request.status === 200) {
var myJsonString = JSON.parse(request.responseText);
var myJsonArray = myJsonString["An Array in myJSON.json"];
callback(myJsonArray);
}
}
} // onreadystatechange
} // getJsonData

Passing variable to PHP file

So I'm not too sure if I'm going to be able to explain this in a way that someone will be able to help me but here it goes:
When I call the function getFishing() I want it to get the "username" Element and put it in a var called get_name, then I want it to send that variable over to the XML_Fishing.php file where is is then used in a mysql query which is then parsed to XML data which is then re-read by the fishingUrl() function. The issue right now is that it's not passing the get_name variable to the XML_Fishing.php file. Can anyone see why from the code below? I didn't give the entire fishingUrl function because it is not relevant to the passing of the variable. It's just the rest of the function, after the data is returned from the XML data.
function getFishing(){
var get_name = escape(document.getElementById("username").innerHTML);
var name = "XML_Fishing.php?username=" + get_name;
fishingUrl(name, "XML_Fishing.php", function(data) {
............
............
............
}
function fishingUrl(name, url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
name is not being passed to the AJAX request - try changing
fishingUrl(name, "XML_Fishing.php", function(data)
to
fishingUrl(name, name , function(data)
that will make first parameter redundant - unless it was being used in the callback function.
This will set $_GET['username'] in the PHP script to the value of get_name from the Javascript

AJAX responseText not getting anything

I wrote this simple AJAX script:
var request;
function createRequest(){
request = null;
try{
request = new XMLHttpRequest();
}catch(failed){
request = null;
}
if(request==null){
alert("Incompatible Browser");
}
}
function getProd(form){
createRequest();
var w = form.list.selectedIndex;
var cat = form.list.options[w].text;
var url = "showProd.do?prodCat=" + cat;
request.open("GET",url,false);
//Send request to server
request.onreadyStateChange = updatePage();
request.send(null);
}
function updatePage(){
//if(request.readyState == 4){
//add your code here
var options = "Bloody Server";
options = request.responseText;
//docWrite(options);
alert(options);
//}
}
I used firebug to check the response i was getting from server. Its absolutely fine and is of type "text/html".
Problem is it doesn't show up in alert box!
By writing request.onreadyStateChange = updatePage(), you are calling the updatePage function and assigning its return value to onreadyStateChange (which, by the way, must be lowercase)
You need to assign the function itself to onreadystatechange without calling it by removing the ().
For example:
request.onreadystatechange = updatePage;
Note that using a global request variable is a horrible idea; your code cannot send two requests at once.
I highly recommend that you use an existing AJAX framework, such as jQuery's, instead.
umm, you are calling your update function on every state change and all but the last will be before there is any data available, resulting in undesirable results.
You need to update your page when readystate==4
createRequest();
....
request.open("GET",url,false);
//Send request to server
request.onreadyStateChange = function(){
if(request.readyState == 4){
//add your code here
var options = "Bloody Server";
options = request.responseText;
//docWrite(options);
alert(options);
}
};
request.send(null);
....

Categories

Resources