Skip to content
Advertisement

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

Advertisement

Answer

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.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement