How can I access to the serverside php from javascript? - 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);
}
}

Related

NodeJS XMLHttpRequest response

I'm making and app and I need do get the number of verses of a chapter of the bible.
I'm getting the info from http://www.kingjamesbibleonline.org/
In order to do that I am making an XMLHttpRequest to send to the server from the function getVerses() from the site.
The problem that I am facing is that I'm not getting a .responseText from the XMLHttpRequest. When I use firebug and call that function, in the Network tab > Response tab I get nothing but on Network tab > Preview I get the answer.
Where is this answer coming from and what is the variable that has this value?
My node code is as follows:
let XMLHttpRequest2 = require("xmlhttprequest").XMLHttpRequest;
function getVerses() {
let xmlhttp = new XMLHttpRequest2(); //: new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == xmlhttp.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
}
else if(xmlhttp.status == 400) { }
else { }
}
}
xmlhttp.open("POST", "http://www.kingjamesbibleonline.org/ajax.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send('callFunc=getMaxVerseForChapter&book='+'"Genesis"'+'&chapter='+'"2"');
}
getVerses();
Apparently the server is very strict and it expects the header to be called Content-Type and not Content-type. Some kind of poorly written stuff obviously (in PHP). Also get rid of the double quotes around the values you are sending.
Here you go:
let XMLHttpRequest2 = require("xmlhttprequest").XMLHttpRequest;
function getVerses() {
let xmlhttp = new XMLHttpRequest2(); //: new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == xmlhttp.DONE ) {
if(xmlhttp.status == 200){
console.log(xmlhttp.responseText);
}
else if(xmlhttp.status == 400) { }
else { }
}
}
xmlhttp.open("POST", "http://www.kingjamesbibleonline.org/ajax.php", true);
xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
xmlhttp.send('callFunc=getMaxVerseForChapter&book=' + 'Genesis' + '&chapter=' + '2');
}
getVerses();
and since you are hardcoding the values, you don't really need string concatenation:
xmlhttp.send('callFunc=getMaxVerseForChapter&book=Genesis&chapter=2);

2 different ajax functions called one after another return the same value

I have a bizarre behavior of 2 different ajax functions called one after another.
Each of them fetch different value and populate different text boxes but the problem is they return the value of the first function called.
here is the code:
if (id == "Other") {
document.getElementById("Value").style.display = "block";
document.myForm.Price.value = "";
document.myForm.Code.value = "";
} else {
document.getElementById("Value").style.display = "none";
document.myForm.TypeValue.value = id;
getCOde(id);
getPrice(id);
}
here is getPrice function:
function getPrice(value) {
if (window.XMLHttpRequest) { //safari, chrome, opera, ffox
xmlhttp = new XMLHttpRequest();
} else { //IE
ActiveXObject("Microft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.AddingForm.itemPrice.value = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../scripts/getPrice.php?ID=" + value, true);
xmlhttp.send();
}
here is the getCode fucntion
function getCode(value) {
if (window.XMLHttpRequest) { //safari, chrome, opera, ffox
xmlhttp = new XMLHttpRequest();
} else { //IE
ActiveXObject("Microft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.AddingForm.itemCode.value = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "../scripts/getyCode.php?ID=" + value, true);
xmlhttp.send();
}
both functions work well if only one of them is called. and beside if I interchange their order, than the value which is returned is the one of the first function called.
I wonder how to make one function to wait till another is executed. because i guess the order is the problem
You should declare xmlhttp inside each function instead of having it as a global variable.
function getPrice(value){
var xmlhttp;
if(window.XMLHttpRequest){//safari, chrome, opera, ffox
xmlhttp=new XMLHttpRequest();
}
else{//IE
xmlhttp = ActiveXObject("Microft.XMLHTTP");
}
you are overriding the reference to one object with another so the object in the event handler refered to by the identifier xmlhttp is the same in both cases

Javascript only execute the last function called

I want my page to execute the same function 3 times, calling for 3 different things each time.
The code is currently
<script>
ajaxGet('/goget.php?name='+edit.dep.value, 'dep_result');
ajaxGet('/goget.php?name='+edit.arr.value, 'arr_result');
ajaxGet('/goget.php?type='+edit.reg.value, 'reg_result');
</script>
But it only executes the last call. Why?
Javascript:
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new ActiveXObject("Microsoft.XMLHTTP");
}
function ajaxGet(ajaxLoadData, changeToID) {
if(XMLHttpRequestObject) {
var obj = document.getElementById(changeToID);
XMLHttpRequestObject.open("GET", ajaxLoadData);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
You'll want to have each call to ajaxGet create its own XMLHttpRequest.
An XMLHttpRequest can only handle 1 request at a time. And, since they'll be making the request asynchronously, they'll be processing in parallel rather than sequentially.
function ajaxGet(ajaxLoadData, changeToID) {
var obj = document.getElementById(changeToID);
var xhr = new XMLHttpRequest();
xhr.open("GET", ajaxLoadData);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && xhr.status == 200) {
obj.innerHTML = xhr.responseText;
}
};
xhr.send(null);
}
Granted, browsers generally limit requests to only a few at a time (usually 2), queuing any additional. But your code shouldn't count on that.
Side note: Unless you need to support IE6 or older, you shouldn't need to fallback to ActiveXObject.
You need to change your ajaxGet() method to instantiate a new XMLHttpRequest object at every call. Since, you're using the same XMLHttpRequest every new request is overwriting the previous one.
Hence, you're getting the results returned by the last method call only.
function getXHRObj() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function ajaxGet(ajaxLoadData, changeToID) {
var XMLHttpRequestObject = getXHRObj();
var obj = document.getElementById(changeToID);
XMLHttpRequestObject.open("GET", ajaxLoadData);
XMLHttpRequestObject.onreadystatechange = function() {
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}

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);
}

How to make update function check if it has loaded same context as there already is?

So I have next update function:
function update() {
var xmlhttp;
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
var success = false;
var objects = ["MSXML2.XMLHTTP.5.0", "MSXML2.XMLHTTP.4.0", "MSXML2.XMLHTTP.3.0", "MSXML2.XMLHTTP", "Microsoft.XMLHTTP"];
for (var i = 0; i < objects.length && !success; i++) {
try {
xmlhttp = new ActiveXObject(objects[i]);
success = true;
} catch (e) { };
}
if (!success) throw new Error("AJAX is unavailabe");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
document.getElementById('usersList').innerHTML = xmlhttp.responseText;
};
}
xmlhttp.open("get", "buttons.html", true);
xmlhttp.send(null);
}
update();
setInterval(update, 5000);
so what I want it not to update documents contents if it has loaded same stuff that there is already. How to do such thing?
Something like:
if (xmlhttp.readyState == 4 &&
document.getElementById('usersList').innerHTML != xmlhttp.responseText) {
document.getElementById('usersList').innerHTML = xmlhttp.responseText;
};
EDIT: After patrick's comment in the page, it looks better to store the response somewhere and compare it to the new instead of relying on the innerHTML that can change the original HTML string.
You'll need to do the download first to determine what text you're comparing in the first place. I'm assuming buttons.html is somehow dynamic, so when you download it, you need to compare it to what's already in the innerHTML of userList.
...
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if(document.getElementById('usersList').innerHTML != xmlhttp.responseText)
document.getElementById('usersList').innerHTML = xmlhttp.responseText;
};
}
...
In addition, if you're going to do a lot of ajax, I suggest using a library such as jQuery. Ajax calls are as simple as
$('#userList').load('buttons.html');
or
$.ajax({
url: 'buttons.html',
success: function(data) {
if ($('#userList').html() != data)
$('#userList').html(data);
}
});

Categories

Resources