Ajax request seems to fail in IE 8 - javascript

The following jQuery code returns an xml file from the Met Office datapoint and should alert the user with an attribute in the xml data:-
$.ajax({
url: "http://datapoint.metoffice.gov.uk/public/data/val/wxfcs/all/xml/324246?res=daily&key=myapikey",
dataType: "xml",
method: "GET",
success: function (text) {
myValue = $(text).find("Period Rep").first().attr("W");
alert(myValue);
},
error: function () {
alert("Not working");
}
})
This works fine in Chrome and does what I expect, but in IE8 the error function is called. Any ideas what I'm doing wrong or why IE doesn't want to work?
(Note: I know IE8 is far from ideal but I have to support it for this application unfortunately. There's no way around this at present)

Try
jQuery.support.cors = true;
Before request and
crossDomain: true
as ajax option

Related

ajax post working on chrome but not working on firefox and safari

I've encountered an issue where a jquery ajax post method works on chrome but does not work on safari or firefox. I've looked through all the other similar posts and they don't solve the problem. Whenever I run the ajax code, it just returns the entire HTML of the page the form is found on.
Here's my javascript:
$("#piece-form").submit(function(e)
{
e.preventDefault();
// gets which submit button was clicked
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
var formData = new FormData(this);
$.ajax
(
{
type: "POST",
url: url,
data: formData,
cache: false,
processData: false,
success: function(data)
{
if(data == "Success!")
{
$("#error-box").css("display", "none");
$("#success-box").html("Success! Publishing...");
$("#success-box").css("display", "block");
}
else
{
$("#success-box").css("display", "none");
$("#error-box").html(data);
$("#error-box").css("display", "block");
}
}
}
)
});
No matter the content of the PHP file the function points to, it doesn't work as planned. I've tried making a PHP file with a single echo line and I still run into the same problem. I've implemented an error block in the ajax as well and it returns nothing. I also don't receive an error in the console other than: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/" in Firefox
Edit: I've added contentType:false and it still isn't functioning properly on Firefox and Safari
Have you tried wrap your code in document ready?
Also as much as i know now it is correct to use on():
$( document ).ready(function() {
$("#piece-form").on('submit', function(e){
//your main code here
});
});
For now it does not looks like there would be any issue. ..
I finally found the answer.
The error is in the following line of code:
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
For some reason, Firefox and Safari don't properly get the value of "selectedButton" (although Chrome does) resulting in the url variable being incorrectly set. In order to circumvent this, I did the following:
$(".piece-button").click(function (){
url = $(this).attr("name");
})
I needed the submittedButton method because I had two submit buttons for the form and was trying to find which one was clicked. This alternate method does that and is transferrable across all three browsers I have tested. This may not be an optimal solution to the two button submit issue but it worked for me and now the ajax works without a hitch.
Though you have got the solution but from interest I am sharing mine as I have just encountered same problem and got the workaround by adding event.preventDefault(); after success. Example code is given
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data: {
name: $('#nameInput').val(),
email: $('#emailInput').val()
},
type: 'POST',
url: '/post_for_db',
success: function(data) {
console.log(data)
$("body").html(data);
// This will navigate to your preferred location
document.location = '/render_table_from_db';
},
event.preventDefault(); // solution is this for me
});
});

jQuery ajax works in Chrome, but not in Firefox or Safari

I implemented ajax request with jQuery. This is the code:
//initialize value, nameValue, emailValue
$.ajax({
url: "getPOST.php",
type: 'POST',
data: {
'id': value,
'name': nameValue,
'email': emailValue
},
success: function(response) {
console.log(response);
}
});
The code works fine in chrome, but it fails in Safari and in Firefox. I've seen some answers to this question, but they are 6 or more years old. What could be the fix for this problem?
EDIT: By fail I mean that on php side, nothing gets stored in database when run on Firefox or Safari, but it works as expected in Chrome. There is no error messages in console. The request in Safari is shown in red, and it didn't sent any data.
I inspected the post data in Firefox and they are as they should be. No errors there. Although the request is painted in red. This is how it looks. An error on the jQuery side?
I am using this code to send data to my server, before directing user to the PayPal payment page.
jQuery code. Hope I didn't delete to many braces.
// JavaScript Document
jQuery(document).ready(function($){
//you can now use $ as your jQuery object.
//real stuff here
$(".submit-link").click(function(e){
var value=$.trim($(".url-submit").val());
if(value.length>0){
value = encodeURIComponent(value);
var nameValue=$.trim($(".name-submit").val());
var emailValue=$.trim($(".email-submit").val());
if(nameValue.length>0){nameValue = encodeURIComponent(nameValue);}
if(emailValue.length>0){emailValue = encodeURIComponent(emailValue);}
$.ajax({
url: "getPOST.php",
type: 'POST',
data: {"id":value,"name":nameValue, "email":emailValue},
success: function(response) {
console.log(response);
}
//go to link in href now
});
}else{
var $urlSubmit = $('.url-submit');
$urlSubmit.addClass('invalid');
setTimeout(function(){
$urlSubmit.removeClass('invalid');
},500);
e.preventDefault();
}
});
//some other stuff
});
Got to long for a comment but try excluding jquery and try simple xhr/fetch to see if it works (maybe you will get a other understandable error if you try fetch)
fetch('getPOST.php', {
method: 'POST',
headers: {'content-type': 'application/x-www-form-urlencoded; charset=UTF-8'}
body: 'id=0&name=bob&email=bob%40localhost'
}).then(res => console.log(res))
(safari don't have fetch so try in firefox)
The only thing i can thing of is that you are posting cross origins... Are you posting to the same domain? Must be a network error/restriction cuz your code is valid

Why doesn't this function load after a successful ajax call in jquery? (updated)

I'm using the tutorial here, that used to work last month, but now it isn't. I've copied the relevant code below.
<script>
(function($) { //In case jQuery no conflict is being used
$(document).ready(function() { //wait for document ready
$("#loaddaold").click(function () {
alert("123");
//$( "#duplicateshere" ).empty();
$.ajax({
type: "GET",
url: "ajax-oldmessages.php",
dataType: "xml",
success: xmlParser
});
});
});
function xmlParser(xml) {
alert("456");
//$("#rev2").slideDown();
$(xml).find("result").each(function () {
$("#appendhere").append('' + $(this).find("title").text() + '<br>');
//$(".book").fadeIn(1000);
});
}
})(jQuery);
// http://www.webdevdoor.com/jquery/javascript-delay-input-field-change/
// http://papermashup.com/parse-xml-with-jquery/
// (not used) http://www.paulund.co.uk/process-each-node-of-xml-in-jquery
</script>
The problem is that the xmlParser() function isn't being called after the successful ajax request. It shows a 123 alert but not a 456 alert. Am I doing something wrong, or is the tutorial wrong?
Previously on the other question I was told it was a CORS issue, but I was calling the file off my computer, and in my example, so what is the problem now?
if youre using
dataType: "xml"
and if you have an invalid xml in youre response then success wont triger
check youre response because its invalid... if you want to test your code just change
dataType: "html"
and you will see your alert(456) that confirms invalid xml data
I've duplicated your issue and by placing in my response a valid xml, code was running fine
Also if youre expected data is just an string that contains an id, try using
dataType: "xml text"
NOTE: As of jQuery 1.5, jQuery can convert a dataType from what it received in the Content-Type header to what you require

Javascript FormData function works with Chrome and Opera but not Firefox

var data = new FormData(document.getElementById("uploadform"));
$.each($('#file')[0].files, function(i, file) {
data.append('file-'+i, file, this.name);
});
That code works on Chromium 26 but not Firefox 21. I put an alert within the each loop, "alert(this.name)", which displays the filename in Chrome, but nothing in Firefox...so that's apparently where it's all bogging down in Firefox.
I also tried it on Firefox 24--same problem. I know this code used to work on Firefox--an older version than 21.
This slight change, just leaving off a couple parameters, gives me the same results:
var data = new FormData();
$.each($('#file')[0].files, function(i, file) {
data.append('file-'+i, file);
});
I just have no idea what's up, because Mozilla docs show that this is supported and that I'm doing it right.
Here's the ajax call portion of the code if anyone curious (but this is not the problem--it's bogging down in the above code per my alert check):
$.ajax({
url: 'upload.php',
data: data,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data){ }
Anyone have any similar problems, or have any inkling where to even look?
Are there errors in your browser's console? Check the Net (or Network) tab as well.
I would test in IE or Opera as well to confirm that it is specifically a FF issue.
Also try producing an alert
if (!window.FormData) {
alert('Doh!');
}

Internet explorer wont show the rendered gsp with embeded jquery

I send an Ajax request and the result is a table presented using data-table jquery plug-in. If the response is successful I will open a NEW WINDOW and display the result there. This works perfectly in FF but fails in IE 8. IE throws object expected error. For some reason it does not recognize the jquery libraries. But if I refresh the IE page once it will render the table successfully.
Am I missing anything here? what is different when I open a new window in IE?
function openResult (html){
var output = window.open("",null, "resizable=1,scrollbars=1,status=1,toolbar=0,menubar=0,location=0");
if (window.focus) {output.focus()}
output.document.open();
output.document.write(html);
output.document.close();
return false;
};
.....
$.ajax({
type: "POST",
url: "${g.createLink(action: 'search' )}?&time="+ date,
data: dataString,
success: function(response) {
$("#displayBox").hide()
openResult(response)
//$('#listTemplateDivId').html(response) ;
$.unblockUI()
}
});
#ThiefMaster Thanks for the suggestion. I endup using colorbox and its working perfectly.

Categories