LSN Rabbani LSN Rabbani - 13 days ago 4
Javascript Question

AJAX Post Showing An Error when Try to Upgrade jQuery Version

I have a lot of radio element which have different names and also values. And when I click the radio, it will send to server with AJAX method.

AJAX METHOD :

$("input[type=radio]").click(function() {
$.ajax({
url: "http://localhost/myproject/ajax_url",
type: "POST",
data: $("#my-form").serialize(),
dataType: JSON,
success: function(){}
});
});


Previously I was used jQuery version 2.2.4 and it works fine, but when I try to change it with jQuery version 3.1.1 it showing an error :


Uncaught TypeError: (o.dataType || "*").toLowerCase is not a function


I'm sure that what I type on server is not wrong (because I never changing my server code), the error just showing when I try to upgrade my jQuery version. Your solution might help me a lot :)

Answer

The problem is with JSON MDN

The JSON object contains methods for parsing JavaScript Object Notation (JSON) and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.

jQuery 2.x.x

It trims dataType and then returns string type [Object JSON] which is fine--string. jQuery.trim saves the day.

// Extract dataTypes list
s.dataTypes = jQuery.trim(s.dataType || "*").toLowerCase().match(rnotwhite) || [""];
// ------------------^^^^

jQuery 3.x.x

They removed $.trim and since you passed JSON which is defined (otherwise, OR operator || would pass string *.

// Extract dataTypes list
s.dataTypes = (s.dataType || "*").toLowerCase().match(rnothtmlwhite) || [""];

Fix

Enclose JSON by quotes so you string rather than an object. dataType accepts strings.

$.ajax({
        url: "http://localhost/myproject/ajax_url",
        type: "POST",
        data: $("#my-form").serialize(),
        dataType: 'json', // lowercase is always preferered though jQuery does it, too.
        success: function(){}
});
Comments