while running these functions, I am calling such web service through which I have to generate session Id.
consider url is correct
I want to know,that I am calling function from onreadystatechange.wheteher it is correct way.
if you have another way please reply.
function getData(_url) {
var xmlhttpRequest = null;
xmlhttpRequest = new XMLHttpRequest();
xmlhttpRequest.open("GET", _url, true);
xmlhttpRequest.send();
xmlhttpRequest.onreadystatechange = function() {
//alert(xmlhttpRequest.status);
if(xmlhttpRequest.readyState == 4)// 4: The Request is complete
{
var request = xmlhttpRequest.responseXML;
var items = request.getElementsByTagName("id")[0].firstChild.nodeValue;
var hashcode = GetHashCode(passwordvalue + items);
var strUrl = commonURL + 'data/' + userName + ';' + hashcode;
data1(strUrl, 'tagname');//calling another function to generate session id
}
}
}
function data1(_url, _tagName)
{
var xmlhttpRequest = null;
xmlhttpRequest = new XMLHttpRequest();
xmlhttpRequest.open("GET", _url, true);
xmlhttpRequest.send();
xmlhttpRequest.onreadystatechange = function()
{
if(xmlhttpRequest.readyState == 4 && xmlhttpRequest.status==200)// 4: The Request is complete
{
var request = xmlhttpRequest.responseXML;
//alert('items .....= '+ request);
var sessionid = request.getElementsByTagName(_tagName)[0].firstChild.nodeValue;
alert('session ID='+sessionid);
}
}
}
Thanks,
i would place xmlhttpRequest.send(); after the onreadystatechange function
Also when you using the GET method you send a null value, that holds zero
Related
I'm trying to comunicate with a server, using XMLHttpRequest in javascript.
How can I pass info to the onload function?
// global variable that containts server response
var reply;
var makeRequest = function(extraInfo) {
var request = new XMLHttpRequest();
request.open(...);
request.onload = handler;
};
var handler = function(data) {
reply = data.target.response;
console.log("Server Reply: " + reply);
};
How can I pass the parameter extraInfo from makeRequest to the handler function? (without using a global variable)
Just use a closure in such way:
...
var makeRequest = function(extraInfo) {
var request = new XMLHttpRequest();
request.open(...);
request.onload = function(data) {
// extraInfo is accessible here
reply = data.target.response;
console.log("Server Reply: " + reply);
};
};
I figured out that passing extra info into the request handler can be done this way: (At least is good for me)
request.open(...);
request.extraInfo = identifier;
request.onload = function() {
identifier = this.extraInfo;
};
The accepted solution didn't work for me, but this did
const params = new FormData();
params.append('selectedValue', selectedValue);
const xhr = new XMLHttpRequest();
xhr.open('post', url, true);
xhr.send(params);
xhr.extraInfo = extraInfo; // <- set your data here
xhr.onload = (e) => {
const data = JSON.parse(xhr.responseText);
alert(xhr.extraInfo) /// <- access it like this
alert(e.target.extraInfo) // <- or like this
//return data;
};
I'm trying to learn how to make an AJAX call using vanilla JavaScript in an effort to move away from JQuery for a little project that I'm working on but don't seem to be getting past xmlhttp.onreadystatechange. Can anyone point to what I'm doing wrong (the function getDVDsAndBluRays() is getting invoked on DOMContentLoaded)? Thanks!
function getDVDsAndBluRays() {
console.log("Getting logged");
var xmlhttp = new XMLHttpRequest();
var url = 'http://www.omdbapi.com/?t=metropolis&y=&plot=short&r=json';
xmlhttp.onreadystatechange = function() {
console.log("Not getting logged");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
var myMovies = JSON.parse(xmlhttp.responseText);
myFunction(myMovies);
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
};
}
function myFunction(myMovies) {
for (var i = 0; i < myMovies.length; i++) {
var title = myMovies[i].Title.toLowerCase().split(' ').join('+');
var year = myMovies[i].Year;
console.log(title + ", " + "year");
}
}
It should be like that, notice the location of open and send functions:
function getDVDsAndBluRays() {
console.log("Getting logged");
var xmlhttp = new XMLHttpRequest();
var url = 'http://www.omdbapi.com/?t=metropolis&y=&plot=short&r=json';
xmlhttp.open('GET', url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
console.log("Not getting logged");
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log('responseText:' + xmlhttp.responseText);
var myMovies = JSON.parse(xmlhttp.responseText);
myFunction(myMovies);
}
};
}
function myFunction(myMovies) {
for (var i = 0; i < myMovies.length; i++) {
var title = myMovies[i].Title.toLowerCase().split(' ').join('+');
var year = myMovies[i].Year;
console.log(title + ", " + "year");
}
}
onreadystatechange is executed after the call, you were actually "calling the service when it replies"
You have your .open() and .send() inside your onreadystatechange() handler. Put those outside of the onreadystatechange function and you should be good to go.
Onreadystatechange() is the event handler for when there is a change in state in the xmlhttp request, and will not get called until you open the request and send it.
Hope this helped!
You have put the calls to open and send inside the onreadystatechange event handler so they will never be called.
Move them outside it.
Is it possible to make an ajax post without having an HTML form? And if it is how should i do it and what PHP variable is used to fetch the variable? The PHP is inside the fetched file. I'm not using any framework.
function ajax(instruction, push, url, callback){
var xmlhttp; // the object for the httprequest
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() { // every time the readystate changes
ajaxLoad(xmlhttp.readyState); // Calls function with the ready state each time it uppdates
if (xmlhttp.readyState == 4) { // status 200 = sucessfull page! NOT 404! // 1 2 3 4 are states of the request (4 is when it's done)
// When load bar is complete
if(xmlhttp.status == 200){
callback(xmlhttp.responseText); // goes to the callback function (from the argument "callback") and then passes the xmlhttp
}
else if(xmlhttp.status == 404){ // Could not find file
ajaxError() // Function that will call the ajax but with the error file
}else{}
ajaxDone(); // activates all the nessesary js to check what to do with some parts of the site
}
else{}
};
xmlhttp.open(instruction,url, true); // sends a the var q to the next php file
if(instruction === "GET"){
xmlhttp.send(''); // Sends the request
}
else if(instruction === "POST"){
xmlhttp.send(url); // Sends the request
}
else{
console.log("This ajax does not support " + instruction + " requests.");
}
if(push == true){ // Change the link to the url of the ajax with
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname; // where the host is on
if(url == "home.php"){ // If it's the starting page REMOVE THE ?p= !!
var urlPath = window.location.protocol + "//" + window.location.host + window.location.pathname;
window.history.pushState({path:urlPath},'','./'); // an empty url push (!REMOVE THE DOT WHEN THE SITE IS HOSTED PROPERLY)
return; // exit's the function
}else{}
var newLink = "?p=" + url; // Gives us the link we want except that we don't want the .php
newLink = newLink.substring(0, newLink.indexOf('.')); // makes a new string with character 0 to the dot! Will not include the ending of the file
window.history.pushState({path:urlPath},'',newLink); // the push
}
else{}
}
To page 1
You can find some answers here, about how to make Vanilla JS Ajax call:
http://www.sitepoint.com/guide-vanilla-ajax-without-jquery
About to send without forms, you already have the response here:
Send POST data using XMLHttpRequest
You can get your params server-side(php) with the global variables $_GET["your_param_name"] and $_POST["your_param_name"], they are arrays so I think you know how to use them.
Of course, you can make AJAX request in pure js, even jquery handle ajax request in pure js in behind.
JavaScript:
var ajax = {};
ajax.x = function () {
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
return xhr;
};
ajax.send = function (url, callback, method, data, async) {
if (async === undefined) {
async = true;
}
var x = ajax.x();
x.open(method, url, async);
x.onreadystatechange = function () {
if (x.readyState == 4) {
callback(x.responseText)
}
};
if (method == 'POST') {
x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
}
x.send(data)
};
ajax.get = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url + (query.length ? '?' + query.join('&') : ''), callback, 'GET', null, async)
};
ajax.post = function (url, data, callback, async) {
var query = [];
for (var key in data) {
query.push(encodeURIComponent(key) + '=' + encodeURIComponent(data[key]));
}
ajax.send(url, callback, 'POST', query.join('&'), async)
};
Call Ajax Method: I will recommend you to not use it in onclick.
ajax.get('ajax.php',{DATA_TO_PASS},function(response) {
//Do something with response
console.log(response);
},true);
$_GET to receive the ajax data;
OR:
ajax.post('ajax.php',{DATA_TO_PASS},function(response) {
//Do something with response
console.log(response);
},true);
$_PSOT to receive the ajax data;
You don't need a form to use ajax post.
$.post( "test.php", { 'choices[]': [ "Jon", "Susan" ] } );
as the same way you are using form you can fetch the values from php using $_POST
At the moment I am calling a function on a setInterval basis.
This function makes a XMLHttpRequest to my server to get update info. If there is an update available I update an image (using canvas element).
Is this the optimum way to do this sort of thing?
My code:
Calling code:
function StartFeedUp() {
if (tmrStartFeedUp) window.clearInterval(tmrStartFeedUp);
tmrStartFeedUp = setInterval(GetNextImage, 330);
}
My called function:
var isProcess = false;
function GetNextImage() {
try {
if (!isProcess) {
isProcess = true;
var urlTS = '/Cloud/isNewFrames.ashx?alias=' + alias + '&version=' + version + '&guidlogon=' + guidlogon;
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", urlTS, true);
xmlhttp.timeout = 200;
xmlhttp.send();
var nextts = xmlhttp.responseText;
}
isProcess = false;
}
catch (err) {
isProcess = false;
document.getElementById("divMode2").innerHTML = err;
}
}
Other than repeating the XHR call, you can use HTML5 Web Sockets which allows you to maintain a connection to the server, whereby the server would push data as and when needed. Web Sockets are relatively new and so aren't supported by old browsers.
Your XHR is asyncronous so you should be listening on the onreadystatechange event instead of always expecting the response to be available directly after the send() call:
xmlhttp.open("GET", urlTS, true);
xmlhttp.timeout = 200;
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
console.log("received " + xmlhttp.responseText);
}
}
xmlhttp.send();
I have some problem with transfer of variable outside the function.
It's seems to be very simple but I have some problem with it.
var myJson;
var url = "https://openbook.etoro.com/api/Markets/Symbol/?name=" + symbol;
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", "proxy.php?url=" + url, true);
xhr.send(null);
function XHRhandler() {
if (xhr.readyState == 4) {
var json;
if (JSON && JSON.parse) {
json = JSON.parse(xhr.responseText);
} else {
eval("var json = " + xhr.responseText);
}
console.log(json);
myJson= json;
xhr = null;
}
}
console.log(myJson);
What I need is to pass the data from local variable json to global myJson;
But when i do console.log(myJson) i get undefined.
What is the problem?
Thank you
Try moving the statement console.log(myJson); inside your if condition or alternately initialize your variable with some value. It seems your statement is getting called before it is getting populated with any value.
The XMLHttpRequest is async so it is not done yet when you try to write the myJson variable to console. Wrap it in a function and call that function after the XMLHttpRequest is completed instead.
var myJson;
var url = "https://openbook.etoro.com/api/Markets/Symbol/?name=" + symbol;
var xhr = (window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"));
xhr.onreadystatechange = XHRhandler;
xhr.open("GET", "proxy.php?url=" + url, true);
xhr.send(null);
function XHRhandler() {
if (xhr.readyState == 4) {
var json;
if (JSON && JSON.parse) {
json = JSON.parse(xhr.responseText);
} else {
eval("var json = " + xhr.responseText);
}
console.log(json);
myJson= json;
xhr = null;
writeToConsole();
}
}
function writeToConsole() {
console.log(myJson);
}