jQuery AJAX request being treated as application/xml instead of text/xml - javascript

Im making a simple AJAX request for an XML file, but instead of text/xml
it returns it as application/xml, which apperently gives me some issues.
Code:
method.getXmlData = function () {
return jQuery.ajax({
type: "GET",
url: "testxml.xml?id=" + theQuizId,
async: false,
dataType: "xml"
});
};
theQuizData = method.getXmlData();
Anyone had a similar problem?
Note: can't include js-fiddle because of CORS.

I got it working by changing the code to the following:
method.getXmlData = function () {
var outerData;
jQuery.ajax({
type: "GET",
url: "testxml.xml?id=" + theQuizId,
async: false,
cache: false,
dataType: "xml",
success : function(data) {
outerData = data;
}
});
return outerData;
};
theQuizData = method.getXmlData();

On Which Browser you are trying the above code?
Try using dataType : "text/xml" instead of xml . IE handles XML data type differntly (As ActiveXObject other browsers like chrome handle them as Simple XML).
For Example.
$.ajax({
url : "myUrl",
type : 'post',
dataType: ($.browser.msie) ? "text" : "xml",
success: function(data) {
var xml;
if (typeof data == 'string') {
/*This is for IE*/
xml = new ActiveXObject("Microsoft.XMLDOM");
xml.async = false;
xml.loadXML(data);
} else {
xml = data;
}
}
}

Related

How do I need to convert this to plain javascript or jquery?

I'm new to JavaScript and jQuery. I'm currenly having the following code in my javascript file, however it doesn't seem to be working. I'm using this from prototype.js :
var url = '/sip/TnsViewScreenResponse';
var myAjax = new Ajax.Request(url, {
method: "post",
headers:{
'X-Requested-By': 'XMLHttpRequest'
},
parameters: "tin=" + tin,
success: function transResult(response) {
document.getElementById('tinVersionsOf_' + tin).innerHTML
= response.responseText;
document.getElementById('ajax_loading_img').style.display
= 'none';
document.getElementById('tinVersionsOf_' + tin).style.display =
'block';
},
error: function transResult(response) {
document.getElementById('ajax_loading_img').style.display = 'none';
alert('Failure: Problem in fetching the Data');
},
}
);
return false;
This seems to be conflicting with the other jQuery files being used in the file, so I want to convert this to plain JavaScript or jQuery. I have tried the below but it doesn't seem to be working. How can I make this right ?
var url = '/sip/TnsViewScreenResponse';
var myAjax = $.ajax({
type: "POST",
url: url,
data: tin,
success: function transResult(response) {
$('#tinVersionsOf_' + tin).html(response.responseText);
$('ajax_loading_img').css("display","none") ;
$('#tinVersionsOf_' + tin).css("display","block");
},
error: function transResult(response) {
$('#ajax_loading_img').hide();
alert('Failure: Problem in fetching the Data');
},
}
});
The above code is getting skipped while being parsed in the browser, which I had checked with inspect element option in Google chrome.
Try This
$.ajax({
type: "POST",
dataType: "json",
contentType: "application/json",
url: "/sip/TnsViewScreenResponse",
data: JSON.stringify({ mydata: tin }),//where tin is ur data
success: function (result) {
//include your stuff
},
error:function(error)
{
// include your stuff
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

AJAX call gets a “400 bad request”

I am new to jquery, i am getting 400 bad request (i find in browser console).
$("form#upload").submit(function(){
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
var formData = new FormData($(this)[0]);
$.ajax({
url : '/uploadController/upload',
type: 'POST',
data: formData,
async: false,
beforeSend: beforeSendHandler,
success: function (data) {
var msg=data.msg;
var obj=data.obj;
if(data.success == true)
{
$('#successmsg').html(msg);
$('.alert-success').show();
$('.alert-danger').hide();
setTimeout(function() {
$(".alert-success").alert('close');
}, 10000);
}else {
$('#errmsg').html(msg);
$('.alert-danger').show();
$('.alert-success').hide();
setTimeout(function() {
$(".alert-danger").alert('close');
}, 10000);
}
},
cache: false,
contentType: false,
processData: false
});
return false;
});
POST url 400(Bad Request)
Here console showing in error $.ajax({ line on my js file.
But it working on some systems, i don't what is the problem.
Anyone has some ideas?? Thanks a lot.
Since you are using jQuery, you can get serialized you form with this line:
var formData = $(this).serialize()
Use this formData in the ajax and it should work (assuming the relative URL to post is correct)

I am passing an ajax to php with datatype as JSONP,but showing undefined index in php file

On submit button click,
I am passing a variable to sendmail.php.It's showing that contactname is undefined in php.
why is it happening ?
Here is my Code :
var name = document.getElementById('stream_cotactname').value;
alert(name);
$.ajax({
url: "sendmail.php",
async: false,
type:"POST",
data : "cotactname="+name+"file=" + formdata,
dataType: "jsonp",
contentType: false,
processData:false,
jsonp: "jsoncallback",
success: function(html){
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
My Php File:
<?php
$name =$_POST['cotactname'];die("A".$name);
?>
ALL gone well,Thanks.
Now let my introduce my exact code:
<script type="text/javascript">
var formdata = false;
(function () {
var input = document.getElementById("uploaded_file");
formdata = false;
formdata = new FormData();
input.addEventListener("change", function (evt) {
var i = 0, len = this.files.length, img, reader, file;
for ( ; i < len; i++ ) {
file = this.files[i];
if (formdata) {
formdata.append("uploaded_file[]", file);
}
}
}, false);
}());
</script>
HOw can I get the form data information in php (like we do as $_FILES)
If you are not using cross domain call then you can call ajax like this:
$.ajax({
url: "sendmail.php",
async: false,
type:"POST",
data : {cotactname:name},
dataType: "json",
contentType: 'application/x-www-form-urlencoded',
success: function(html){
alert("Thank you. We will be in touch with you");
},
error: function(){
alert("Thank you. We will be in touch with you");
}
});
try to change your data sending for more https://api.jquery.com/jQuery.ajax/
data : {cotactname:name},
also try to check console for any error is post ok on that file or try with correct path of file
You are sending a string from ajax and getting value of variable.
Try this:
CHANGE
data : "cotactname="+name,
TO
data: {"cotactname" : name},

Problen with jquery and ajax parsing JSON. Only working in firefox

I have this jquery code:
var baseURl = 'http://www.testdomain.com';
bindItemImage("230015");
function bindItemImage(_itemCode) {
$.ajax({
url: baseURl + 'v3/api/itemimage/' + _itemCode,
type: 'GET',
contentType: "application/json;charset=utf-8",
success: function (data) {
var item = $.parseJSON(data);
var file = baseURl + item.File;
$('.itemPhoto').attr('src', file);
}
});
}
it displays the image just fine in firefox but not in IE or chrome.
Chrome and IE return the right data but I get a JS error message "Cannot read property 'File' of null"
here is the JS fiddle
http://jsfiddle.net/C8Xjy/3/
Thank you
When you're expecting a json response you set dataType to "json", using contentType: "application/json;charset=utf-8", is for when you're sending json in your request. Also when you specify json as the data type it will already be parsed when passed to the success handler.
$.ajax({
url: baseURl + 'v3/api/itemimage/' + _itemCode,
type: 'GET',
dataType: "json",
success: function (data) {
var file = baseURl + data.File;
$('.itemPhoto').attr('src', file);
}
});
DEMO

Response/callback for JSONP using jQuery $.ajax not working

I am unable to catch response from C# to jQuery using $.ajax. I get an error "SCRIPT ERROR". How can I catch response using JSONP? This is what i am using:
$.ajax({
async: true,
context: mrq,
cache: false,
type: "GET",
url: MYURL,
crossDomain: true,
dataType: 'jsonp',
data: MYDATA,
processData: false,
jsonp: "jsonREQ",
jsonpCallback: "onJSONPsuccess",
success: function (jsonText, textStatus) {}
});
As far as I understand, dataType: 'jsonp' means that as soon as it's returned it's put into the callback function as an argument. So, I'd try this:
onJSONPsuccess = function(response) {
// do something with response, e.g.
results = response["results"]
}
$.ajax({
crossDomain: true,
dataType: 'jsonp',
data: { /*params you're sending in*/ },
jsonp: "jsonREQ",
jsonpCallback: "onJSONPsuccess",
success: onJSONPsuccess
});
You say the server side is C# - are you using WCF? There's a great article here about it:
http://bendewey.wordpress.com/2009/11/24/using-jsonp-with-wcf-and-jquery/
Basically you need to set up WCF (or whatever server-side code you're using) to return the json wrapped in a call to your callback function.
However, with jquery, you can simply add "?Callback=?" to your URL, change the dataType to 'jsonp', and forget about the rest of that stuff. You don't need the jsonp or jsonpCallback options set.
In contrast to a json request, the jsonp request will return your data not wrapped in a 'd' property, so your call back function is:
function(data) { var a = data.myProperty ... }
rather than
function(data) { var a = data.d.myProperty ... }
and the whole method is along the lines of:
var url = configuration.serviceUrl + "/" + method + "?callback=?";
var options = {
type: 'GET',
url: url,
data: args,
dataType: "jsonp",
contentType: "application/json",
success: function(data) {
if (callback != null) callback(data);
}
};
if (typeof errorCallback != 'undefined')
options.error = errorCallback;
$.ajax(options);

Categories