I have a javascript function which get's me the emailID of the respective text added.
But what happens if the EmailID doesn't exist's it gives me error as
Microsoft JScript runtime error: Object doesn't support this property or method
Here is the function.
function getEmailIdByType() {
StrPriFnName = "FunGetEmailIdByType(" + document.getElementById('TxtPartyName').value + ")";
var ObjPriXMLHTTP = new ActiveXObject("Microsoft.XMLHTTP")
ObjPriXMLHTTP.open("GET", "FrmInwardXMLHTTP.aspx?para=" + StrPriFnName, false);
ObjPriXMLHTTP.send("");
if (Trim(ObjPriXMLHTTP.responseText) != "") {
var StrPriData = ObjPriXMLHTTP.responseText.Split('~');
document.getElementById('TxtEmail').value = StrPriData[1];
}
else {
return false;
}
}
It gives me error at line:-
var StrPriData = ObjPriXMLHTTP.responseText.Split('~');
if (Trim(ObjPriXMLHTTP.responseText) != "") {
var StrPriData = ObjPriXMLHTTP.responseText.Split('~');
document.getElementById('TxtEmail').value = typeof StrPriData[1] != "undefined" ? StrPriData[1] : "";
}
else {
return false;
}
You should try to access the responseText only when the ObjPriXMLHTTP changes it's readyState
ObjPriXMLHTTP.onreadystatechange = function() {
if (ObjPriXMLHTTP.readyState == 4 && ObjPriXMLHTTP.status == 200) {
var StrPriData = ObjPriXMLHTTP.responseText.split('~');
}
Probably the responseText property is only available after it got a response. The response hasn't really arrived where you try to see it.
Here is a full example.
Related
I want Ajax to get information while the information is valid. So if I do
$(document).ready(function () {
var url = '/my/url/';
var ses = true;
var i = 0;
while (ses) {
i++;
var temp;
$.get(url + "?get=" + i, function (data) {
if (data != '') {
temp = data;
sortArticles(data);
}
});
if(temp == '') ses = false;
}
});
If I do this without while (putting 0 instead of get var), I get the information I need, but if I put it like this, I enter an infinite loop and the page breaks. By the way, I tested and the if(data != '') statement works as intended.
I don't know why temp doesn't change the state of the ses variable. I tried putting an else statement inside $.get(..)
else ses = false;
but it doesn't do the trick neither.
Thanks for reading!
jQuery ajax (as most ajax implementations), which $.get() is a shorthand for, is asynchronouos be default. The callback function is only executed once the request is complete. The while continues indefinitely since without yielding control out to the JS engine the callback doesn't get a chance to do it's work - even if the request(s) are done.
In order to continuously send requests, try like this:
function requestMore(i) {
$.get('/my/url/?get=' + i, function (data) {
if (data != '') {
sortArticles(data);
requestMore(i + 1);
}
});
}
(document).ready(function () {
requestMore(1);
});
The way you wrote your code temp will never be ''.
The problem is temp is not a string. It's undefined.
Instead of:
if(temp == '') ses = false;
write:
if(typeof(temp) == 'undefined') ses = false;
$(document).ready(function () {
var url = '/my/url/';
var ses = true;
var i = 0;
while (ses) {
i++;
var temp='';
$.get(url + "?get=" + i, function (data) {
if (data != '') {
temp = data;
sortArticles(data);
}
});
if(temp == '') ses = false;
}
});
This will work.Initialize temp as a blank string as shown :)
LogCat is showing that cordova.js line 415 (function checkArgs shown below) is throwing an Uncaught TypeError causing my app to break.
The log shows Uncaught TypeError: Wrong type for parameter "successCallback" of Device.getInfo: Expected Function, but got Undefined.
The error only occurs when making an AJAX call... my AJAX call is below
function checkArgs(spec, functionName, args, opt_callee) {
if (!moduleExports.enableChecks) {
return;
}
var errMsg = null;
var typeName;
for (var i = 0; i < spec.length; ++i) {
var c = spec.charAt(i),
cUpper = c.toUpperCase(),
arg = args[i];
// Asterix means allow anything.
if (c == '*') {
continue;
}
typeName = utils.typeName(arg);
if ((arg === null || arg === undefined) && c == cUpper) {
continue;
}
if (typeName != typeMap[cUpper]) {
errMsg = 'Expected ' + typeMap[cUpper];
break;
}
}
if (errMsg) {
errMsg += ', but got ' + typeName + '.';
errMsg = 'Wrong type for parameter "' + extractParamName(opt_callee || args.callee, i) + '" of ' + functionName + ': ' + errMsg;
// Don't log when running unit tests.
if (typeof jasmine == 'undefined') {
console.error(errMsg);
}
throw TypeError(errMsg);
}
}
My AJAX call:
var ajax = $.ajax({
type: "POST",
url: "http://www.example.com/tools/api/index.php",
data: api,
dataType:"json",
async:async
});
ajax.done(function( response ) {
// do this
});
ajax.fail(function( jqXHR, textStatus, errorThrown ) {
// do that
});
NOTE: I'm using build.phonegap.com and using version 3.3.0
Any thoughts or suggestions would be greatly appreciated.
UPDATE: going through the all the source code which uses the function checkArgs I have found this. This is the only other function that uses checkArgs
/**
* Get device info
*
* #param {Function} successCallback The function to call when the heading data is available
* #param {Function} errorCallback The function to call when there is an error getting the heading data. (OPTIONAL)
*/
Device.prototype.getInfo = function(successCallback, errorCallback) {
argscheck.checkArgs('fF', 'Device.getInfo', arguments);
exec(successCallback, errorCallback, "Device", "getDeviceInfo", []);
};
Why it's throwing error... I'm not sure
Turns out the problem was with pulling the window.device data.
I tried logging all the device at once api.device = window.device ... turns out device is a cordova function not an object with static values attached to it.
I had to change my code to
api.device = {};
api.device.name = device.name;
api.device.phonegap = device.phonegap;
api.device.platform = device.platform;
api.device.uuid = device.uuid;
api.device.version = device.version;
where before I just had
api.device = device;
Hope this can help someone else in the future.
I have a issue in getting response in Kony application. this is the code
function getServerResponceOption(url){
alert(url);
var httpclient2 = new kony.net.HttpRequest();
var requestMethod = constants.HTTP_METHOD_GET;
var async = true;
httpclient2.open(requestMethod, url,async);
if(getAccessToken() != null && getAccessToken() != ""){
httpclient2.setRequestHeader("AuthToken",getAccessToken());
}
httpclient2.send();
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
}
function HandleResponce(obj)
{
alert("Getting data "+obj.readyState+" Status "+obj.status+" Response "+obj.response );
if(obj.readyState == 4 )
{
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(0,jsonObj);
return;
}
else
{
}
}else{
var state = obj.status;
alert("Readystate "+obj.readyState+" Status = "+state);
}
if (obj.response != null && obj.response != "")
{
var jsonObj = obj.response;
handleResponseOption(1,jsonObj);
}
}
Here i got server response if i put the alert message in HandleResponce(obj) without the alert i didn't get any response. the ready state is 1 and status is 0. What is the problem occurred if i remove the alert message?
Note: URL and getAccessToken() is getting values.
You are calling function in line, When you use HandleResponce(httpclient2) function is immediately executed.
httpclient2.onReadyStateChange = HandleResponce(httpclient2);
Change your code as
httpclient2.onReadyStateChange = function(){ HandleResponce(httpclient2) };
$(function () {
//To send data from input text
$('#add').click(function () {
var name = $('#name').val();
var gender = $('#gender').val();
var age = $('#age').val();
var address = $('#address').val();
var illness = $('#illness').val();
var selectunit = $('#selectunit').val();
if (typeof name !== null) {
my codes here...
} else {
alert('Some fields are missing!');
}
return false;
});
});
i want to trap my variables (name,age,address,illness) not to be null before doing the codes
please help thanks
use
name != null || name != ""
instead of
typeof name !== null
if your case is to check if name is undefined then use
typeof name !== "undefined"
You can check for null like so:
if (somevariable == null) { /* code */ }
The check for undefined is a little different:
if (typeof somevariable === "undefined") { /* code */ }
I'm writing an Http Request without the use of a library (another script was having conflits...)
But Im having trouble with the scope of my object. Below is the calling script, then the Ajax_Request object follows.
function loadCard(e) {
var element = e.target;
if($('overlay')) {
return false; //something is already over the layout
}
var card = '/card/'+element.id;
var option = {method:'post', parameters:'test', async:true}
loadOverlay();
var ajax = new Ajax_Request(card, option);
}
//Ajax_Request
function Ajax_Request(url, options) {
if(typeof url !== 'undefined') {
this.url = url;
}
if(typeof options.method !== 'undefined') {
this.method = options.method;
} else {
this.method = 'get';
}
if(typeof options.parameters !== 'undefined') {
this.parameters = options.parameters;
}
if(typeof options.async !== 'undefined') {
this.async = true;
} else {
this.async = false;
}
if(window.XMLHttpRequest) {
this.request = new XMLHttpRequest();
} //check for MS browser
this.makeRequest = function() {
try {
this.request.onreadystatechange = this.checkReadyState;
this.request.open(this.method, this.url, this.async);
if(this.method == 'post') {
this.request.send(this.parameters);
} else {
this.request.send(null);
}
} catch(err) {
alert(err);
}
}
this.setResponse = function(r) {
alert(r)
this.response = r;
}
this.getResponse = function() {
return this.responseText;
}
this.checkReadyState = function(r) {
switch(this.readyState) {
case 4:
//Represents a "loaded" state in which the response has been completely received.
if(this.status == 200) {
this.setResponse(this.responseText)
}
...
}
}
}
I'm trying to set the response to a property so my calling object can work with it.
But when I try to call this.setResponse(), I get an error that it's undefined.
How can I tie the onreadystatechange callback to my program properly?
The script otherwise returns the data properly, and I could simply output it right there, but I need a bit more flexibility.
Thanks
Rich
This is happening to you because inside the checkReadyState function this actually represents the XMLHttPRequest instance not you Ajax_Request object, thus this.setResponse is undefined. In order to reference your object´s method you have to use a little trick: var that = this.
function Ajax_Request(url, options) {
var that = this;
...
this.checkReadyState = function (r) {
switch(this.readyState) {
case 4:
if(this.status == 200) {
// "this" refers to the XMLHttpRequest,
// but "that" refers your custom Ajax object
that.setResponse(this.responseText)
}
...
}
}
}
I'm not sure whether this is the problem, but you shouldn't be referring to Ajax_Request within the constructor. Use this instead. (this refers to the actual object instance—Ajax_Request refers to the object constructor.)
this.makeRequest = function() {
try {
this.request.onreadystatechange = this.checkReadyState;
this.request.open(this.method, this.url, this.async);
if(this.method == 'post') {
this.request.send(this.parameters);
} else {
this.request.send(null);
}
} catch(err) {
alert(err);
}
};
In this.checkReadyState, try changing this.setResponse(this.responseText) to this.setResponse(this.request.responseText);.