Why can't separate the function for xmlHttp.onreadystatechange? - javascript

The below js file test.js` works fine in my html.
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
Now i want to separate them
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
in a single function.
I rewrite the test1.js as test2.js.
var xmlHttp;
function ready(){
if (xmlHttp.readyState == 4 && xmlHttp.status == 200){
alert(xmlHttp.responseText);
}
}
function sendData()
{
var formData = new FormData( document.querySelector("form") );
var xmlHttp = new XMLHttpRequest();
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = ready;
}
ob = document.getElementById("submit");
ob.addEventListener("click",sendData);
The test2.js encounter error info:
test2.js:4 Uncaught TypeError: Cannot read property 'readyState' of undefined
at XMLHttpRequest.ready (test2.js:4)
Another issue :what is the right order for the following statements?
I have seen some material write them as below :
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
xmlHttp.onreadystatechange = function(){ }
Other material also seen:
xmlHttp.onreadystatechange = function(){ }
xmlHttp.open("post", "test.php",true);
xmlHttp.send(formData);
And other order in webpage xmlHttp statements order
xmlhttp.open("POST", "Demo", true);
xmlhttp.onreadystatechange=myCallBack;
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
xmlhttp.send("FirstName=Nat&LastName=Dunn");

In sendData you have:
var xmlHttp = new XMLHttpRequest();
Your only mistake is including the var here - just do this instead:
xmlHttp = new XMLHttpRequest();
The reason this matters is that the var is declaring a new local variable of the same name, which is then getting assigned to - so ready doesn't get access to it. It accesses the global xmlHttp variable, which is never assigned to. By removing the var as shown above, you ensure that the global variable is assigned to - and this should work. (Although of course it's not best practice to use globals.)

Related

How to link JSON file so that it can be parsed and used to create an arraylist

I would like my program to import an JSON file, using the data to create an array-list then access the array-list so that I can display it on the web page.
I've tried using JSON.parse() but it only works when I do something like JSON.parse('[{"shape":"polygon"},{"shape":"square"}]); It doesn't work for parsing a JSON file that is not declared inside. My JSON file is saved to my desktop. I'm new to JavaScript and importing files so anything would be helpful!
I've tried using:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObject = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", "PATIENT51.txt", true);
xmlhttp.send();
I keep getting errors with: JSON.parse(this.responseText);
JSON.parse Error: Invalid character at position:5 problemlist1.html(3,5)
You can just have the log in xmlhttp scope and it'll work.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
console.log(JSON.parse(this.responseText))
}
};
xmlhttp.open("GET", "PATIENT51.txt", true);
xmlhttp.send();
EDIT: seen your edit, in addition, make sure that your JSON has the right format:
{
"key1" : 1,
"key2" : 2,
"key3" : 3
}

Get JSON from local JavaScript

good afternoon. I'm developing an app that can get a JSON from local (manifest.json). I want to get this file from JavaScript and then read it. But I have a problem, I cant call this file. How can I?
var urlJSON = new XMLHttpRequest("manifes.json").toString;
var dataJSON = JSON.parse(urlJSON);
alert(dataJSON.name);
var xmlhttp = new XMLHttpRequest();
var url = 'manifest.json';
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(JSON.parse(xmlhttp.responseText));
}
if (xmlhttp.status == 404) {}
};
xmlhttp.open('GET', url, true);
xmlhttp.send();
Or run chrome with arguments --allow-file-access-from-files
Or download and create server for your app

Passing value from JavaScript to PHP using AJAX

I'm trying to pass value to PHP code using AJAX.
Javascript
function countop() {
var href = window.location.href;
var href2 = href.split('/', 7);
xmlhttp.open('GET', '/count.php?val_for_count='+href2[6], true);
xmlhttp.send();
};
PHP
$x = $_GET['val_for_count'];
echo $x;
I don't get $x printed and I don't know why.
You have two problems.
First, xmlhttp is never declared, so your code throws a reference error.
var xmlhttp = new XMLHttpRequest();
Second, you never look at the HTTP response!
xmlhttp.addEventListener("load", function (event) {
document.body.appendChild(
document.createTextNode(
this.responseText
)
);
});
You have to create a new instance of XMLHttpRequest before using it:
var xmlhttp = new XMLHttpRequest();
And if you want to print the result of your request in your document, you can do it like this:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.body.innerHTML = xmlhttp.responseText;
}
};

How can I access to the serverside php from javascript?

I set some variables in serverside through PHP
$LGD_AMOUNT = ""; //Amount is for the price that customer purchases
$LGD_BUYER = "";//Buyer collect name of the customer
And I store these in $payReqMap
$payReqMap['LGD_AMOUNT'] = $LGD_AMOUNT;
$payReqMap['LGD_BUYER'] = $LGD_BUYER;
what I want to do is before I send these to the server side, in <script> part, I want to give them values. Is there any method that I can call these stored variables in <script> part?
This is a start point to use Ajax using pure Javascript;
function getxmlhttp (){
//Create a boolean variable to check for a valid Microsoft active x instance.
var xmlhttp = false;
//Check if we are using internet explorer.
try {
//If the javascript version is greater than 5.
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
//If not, then use the older active x object.
try {
//If we are using internet explorer.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (E) {
//Else we must be using a non-internet explorer browser.
xmlhttp = false;
}
}
// If not using IE, create a
// JavaScript instance of the object.
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}//Function getxmlhttp()
//Function to process an XMLHttpRequest.
function processajax (serverPage, obj, getOrPost, str){
//Get an XMLHttpRequest object for use.
xmlhttp = getxmlhttp ();
if (getOrPost == "get"){
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(null);
}
else {
xmlhttp.open("POST", serverPage, true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
obj.innerHTML = xmlhttp.responseText;
}
}
xmlhttp.send(str);
}
}

How to pass a JSON object using form data to a rest service using JS

I have a rest webservice which can accept a string. I want to pass a json object as a string to this service. I have to use a HTML page with some textfields and has to pass the form data to the service. can any one help??
Thankyou
you can try this
function callWebService{
var field= document.getElementById('field').value;
//use jquery to convert to json object
//see comment for more info on this
var ws = 'http://localhost:8080/WebServicePath/';
var url = ws + field;
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("Success");
}
else {
alert("Failure");
}
};
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
}

Categories

Resources