404 in JQuery Ajax POST call while sending XML to server - javascript

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>

Related

Ajax character encoding changed after send to server

I have an ajax like this:
$.ajax('../EditUser?userId=' + editingId + '&full_name=' + name + '&position=' + position + '&office=' + office
+ '&office_address=' + office_address + '&age=' + age + '&user_login_name=' + user_login_name + '&email=' + email
+ '&user_type=' + usertype + '&password=' + password + '&meetingIds=' + selectedmeetingid, {
type: 'POST',
success: function (data) {
if (data.indexOf('error://') < 0) {
$('#tbl_meetings').html(data);
} else {
$('#errorMessage').html(data);
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error " + errorThrown);
alert("error " + textStatus);
alert("error " + jqXHR.status);
}
}
);
and my server received data with wrong encoding,example: "Hà Thị Minh Thắng" became "H? Th? Minh Th?ng" after received on server side.I tried adding
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-15",
and
beforeSend: function(jqXHR) {
jqXHR.overrideMimeType('text/html;charset=iso-8859-1');
}
to my ajax but it didn't works. So, anyone know how to fix this?
Try specifying content type to the ajax request & you have to add header to the server side to receive the charset.
$.ajax({
data: parameters,
type: "POST",
url: your-url,
timeout: 20000,
contentType: "application/x-www-form-urlencoded;charset=ISO-8859-1",
dataType: 'json',
success: callback
});
// Server Side... (This is an example in php which I have used in my app)
header('Content-Type: text/html; charset=ISO-8859-1');
Hope this helps you!

Parse cloud code is not logging/alerting on success or failure

I am a newbie in Parse.com cloud code. I am trying to query a table which has a particular column having a request parameter which I am supplying. The query is:
Parse.Cloud.define("newPostNotification", function(request, response) {
Parse.Cloud.useMasterKey();
var userId = request.params.userid;
console.log("User Id "+userId);
var query = new Parse.Query(Parse.ViewCount);
query.equalTo('userId', userId);
query.first({
success: function(object) {
/* var userString = request.params.username;
response.success(userString); */
alert("Success!");
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
});
I am utterly confused as why I cannot see the the alert messages for success or failure! Please rectify me where I am wrong!
You need to pass a JSON string.
For example: console.log({"Log message":"My message!"});
You can use console.log, console.error, or console.warn. Check the guide.
query.first({
success: function(object) {
console.log("Success!");
response.success();
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
response.error("Error " + error.code + " : " + error.message + " ;
}
});

Ajax post not sending data out

var dataString = 'edulevel='+ edulevel
+ '&course=' + course
+ '&financerelated=' + financerelated
+ '&occupation=' + occupation
+ '&joblevel=' + joblevel
+ '&income=' + income
+ '&bankname=' + bankname
+ '&acctype=' + acctype
+ '&accno=' + accno;
//ajax
$.ajax({
type:"POST",
url: "process/veriamateur.php",
data: dataString,
success: success(),
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
I have checked and made sure that dataString was sending out correct stuff, however, the ajax was just not sending out any data, no error whatsoever. Even when I changed the url to an invalid one it still went to my success function.
You should pass data as an object instead of a string when you are sending via POST
Example:
data = {
'edulevel': edulevel,
'course': course
(.....)
};
I have made some changes and now this is working your callback function was success() and jQuery was trying to find the function, either you can write your function at same place or you can write a stand alone function and assign it to sucess:, if you are still getting problem try to change your url, if your current files location is /files/file.php
then your veriamateur.php must be /files/process/veriamateur.php
var dataString = 'edulevel='+ edulevel
+ '&course=' + course
+ '&financerelated=' + financerelated
+ '&occupation=' + occupation
+ '&joblevel=' + joblevel
+ '&income=' + income
+ '&bankname=' + bankname
+ '&acctype=' + acctype
+ '&accno=' + accno;
//ajax
$.ajax({
type:"POST",
url: "process/veriamateur.php",
data: dataString,
success: function(){ alert('success');},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});

Error: $.ajax is not a function

Am getting a error like that, $ajax is not working
<script type="text/javascript">
$(document).ready(function () {
$("#btnsubmit").click(function () {
$.ajax({
type: "POST",
url: "loginform.aspx/getdataval",
data: "{'uname':'" + $("#TextBox1").val() + "','passwod':'" + $("#TextBox2").val() + "'}",
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function (msg) {
alert("welcome");
AjaxSucceeded(msg);
},
error: function (xhr, ajaxOptions, thrownError) {
alert("what is the problem")
}
});
});
});
function AjaxSucceeded(result) {
alert(result.d);
var Emp = result.d;
$("#output").append('<p>' + Emp.Sname + ' ' + Emp.Sno + '</p>');
}
</script>
$ ajax not a function why? When I run this script I get error, it not running, what is the problem?
Thanks
You may have an issue with the single/doule quotes on the data string as the JSON standard says double quotes.
You can also simplify the contentType.
I tend to simplify my use of the .d in asp.net by including a converter and the ajax itself using ajaxSetup like so: (Note that using a converter like this works in jQuery 1.5 forward due to that syntax. Feel free to refactor out the ajaxSetup if you prefer but I find it helps me as I only have to do it once when I have multiple ajax calls.)
$(document).ready(function() {
$.ajaxSetup({
data: "{}",
dataType: "json",
type: "POST",
contentType: "application/json",
converters: {
"json jsond": function(msg) {
return msg.hasOwnProperty('d') ? msg.d : msg;
}
},
error: function(xhr, textStatus, errorThrown) {
var errorMessage = "Ajax error: " + this.url
+ " : " + textStatus + " : " + errorThrown
+ " : " + xhr.statusText + " : " + xhr.status;
alert(errorMessage);
if (xhr.status != "0" || errorThrown != "abort") {
alert(errorMessage);
}
}
});
$("#btnsubmit").click(function() {
var pString = '{"uname":"'
+ $("#TextBox1").val() + '","passwod":"'
+ $("#TextBox2").val() + '"}';
$.ajax({
url: "loginform.aspx/getdataval",
data: pString,
success: function(msg) {
alert("welcome");
AjaxSucceeded(msg);
}
});
});
});
// converter gives us the result instead of the .d here
function AjaxSucceeded(result) {
alert(result);
var Emp = result;
$("#output").append('<p>' + Emp.Sname + ' ' + Emp.Sno + '</p>');
}
EDIT: as of jQuery 1.9, you should bind the ajax setup as such:
$(document).ajaxSetup({..more code

JavaScript error "Function expected" in if statement

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.

Categories

Resources