update ajax send() content - javascript

I'm trying to receive data from ajax call and then send this data back using ajax.
javascript code:setInterval (function ()
{
var xmlhttp = new XMLHttpRequest();
var content = "data=1";
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
content = "data=" + xmlhttp.responseText;
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST" , "execute-page.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(content);
},5000);
the problem now is that it keeps sending the old content. how can I update content variable with ajax response text?

Move the line var content = "data=1"; out of the function:
var content = "data=1";
setInterval (function ()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
content = "data=" + xmlhttp.responseText;
alert (xmlhttp.responseText);
}
}
xmlhttp.open("POST" , "execute-page.php" , true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(content);
},5000);

Related

Ajax doesn't fire onreadystatechange

I know the URL is working as intended as i logged that to the console and it is fine. However I can't get "Good News" to log to the console when readyState == 4 and status == 200. I tried removing readState and it still wouldn't log. I tried logging the status and It would only fire once with a value of 0. This is the first time I am working with Ajax so any help is appreciated.
function setupRequest(){
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData () {
console.log('ran')
var url = 'localhost/bev/drinks.php';
var data = document.getElementById('input').value;
url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
request.send;
console.log('sent')
}
You need to actually call send(). You aren't doing anything whenever you say request.send;
function setupRequest() {
var bttn = document.querySelector('#send');
bttn.addEventListener('click', sendData)
}
setupRequest();
function sendData() {
console.log('ran')
var url = 'https://jsonplaceholder.typicode.com/posts';
var data = document.getElementById('input').value;
//url += '?' + 'alcohol=' + data;
console.log(url)
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('good news')
console.log(this.responseText)
} else {
console.log(this.status)
}
}
request.open('GET', url, true);
// You wrote (without parentheses):
///////////////////
// request.send; //
///////////////////
// You need to write
request.send();
console.log('sent')
}
<button type="button" id="send">Btn</button>
<input type="text" id="input">

Ajax function in javascript is not working in mozilla firefox browser, why?

Follownig is my javascript code, ajax function is used to read response from
server. but xmlhttp.status is always 0 in firefox browser, why? please help me.
function ajaxAsyncRequest() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveObject("Microsoft.XMLHTTP");
}
//creating asynchrounous GET request
var tempValUrl = $(".urlVal").val();
var urls = tempValUrl + '/Department/departmentAdminTokenReceive';
xmlhttp.open("GET", urls, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
alert("readyState"+xmlhttp.readyState);
alert("status"+xmlhttp.status);
if (xmlhttp.status == 200) {
var data = xmlhttp.responseText;
//for signing
var signarr = data.split("$$");
//for signing
document.getElementById('signName').value = signarr[1];
document.getElementById('signCertName').value = signarr[2];
document.getElementById('signCa').value = signarr[3];
document.getElementById('signExpiryDate').value = signarr[4];
document.getElementById('signPublicKey').value = signarr[5];
}
}
}
}

How do I make an HTTP request to bitstamp?

I'm trying to use an API from bitstamp to fetch a currency trading price on my webpage.
I have researched this problem, but I still cannot get it to work as it always returns ERROR
The link used is https://www.bitstamp.net/api/ticker/ and the response should be last
Here is my code:
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
}
else {
window.alert("ERROR");
} }
Try this:
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var jsonRes= JSON.parse(this.responseText);
if (jsonRes.hasOwnProperty('last')) {
document.getElementById("demo").innerHTML =
jsonRes.last;
alert(jsonRes.last);
}
}
};
xhttp.open("GET", "https://www.bitstamp.net/api/ticker", true);
xhttp.send();
}
<h2>Using the XMLHttpRequest object</h2>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
<p>last attribute is: <span id="demo"></span></p>
Here is one way:
<script src="./jquery.min.js">
//none secure web page ?
jQuery.get("https://www.bitstamp.net/api/ticker/", function (data, status)
{
// use response here; jQuery passes it as the first parameter
var response = JSON.parse(data);
window.alert(response.last);
console.log("MyFunc: " + "response : " + response + "\nStatus: " + status);
});
</script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "https://www.bitstamp.net/api/ticker/", true);
xhr.send();
xhr.addEventListener("readystatechange", processRequest, false);
function processRequest(e) {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
var response = JSON.parse(xhr.responseText);
window.alert(response.last);
} else {
window.alert("ERROR");
}
}
}

Loop Calling Function in Native Ajax

Here's my native ajax code:
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined'){
alert('Data Found:' + result);
//start: new request data for #valdata
xmlhttp.open("POST", "inc.php?q="+str, true);
document.getElementById("valdata").value = xmlhttp.responseText;
xmlhttp.send(null);
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined'){
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q="+str, true);
xmlhttp.send(null);
}
From the code, let me explain that:
I want to get data/value from result and dataval. After I get the data, I execute script_dkill() function.
However, It creates loop and never get to script_dkill.
So, the question is: How to get to script_dkill and execute it?
For example:
The script_dkill() has content as follow:
function script_dkill(){
alert('Hallo, you call me!');
}
Any help, please...
You need to use a different XMLHttpRequest object for the second request, since you are using the same object it will call the same onreadystatechange event again and again
function script_grabbed(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("numvalue").value = xmlhttp.responseText;
var result = document.getElementById("numvalue").value;
if (typeof result !== 'undefined') {
alert('Data Found:' + result);
//start: new request data for #valdata
var xmlhttp2 = new XMLHttpRequest();
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
document.getElementById("valdata").value = xmlhttp2.responseText;
var dataval = document.getElementById("valdata").value;
if (typeof dataval !== 'undefined') {
alert('Data Bound:' + dataval);
//continue to call maps
script_dkill()
}
}
}
xmlhttp2.open("POST", "inc.php?q=" + str, true);
xmlhttp2.send(null);
//end: new request data for #valdata
}
}
}
xmlhttp.open("POST", "inc_num.php?q=" + str, true);
xmlhttp.send(null);
}

Json object successfully filled with xmlhttprequest suddenly is "null"

function getOptionsData()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
json_options = JSON.parse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "getData.php", true);
xmlhttp.send();
}
"json_options" is a global variable, which should get filled with the responseText of the XMLHttpRequest, which is containing a valid json String:
[{"id":"3","model":"NZ\/","model1":"","tablenr":"1","tabkey":"SSG\/","length":"4","descript":"Schukostecker gerade","matchcode":"","price":"0","pricex":"0","code":"1","textnr":"0","artikelnr":"0","funktion":"Seite 1"},{"id":"4","model":"NZ\/","model1":"","tablenr":"1","tabkey":"SWS\/","length":"4","descript":"Schuko gewinkelt \/ angled 90 Grad","matchcode":"","price":"0","pricex":"0","code":"1","textnr":"0","artikelnr":"0","funktion":"Seite 1"}]
At this point everything is fine and json_options contains a valid json Object.
The function "getOptionsData" gets called in the function "createOptionsTable":
function createOptionsTable()
{
getOptionsData();
var element = null;
for(var i = 0; i < json_options.length; i++)
{
[...]
When i want to access "json_options" at this point, it says that it is null and i dont have any idea why.
Any help is greatly appreciated, thanks in advance!
In your code the code after getOptionsData(); is executed before the call's success callback. so u get json_options as null
Try like this
function getOptionsData(callback)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
json_options = JSON.parse(xmlhttp.responseText);
callback();
}
}
xmlhttp.open("GET", "getData.php", true);
xmlhttp.send();
}
function createOptionsTable()
{
var callback = function()
{
var element = null;
for(var i = 0; i < json_options.length; i++)
{
[...]
}
}
getOptionsData(callback);
}
function getOptionsData()
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
json_options = JSON.parse(xmlhttp.responseText);
for(var i = 0; i < json_options.length; i++)
{
[...]
}
}
}
xmlhttp.open("GET", "getData.php", true);
xmlhttp.send();
}
Your for loop should execute after you could actually get the reponse from ajax and not inside createOptionsTable()...

Categories

Resources