Feeling very proud of myself after creating a form with an AJAX submit, I test it in IE8 and get "Message: 'quantity' is undefined". I've read that it could be something to do with the fact that earlier versions of IE used ActiveX for AJAX requests, but I'm very new to JS and have no real understanding of the problem, let alone the ability to implement a fix.
Here's my code:
var time_variable;
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
var txtname = document.getElementById("txtname");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText; //Update the HTML Form element
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
From your last comment on your question, I suspect you are not defining 'quantity' anywhere and assuming that it will reference the form field. Try this:
if(xmlhttp) {
var txtname = document.getElementById("txtname");
var quantity = document.getElementById("quantity");
var price = document.getElementById("price");
var store = document.getElementById("store");
xmlhttp.open("POST","slots.php",true); //calling testing.php using POST method
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("quantity=" + quantity.value + "&price=" + price.value + "&slot=" + slot.value + "&store=" + store.value); //Posting txtname to PHP File
}
If quantity is a form field you need to get it using getElementById before using it just like you did with txtname:
var quantity = document.getElementById("quantity");
You cant use it directly from the form.
Related
We have a web application that makes use of native XMLHttpRequest() to send data back to our server. One of our larger clients have users that appear to be running IE8 in Win7 (64-bit) and have "Enable native XMLHTTP support" disabled in their browser.
We've implemented the typical scenario of instantiating an ActiveXObject in place of XMLHttpRequest in order to try to support the likes if IE6 (no native XMLHTTP support; yes, we still have clients running this on thin clients!) which I am hoping IE8 can utilise as a fallback if this checkbox option has been switched off. However, once an object has been created, I get a type error when calling open() method on it.
Here's my code:
// Posts back an xml file synchronously and checks for parse error.
// Returns xml object or null. Used in RSUserData.
XML.PostXmlFile = function(sURL, doc)
{
try
{
// Validate Input
if ((typeof (sURL) != "string") || (sURL == ""))
return null;
if (window.XMLHttpRequest) // IE7+, FF and Chrome
{
// Mozilla, create a new DOMParser and parse from string
// Although IE9 and IE10 can successfully load XML using this block, it can't use document.evaluate nor selectNodes/selectSingleNode to navigate it
// Ref: http://msdn.microsoft.com/en-us/library/ie/ms535874(v=vs.85).aspx
// Ref: http://msdn.microsoft.com/en-us/library/ie/ms534370(v=vs.85).aspx
// Ref: http://blogs.msdn.com/b/ie/archive/2012/07/19/xmlhttprequest-responsexml-in-ie10-release-preview.aspx
var req = new XMLHttpRequest();
req.open("post", sURL, false);
req.send(doc);
if (req.status != 200)
throw { message: 'HTTP Post returned status ' + req.status + ' (' + req.statusText + ') when sending to ' + sURL };
// IE11+: req.responseXML returns a native XML Document
// IE9/10: req.responseXML returns an IXMLDOMDocument2 object but we can convert req.responseText to native XML using DOMParser
// IE6/7/8: req.responseXML returns an IXMLDOMDocument2 object but DOMParser is not available
if (window.DOMParser)
{
var parser = new DOMParser();
return parser.parseFromString(req.responseText, 'application/xml');
}
else
return req.responseXML; // NATIVE
}
else
{
// up to IE6:
// Ref: http://blogs.msdn.com/b/xmlteam/archive/2006/10/23/using-the-right-version-of-msxml-in-internet-explorer.aspx
var oXML = XML.GetActiveX_XML();
if (!oXML)
throw { message: "Could not instantiate an Msxml2 ActiveXObject", innerException: e };
oXML.open('POST', sURL, true);
oXML.send(sFile);
if (oXML.parseError.errorCode == 0)
{
xmlDoc = oXML;
return xmlDoc;
}
return null;
}
}
catch (e)
{
var s = "Exception in XML.PostXmlFile(). " + (e.message ? e.message : "");
throw { message: s, innerException: e };
}
}
XML.GetActiveX_XML = function()
{
var progIDs = ['Msxml2.DOMDocument.6.0', 'Msxml2.DOMDocument.3.0'];
for (var i = 0; i < progIDs.length; i++)
{
try
{
var oXML = new ActiveXObject(progIDs[i]);
var sl = oXML.getProperty("SelectionLanguage");
if (sl !== "XPath")
oXML.setProperty("SelectionLanguage", "XPath"); // Changes v3.0 from XSLPattern to XPath
var ns = "xmlns:rs='" + XML._nsResolver('rs') + "' xmlns:xsi='" + XML._nsResolver('xsi') + "'";
// ns = "xmlns:na='http://myserver.com' xmlns:nb='http://yourserver.com'";
oXML.setProperty("SelectionNamespaces", ns);
return oXML;
}
catch (ex) { }
}
return null;
}
NOTES:
The aim is to call to XML.PostXmlFile() with the url and payload.
Modern browsers use new XMLHttpRequest() as expected
IE6 is expected to use XML.GetActiveX_XML() on account that window.XMLHttpRequest returns falsey
IE8 with "Enable native XMLHTTP support" disabled falls through to the IE6 code (because window.XMLHttpRequest returns falsey) but the instantiated object fails because it doesn't support open() method (oXML.open('POST', sURL, true);)
Is there any way I can post my payload back using IE8 when "Enable native XMLHTTP support" is disabled?
You should see if the Microsoft.XMLHTTP is available before checking if there is a XMLHttpRequest:
var bActiveX;
try {
new ActiveXObject('Microsoft.XMLHTTP');
bActiveX = true;
}
catch(e) {
bActiveX = false;
}
And then, check in your if condition:
if (window.XMLHttpRequest || bActiveX) { // IE7+, FF and Chrome
var req = XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject('Microsoft.XMLHTTP');
/* the rest of your code */
}
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);
}
}
I've looked through a few similar threads - but can't see exactly where I am going wrong.
I'm savng the lat & lng of a user on an app I'm creating, using AJAX & PHP. I know the AJAX & PHP works as it saves everything (even dummy lat & lng values) to my database table.
I've been playing with the variables for a couple of hours now, and the best results I have had so far is a '0' value inserted in the database.
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
getCurrentLocation();
}
function onError(message) {
navigator.notification.alert(message, "", "Error");
}
function getCurrentLocation() {
navigator.geolocation.getCurrentPosition(locationSuccess, onError);
}
function locationSuccess(position) {
lat = document.getElementById("latSpan");
lon = document.getElementById("latSpan");
latitude = position.coords.latitude;
longitude = position.coords.longitude;
}
//recording function
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined')
{
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
var getdate = new Date(); //Used to prevent caching during ajax call
if(xmlhttp) {
xmlhttp.open("POST","http://www.lauracrane.co.uk/app/rec/location.php",true); //
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send("latitude=" + latitude + "&longitude=" + longitude);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
else {
alert("Error during AJAX call. Please try again");
}
}}'
I was wondering if someone can see why it's not passing the value of lat & lng to the AJAX function.
Any help would be appreciated. :)
Laura
Maybe we can't see all the code but it looks like latitude and longitude are function scoped to locationSuccess. So when you try to access them in ajaxFunction they will get the default values.
Also, you don't need to do all that getXMLObject fun. On webkit browsers like in Android, iOS and BlackBerry you just need to do:
var xmlhttp = new XMLHttpRequest();
And finally since you are probably running this off of the file:// protocol you will have to look for a status code of 0 which is analogous to 200 in this case.
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200 || xmlhttp.status == 0) {
document.getElementById("message").innerHTML=xmlhttp.responseText;
}
}
// etc.
}
Why not just use a jQuery ajax call? Your code is marked up for IE6... Since this in tagged in phonegap I would assume you have access to using newer methods of doing things.
I would suggest using jQuery ajax..
function ajaxFunction() {
$.ajax({
url:'http://www.lauracrane.co.uk/app/rec/location.php',
type:'POST',
data:'lat='+lat+'&long='+long,
success:function(d){
console.log(d);
},
error(w,t,f){
console.log(w+' '+t+' '+f);
}
});
}
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);
}
I'm trying to POST a http request using ajax, but getting a response from the apache server using modsec_audit that: "POST request must have a Content-Length header." I do not want to disable this in modsec_audit.
This occurs only in firefox, and not IE. Further, I switched to using a POST rather than a GET to keep IE from caching my results.
This is a simplified version of the code I'm using for the request, I'm not using any javascript framework.
function getMyStuff(){
var SearchString = '';
/* build search string */
...
/* now do request */
var xhr = createXMLHttpRequest();
var RequestString = 'someserverscript.cfm' + SearchString;
xhr.open("POST", RequestString, true);
xhr.onreadystatechange = function(){
processResponse(xhr);
}
xhr.send(null);
}
function processResponse(xhr){
var serverResponse = xhr.responseText;
var container = document.getElementById('myResultsContainer');
if (xhr.readyState == 4){
container.innerHTML = serverResponse;
}
}
function createXMLHttpRequest(){
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { return new XMLHttpRequest(); } catch(e) {}
return null;
}
How do I force or add the content length for ajax type POST requests in Firefox?
xhr.setRequestHeader("Content-Length", "0");
would be my best guess.
BTW, if you want to stop caching in IE, just add a random number onto the end, as in:
var RequestString = 'someserverscript.cfm' + SearchString + '&random=' + Math.random();
Try to actually send something instead of null (xhr.send(null);).