JavaScript error "Function expected" in if statement - javascript

When I click the button on the page I am getting a "Function Expected" error message.
The error is on the first if statement.
I have the following code:
Response_Error: function (xhr, textStatus, errorThrown) {
if (textStatus && (textStatus == 'error' || textStatus == 'parsererror')) textStatus = '';
if (errorThrown && errorThrown == 'error') errorThrown = '';
var html = '';
try {
html = (textStatus ? 'textStatus: ' + textStatus + '<br/>' : '') +
(errorThrown ? 'errorThrown: ' + errorThrown + '<br/>' + '<br/>' : '') +
(textStatus || errorThrown ? '' : '<hr/>') + xhr.responseText;
}
catch (err) {
document.write(err.description + '<br/>' + xhr.responseText);
}
if (Page._lastModalDialog) {
try {
if (false) { // HACK: change this to true to put contents on a textarea
html = html.replace('<', '<').replace('>', '>');
html = "<form><textarea rows='40' cols='120'>" + html + "</textarea></form>";
}
$(Page._lastModalDialog).html(html).fadeIn("slow");
}
catch (err) {
document.write(err.description + '<br/>' + html);
}
Page._lastModalDialog = null;
}
else {
document.write(html);
}
},

You can determine the line that have the error from the chrome inspector console or from fire bug and i think it hase something to do with providing a variable while a function is expected.

This is usually the case when a callback function is expected. Check the code and see if there is place where one of the parameters should be a callback function. You could also do a console.log xhr.onreadystatechange, to see if there is a callback assigned to the xhr object.

Related

404 in JQuery Ajax POST call while sending XML to server

I am recently working with adobe InDesign extension's and in that I want to upload an xml file to my server using jquery ajax POST call, so for that, I have to read the XML file from the file system store it into a variable and then pass that variable as body into the post request here is my code
function uploadDocument( onSuccess, onError, onComplete) {
var token = localStorage.getItem("token");
writeLogs("uploadDocument function \n " + token );
var result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
var xmlStr = "";
if(result.err == 0){
writeLogs("file read complete " + ' ' + result.data)
xmlStr = result.data;
alert("type of xmlStr new" + ' ' + typeof(xmlStr));
$.ajax({
url : "https://xyz.abc.com/capi-demo/article?customerNumber=888",
method: "POST",
data: xmlStr,
beforeSend : function(xhr) {
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Content-Type", "application/xml");
},
complete: function(xhr) {
alert("on complete with code" + ' ' + xhr.status + ' ' + xhr.statusText );
//onComplete();
},
success : function(response) {
alert("file upload success with response : " + ' ' +response);
},
error : function(jqXHR, textStatus, errorThrown) {
alert('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
}
});
}
}
and here exact is the XML file I want to send :
<document xmlns="http://pubpress.com/document">
<properties>
<magazineNumber>95100</magazineNumber>
</properties>
<article>
<pam:message xmlns:pam="http://xax.org/namespaces/pam/2.0/" xmlns:ppc="http://axa.com/content" xml:base="/article/content/39992.xml">
<pam:article>
<head xmlns="http://www.w3.org/1999/xhtml">
<dc:identifier xmlns:dc="http://purl.org/dc/elements/1.1/">888-create.xml</dc:identifier>
<pam:status/>
</head>
<body xmlns="http://www.w3.org/1999/xhtml"><p>Sample body text</p></body>
</pam:article>
</pam:message>
</article>
</document>
so whenever I execute this POST call it returns 404 error Not Found but when I send the wrong(undesired to server) XML file then it shows 400 bad request.
the wrong xml (undesired to server) is as follows :
<?xml version="1.0" encoding="UTF-8"?>
<variable type="NameValuePair[]">
<item type="NameValuePair">
<name type="String"><![CDATA[No Data Found]]></name>
<value type="String"><![CDATA[95990070]]></value>
</item>
</variable>
i am not able to find why this POST call is returning 404 from ajax call where the same call with same parameters runs well in PostMan.
thank you in advance..
Any help on this will be highly appreciated.
Aside from making sure the url accepts xml posted, you should add the ajax option for contentType: "text/xml", to your configuration.
Here I get stuff out of the global scope with myApp (not part of question but to me it is better in practice to do so). I refactored to the promise form of .ajax() again because I like it better and I could then replace the functions there with some name spaced error handler for all my ajax for example.(is that what those passed things are, callbacks?)
I also saw a couple of bugs like typeof() in there. This assumes ES6.
// create a namespace object
var myApp = myApp || {
url: "https://xyz.abc.com/capi-demo/article?customerNumber=888"
};
// borrow some code from https://stackoverflow.com/a/23861977/125981
myApp.isXHR = function(maybe) {
if (!maybe) {
return false;
}
if (!('readyState' in maybe)) {
return false;
}
if (!('responseText' in maybe)) {
return false;
}
if (!('status' in maybe)) {
return false;
}
if (!('statusText' in maybe)) {
return false;
}
return true;
};
myApp.writeLogs = function(logmessage) {
// just to act as placeholder for the answer
};
myApp.processMessage = function(message, silent = true) {
if (silent) {
alert(message);
} else { // or
console.log(message);
// or something else like send to server via ajax to log or some such
}
};
myApp.getDocumentContent = function() {
let result = window.cep.fs.readFile("/Users/mac41589/Downloads/test-xmls/post.xml");
//var xmlStr = "";
let getResult = {
xmlStr: "",
hasContent: false,
error: result.err
};
if (result.err == 0) {
myApp.writeLogs("file read complete " + ' ' + result.data)
myApp.processMessage("type of xmlStr new" + ' ' + (typeof result.data));
getResult.xmlStr = result.data;
getResult.hasContent = true;
}
return getResult;
};
myApp.sendContent = function(contentObj) {
let token = localStorage.getItem("token");
myApp.writeLogs("uploadDocument function \n " + token);
myApp.writeLogs("file read complete " + contentObj.xmlStr);
myApp.processMessage("type of xmlStr new " + (typeof contentObj.xmlStr));
$.ajax({
url: myApp.url,
method: "POST",
data: contentObj.xmlStr,
contentType: "text/xml",
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("Authorization", "Bearer " + token);
xhr.setRequestHeader("Content-Type", "application/xml");
}
})
.always(function(dataOrJqXHR, textStatus, jqXHROrErrorThrown) {
// determine which parameter is which when the .always() is called
let my_jqXHR = null;
let data = null;
let errorThrown = null;
if (myApp.isXHR(dataOrJqXHR)) {
my_jqXHR = dataOrJqXHR;
errorThrown = jqXHROrErrorThrown;
}
if (myApp.isXHR(jqXHROrErrorThrown)) {
my_jqXHR = jqXHROrErrorThrown;
data = dataOrJqXHR;
}
let status = my_jqXHR.status;
// do something with status
myApp.processMessage("on complete with code" + ' ' + status + ' ' + errorThrown);
})
.done(function(data, textStatus, jqXHR) {
myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
})
.fail(function(jqXHR, textStatus, errorThrown) {
myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
})
.then(function(data, textStatus, jqXHR) {
myApp.processMessage("file upload success with response : " + ' ' + textStatus + ' ' + data);
}, function(jqXHR, textStatus, errorThrown) {
myApp.processMessage('file upload fail with error -- ' + jqXHR.status + ' textStatus: ' + textStatus + ' errorThrown: ' + errorThrown);
});
};
myApp.uploadDocument = function(onSuccess, onError, onComplete) {
let contentObj = myApp.getDocumentContent();
if (contentObj.hasContent && contentObj.err == 0) {
myApp.sendContent(contentObj);
} else {
myApp.processMessage("No Content" + contentObj.err);
}
};
// call it, not sure what these passed thing are, and seem unused
myApp.uploadDocument(onSuccess, onError, onComplete);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

How to properly try and Catch in jQuery

I have the following function, that get a response from a web service. The response should be displayed on one section of the website.
That's working fine, but the thing is, in case of error, I've trying to get the error message and display it in the same way as the succesful response does, but I can't get that.
$(document).ready(function(){
$('.button').click(function(){
try {
var $resp = $.get("service url here", function(resp){
$('.response').append(resp.response.greeting + ", " + resp.response.Welcome);
});
}
catch (err){
$('.response').append(err.name + ", "+ err.message);
}
});
});
Try using .always()
$(document).ready(function(){
$(".button").click(function() {
$.get("service url here")
.always(function(resp, textStatus, jqxhr) {
$(".response")
.append(textStatus === "success"
? resp.response.greeting + ", " + resp.response.Welcome
: textStatus + ", "+ jqxhr
);
});
});

Check if Jquery .get() JSON Function Worked

If have the following code that brings back a JSON array to be used in a banner delivery system. This works fine although there is some data in the system that populates the JSON array that is causing problems. It's an HTML and Javascript string. Is there any way to check if the below function has executed correctly and if not perform a secondary action?
$.get('/X2DFSS46CZKAJ8277/AGS2443WFA', function( data ) {
if (data != null) {
$('.side-banner').html('<img src="' + data.bannerImgUrl + '">');
if ($('.side-banner-H').length) {
if (data.secondBannerImgUrl !== '') {
$('.side-banner-H').html('<img src="' + data.secondBannerImgUrl + '">');
}
}
}
}, "json" );
From the jquery help page, as of jquery 1.5 you should be able to do this
$.get('/X2DFSS46CZKAJ8277/AGS2443WFA', function(data) {
if (data != null) {
$('.side-banner').html('<img src="' + data.bannerImgUrl + '">');
if ($('.side-banner-H').length) {
if (data.secondBannerImgUrl !== '') {
$('.side-banner-H').html('<img src="' + data.secondBannerImgUrl + '">');
}
}
}
}, "json").fail(function() {
// fail code goes here
});
similar to #dfsq answer, but less rewrite
You can use error callback:
$.get('/X2DFSS46CZKAJ8277/AGS2443WFA', "json").then(function(data) {
if (data != null) {
$('.side-banner').html('<img src="' + data.bannerImgUrl + '">');
if ($('.side-banner-H').length) {
if (data.secondBannerImgUrl !== '') {
$('.side-banner-H').html('<img src="' + data.secondBannerImgUrl + '">');
}
}
}
}, function(xhr, textStatus, errorThrown) {
console.log('Error', errorThrown);
});

How to access result array returned in ajax?

Arg!! I had this working flawlessly and now I am back to banging head against the keyboard.
I want access defined columns inside the array, but I am getting undefined but if I display the results using an alert as detailed in snipped of code below I see the following:
[{"firstname":" Mr","0":" Mr","lastname":" Two","1":" Two","user_public_info_id":"3","2":"3","st_usage_id":null,"3":null},{"firstname":" Mr","0":" Mr","lastname":" Three","1":" Three","user_public_info_id":"5","2":"5","st_usage_id":null,"3":null}]
***
g
***
e
***
undefined
Here is the Ajax code:
$.ajax({
type: "POST",
url: "models/ajaxHandler.php",
data: "handler=getStActivitySharingList&stu_id="+stu_id,
datatype: "json",
success: function(result){
var count = 0;
if (result !== null)
{
//display results
alert(result + " <br />*** <br />" + result[0] +" <br />*** <br />" + result[1] + " <br />*** <br />" + result[0]["firstname"]);
//clears choice list
clearOptions();
//result = $.parseJSON(result); //if this is used cannot display result again
alert (result);
$.each(result, function (i, elem) {
alert("elem"+elem.st_usage_id ); //displays as undefined and won't break
if (elem.st_usage_id === null)
{
count++;
alert(elem.firstname + " "+ elem.lastname + " " + elem.user_public_info_id);
appendOption(elem);
}
});
}
alert(count);
if (count === 0){
noResultsAvailableOption();
}else{
resultsAvailableOption();
}
ShowDialog(false);
e.preventDefault();
},
error: function(){
alert("ajax failure: could not retrieve a list of contacts");
}
});
i not know how you return it from PHP, but in jquery try:
sucess: function (result)
{
console.log(JSON.parse(result)); // parse string to json
}
See json.org
To better answer this question is to implement better debugging procedures.
Here is the code that I used for debugging this issue. The breaking down of the xmlHttpRequest clearly displayed to me that issue was with the data and that I was encountering an illegal character exception when trying to encode the data to json.
A great way to solve any issue is to first implement the correct debugging procedures, and everything else will work itself out.
error: function(xmlHttpRequest, status, error){
alert("ajax failure: could not populate list of countires | " + status + " | error:" + error);
var xmlHttpRequestStr= "";
for(x in xmlHttpRequest)
xmlHttpRequestStr = xmlHttpRequestStr + xmlHttpRequest[x];
alert(xmlHttpRequest);
}

How to encode URL being passed to div.load()?

I am using a URL rewrite and using
$('#somediv').load(query, function (response, status, xhr) {
if (status == "error") {
var msg = "Sorry there was an error: ";
$("#somediv").html(msg + xhr.status + " " + xhr.statusText);
}
});
But the div.laod() wont work when my query has character like '?','&' and '='.
As in when I pass parameters as shown beloew, div rendering wont happen .
query ="http://vmsbawcm001.ed.cps.something.com/content/pms/Snapshot.html?date=2011-09-30&email=something#gmail.com&view=external"
But this works!
query ="http://vmsbawcm001.ed.cps.something.com/content/pms/Snapshot.html"
So How do I pass parameters in some encoded way? or any other solution for this is welcome, coz I am clueless..
After some more research, I have a doubt that it is only the # symbol which is creating the problem. Is it so? If yes, what is the possible solution fro that?
Thanks,
Adarsh
The second parameter in .load() is for passing query data. Here's the reference: http://api.jquery.com/load/.
Demo: http://jsfiddle.net/ThinkingStiff/EKHbQ/
HTML:
<div id="somediv"></div>
Script:
var uri = 'http://vmsbawcm001.ed.cps.something.com/content/pms/Snapshot.html',
data = {date:"2011-09-30",email:"something#gmail.com",view:"external"};
$( '#somediv' ).load( uri, data, function ( response, status, xhr ) {
if ( status == 'error' ) {
var msg = 'Sorry there was an error: ';
$( '#somediv' ).html( msg + xhr.status + ' ' + xhr.statusText );
};
});

Categories

Resources