id, string or integer was expected with eval() - javascript

I get a strange error in IE.. but no problems in both FF and chrome
when I alert the variable I get this:
json_post('delete_accounting', 'json.action.php?action=delete_accounting', 'id=682', 'rtn_accounting', {tr_id:'tr_acc682', enc_id:374, delete:1});
but when I want to eval() the sting I get this error (the error is translated from danish, so I don't know how it is put in english?)
id, string or integer was expected
EDIT:
var xmlhttp = {};
function json_post(request_var, response, get_str, callback_function, callback_var)
{
request_var += Math.floor(Math.random()*999).toString();
CNSTR.mouseLoader.cnstr();
if(window.XMLHttpRequest) xmlhttp[request_var] = new XMLHttpRequest();
else if(window.ActiveXObject) xmlhttp[request_var] = new ActiveXObject('Microsoft.XMLHTTP');
xmlhttp[request_var].open('POST', response, true);
xmlhttp[request_var].setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp[request_var].onreadystatechange = function()
{
if(xmlhttp[request_var].readyState == 4)
{
CNSTR.mouseLoader.dstr();
if(callback_function) eval(callback_function+'('+xmlhttp[request_var].responseText+(callback_var ? ', callback_var':'')+')');
}
}
xmlhttp[request_var].send(get_str);
}
I'm quite sure that the error occurs in the eval() because when I run the sting as real code there are no problems..
like this:
json_post('delete_accounting', 'json.action.php?action=delete_accounting', 'id=682', 'rtn_accounting', {tr_id:'tr_acc682', enc_id:374, delete:1});
I have also tried to escape everything in the callback function rtn_accounting(), and still the same error in the same line with the eval()

by adding quotes in the object in the last parameter is works
json_post('delete_accounting', 'json.action.php?action=delete_accounting', 'id=682', 'rtn_accounting', {'tr_id':'tr_acc682', 'enc_id':374, 'delete':1});

Related

Simple AJAX Retrieval of data in XML file, going wrong around ".responseXML"

I've searched and searched and quadruple checked spelling and syntax and I'm stumped. I even checked the syntax on "jslint". I've placed all the code on "jsfiddle":
http://jsfiddle.net/sxtuX/
var xmlHttp= createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.XMLHttpRequest){
xmlHttp = new XMLHttpRequest();
}
else{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function process() {
if (xmlHttp) {
try{
xmlHttp.open("GET", "data_people.xml", true);
xmlHttp.onreadystatechange = handleStateChange;
xmlHttp.send(null);
}
catch (e) {
alert ("In process function.<br/>Error in creating xmlHttp object: "+ e.toString());
}
}
}
function handleStateChange() {
if(xmlHttp.readyState==4) {
if (xmlHttp.status==200) {
try {
handleResponse();
}
catch(e) {
alert ("Trouble getting text." + e.toString());
}
}
else {
alert ("State = "+xmlHttp.readyState+" Status= " + xmlHttp.status);
}
}
}
function handleResponse() {
var xmlResponse = xmlHttp.responseXML,
root = xmlResponse.documentElement,
names = root.getElementsByTagName("name"),
ssns = root.getElementsByTagName("ssn");
alert (xmlHttp.responseText);
var stuff = "";
for(var i=0;i<names.length;i++) {
stuff = names.item(i).firstChild.data + "-" + ssns.item(i).firstChild.data + "<br/>";
}
theD = document.getElementById("theD");
theD.innerHTML = stuff;
}
The javascript works fine up until the last function "handleResponse()" which is the last function. I've placed an "alert" after all the variable declarations using "xmlHttp.responseText" just to prove to myself the file is being accessed and it does print the entire XML file in the alert window.
I tried to create the XML datafile on "jsfiddle" by following the instructions, assuming it was like the HTML file example, but I couldn't get it to work.
So my questions: Why isn't "xmlHttp.responseXML" returning anything? It's either that or something is going wrong with .documentElement. When I examine "names.length" or "ssns.length" they are both zero. Also, can I get some assistance in figuring out the proper way to code an XML file on "jdfiddle" by correcting my fibble attempt?
The way you have your javascript options in the fiddle are set up it only gets executed onLoad (which means all your functions will be defined inside an onload function - and will both not be available in the global scope nor before said function has been executed). It's a catch 22 with sprinkles on top. You'll need to set the second dropdown on the left to either No wrap - in <head> or No wrap - in <body>.
Next up - the jsfiddle example code. There's a whole bunch wrong here:
You should have been referencing Request - not Request.XML (which you just made up ;P). And you should have included the MooTools library (first dropdown on the left) - because that's where Request is from ;)
The url is case sensitive! "/echo/xml/" instead of "/echo/XML/".
The xml string needs to be have properly escaped quotes and javascript strings don't support raw line-breaks (they can be escaped too... but that's another story) - just collapse them for now.
... But you don't need that example. Just use your own code!
Just remember to use the proper test url (with POST not GET) and escape/collapse your test xml.
This is a working fiddle: http://jsfiddle.net/sxtuX/3/

ajax success called before request has finished

at my whits end with this...
The problem I have is that around the same time (roughly 60-70 mins through the request) the success function is called for the ajax request, but the tomcat logs prove that the request is still running.
(perspective: the request is supposed to either return an empty string ("") or a html page (of errors) however when the success function is called, it returns a string of length 2 result = " " (2 white space characters)
I cannot get this to reproduce in chrome, only IE (which is a problem as we cater specificity for IE)
At first I though it was a jQuery issue as I have multiple polls running when the request is sent (to update jQuery progress bar info)
However...
When I test this with just one asynchronous ajax request (not jQuery) that calls a Java method that just loops for 3 hours printing out in the log each second, it always calls success around the 3600 second mark (still another 7200 seconds remaining).
Example code:
var http_request = false;
if (window.XMLHttpRequest) {
http_request = new XMLHttpRequest();
if (http_request.overrideMimeType) {
http_request.overrideMimeType('text/text');
}
}
else if (window.ActiveXObject) {
try {
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!http_request) {
alert('Giving up: Cannot create an XMLHTTP instance');
return false;
}
url += "&random=" + Math.random();
http_request.open('GET', url, true);
http_request.onprogress = function () { };
http_request.ontimeout = function () { };
http_request.onerror = function () { };
http_request.onreadystatechange = function(){
if (http_request.readyState == 4) {
if (http_request.status == 200) {
result = http_request.responseText;
alert("success: ("+result.length+") ["+result+"]");
}
}
};
NOTE: this is not a time-out error (at least not an ajax one) as the ajax time-out options seem to work correctly and return time-out errors accordingly, but as I have said, its not a time-out error...the success function is called too early.
Hope somebody can help :)
Cheers,
Steve.
Update:
I've run the request with the network tab capturing and it shows that the result was aborted: here
Thanks #ArunPJohny, this has given me a new direction to look in. Is there some kind of "onAbort" ajax callback? As I would have thought this kind of response would be caught by the "error:" callback
Update 2:
I have since found my way to a number of SO topics, more notably: xmlhttprequest timeout / abort not working as expected?
Tim provides some useful links for catching the abort, but still no clue as to why its getting aborted.
follow-on: here

AJAX div not updating without alert call with error: b.data is undefined

First of all, any suggestions on rewriting my title?
Issue:
I have an AJAX updatable div, when my error checking alert calls are in, everything works perfect. But when I remove a specific one, the DIV never gets updated. I know it sounds confusing, but code is as follows, and then I will explain further.
AJAX SCRIPT
var xmlhttp
/*#cc_on #*/
/*#if (#_jscript_version >= 5)
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttp=false
}
}
#else
xmlhttp=false
#end #*/
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false
}
}
function myXMLHttpRequest() {
var xmlhttplocal;
try {
xmlhttplocal= new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttplocal= new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttplocal=false;
}
}
if (!xmlhttplocal && typeof XMLHttpRequest!='undefined') {
try {
var xmlhttplocal = new XMLHttpRequest();
} catch (e) {
var xmlhttplocal=false;
alert('couldn\'t create xmlhttp object');
}
}
return(xmlhttplocal);
}
function sndReq(page,key,includesDir,changeDiv,parameterString) {
var divToChange = document.getElementById(changeDiv); // the Div that the data will be put into
// Place loading image in container DIV
divToChange.innerHTML = '<div class="loading">Loading</div>';
if (includesDir == 1){
//Find Current Working Directory. Use to find path to call other files from
var myloc = window.location.href;
var locarray = myloc.split("/");
delete locarray[(locarray.length-1)];
var arraytext = locarray.join("/");
xmlhttp.open("POST","AJAXCaller.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send(parameterString);
} else {
}
xmlhttp.onreadystatechange = handleResponse(changeDiv);
xmlhttp.send(null);
}
function handleResponse(changeDiv) {
/* ======== If I remove the following line script halts ================*/
/* ======== If line stays here, script executes perfectly ==============*/
alert('to changetext 1\n'+xmlhttp.responseText);
/* =========End of line removal issue =================================*/
if(xmlhttp.readyState == 4){
if (xmlhttp.status == 200){
var response = xmlhttp.responseText;
var update = new Array();
if(response.indexOf('|') != -1) {
update = response.split('|');
changeText(update[0], update[1]);
} else {
changeText(changeDiv, response);
}
} //End IF xmlhttp.status == 200
}
}
function changeText( div2show, text ) {
// Detect Browser
var IE = (document.all) ? 1 : 0;
var DOM = 0;
if (parseInt(navigator.appVersion) >=5) {DOM=1};
// Grab the content from the requested "div" and show it in the "container"
if (DOM) {
var viewer = document.getElementById(div2show);
viewer.innerHTML = text;
} else if(IE) {
document.all[div2show].innerHTML = text;
}
}
When I check my Firefox error console, this error ONLY appears when I remove that alert as defined in the code:
Timestamp: 5/30/2012 5:07:55 PM
Error: b.data is undefined
Source File: http://cdn.sstatic.net/js/wmd.js?v=cfd2b283af83
Line: 92
I am an advanced PHP/mySQL developer, but have been trying hard to grasp AJAX/JavaScript. Doing tutorials like mad. So please be descriptive in comments/answers so I can use them as a reference for learning...
Why would displaying an alert box alter code execution (for the better!) in any way?
NEW ERRORS - Google Chrome and Firefox Console (sigh...)
Uncaught Error: INVALID_STATE_ERR: DOM Exception 11
sndReqAJAX.js:89
element.onclick
Line 89 is the following (verified by Google Chrome Console)
xmlhttp.send(null);
Everything I find on the web refers to extremely complex issue regarding DOM objects not existing... This wouldn't apply here, would it?
First, the problem. This is the line:
xmlhttp.onreadystatechange = handleResponse(changeDiv);
The reason this is wrong is that xmlhttp.onreadystatechange should be a function - you need to assign a function to the property, what you are doing is calling the function and assigning the return value to the property. This is not in itself a problem, as long as your function returns a function. Which it doesn't.
If you're used to working with PHP (especially if your used to working with PHP <5.3) you may not be used to this concept. Javascript has support for closures in a way that anyone who doesn't use them much will find confusing.
What the line needs to look like is this:
xmlhttp.onreadystatechange = handleResponse;
By appending (changeDiv) you are calling the function, whereas what you need to do is simply pass it, like you would any other value.
Now, where it gets complicated is that you want to pass an argument that is local to the scope of the calling function. There are a number of ways to handle this, but a cursory look at your code tells me that handleResponse() is not used anywhere else, so it would be better to define this as a closure and not litter the global scope with a named event handler. This also overcomes the variable scoping problem:
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200) {
var response = xmlhttp.responseText;
var update = []; // "new Array()" is baaaad
if (response.indexOf('|') != -1) {
update = response.split('|');
changeText(update[0], update[1]);
} else {
changeText(changeDiv, response);
}
} //End IF xmlhttp.status == 200
}
};
Replace the aforementioned offending line with that block of code, and remove the handleResponse() function definition, and that should solve the immediate problem. Now, as to why the alert() "fixes" your original code - this is a little hard to explain, but I shall have a go... give me a minute to inspect the code properly
Attempt at a full and comprehensible explanation abandoned. If anyone wants one, post a comment and I'll have another go at it when I've had some sleep...

How do I force or add the content length for ajax type POST requests in Firefox?

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

Strange javascript behavior - multiple active XMLHttpRequests at once? Long running scripts?

I'm attempting to issue two concurrent AJAX requests.
The first call (/ajax_test1.php) takes a very long time to execute (5 seconds or so).
The second call (/ajax_test2.php) takes a very short time to execute.
The behavior I'm seeing is that I /ajax_test2.php returns and the handler gets called (updateTwo()) with the contents from /ajax_test2.php.
Then, 5 seconds later, /ajax_test1.php returns and the handler gets called (updateOne()) with the contents from /ajax_test2.php still!!!
Why is this happening?
Code is here: http://208.81.124.11/~consolibyte/tmp/ajax.html
This line:-
req = new XMLHttpRequest();
should be:-
var req = new XMLHttpRequest();
As AnthonyWJones stated, your javascript is declaring the second AJAX object which first overwrites the req variable (which is assumed global since there is no var) and you are also overwriting the ajax variable.
You should separate your code i.e:
function doOnChange()
{
var ajax1 = new AJAX('ajax_test1.php', 'one', updateOne);
var ajax2 = new AJAX('ajax_test2.php', 'two', updateTwo);
}
function AJAX(url, action, handler)
{
if (typeof XMLHttpRequest == "undefined")
{
XMLHttpRequest = function()
{
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
throw new Error( "This browser does not support XMLHttpRequest." )
};
}
url = url + '?action=' + action + '&rand=' + Math.random()
var req = new XMLHttpRequest();
req.onreadystatechange = function() {
if (req.readyState == 4)
{
if (req.status == 200)
{
alert('' + handler.name + '("' + req.responseText + '") ')
handler(req.responseText)
}
}
}
req.open("GET", url, true);
req.send(null);
}
Regards
Gavin
Diodeus and Mike Robinson:
You guys didn't read my post fully. I know that one of the pages takes longer to execute than the other. That is the expected behavior of each page.
HOWEVER if you read my original post, the problem is that the callback for both pages ends up getting called with the HTML contents of the first page only.
AnthonyWJones and Gavin:
Thanks guys! That works like a charm! I guess I need to brush up on my Javascript!

Categories

Resources