views:

240

answers:

2

I have a function which submits data to my server, and then removes the edit UI and replaces it with the regular UI. This works perfectly under JQuery 1.3.2 but does not work with JQuery 1.4.0. Any ideas?

function save_edit(point_id) {
  var data = {};
  data.id = point_id;
  $.post("/foo", data, function(responseData) {
    $("#value" + point_id).show();
    $("#editval" + point_id).hide();
  }, "json");
}
A: 

jQuery 1.4 using strict JSON parsing, as mentioned in the release notes. Is your data valid JSON?

Mike Robinson
+7  A: 

jQuery 1.4 is very picky about valid JSON response text. The following is not valid JSON (and most likely your problem)

 {foo:'bar'}

 // Strict JSON requires quoted attributes - and the quotes must be doubles!

 {"foo": "bar"}

This blog post mentions a workaround using 'text' instead if you can't fix the serverside JSON easily. Applied to your function you get:

function save_edit(point_id) {
  var data = {};
  data.id = point_id;
  $.post("/foo", data, function(responseText) {
    var responseData = eval("("+responseText+")");
    $("#value" + point_id).show();
    $("#editval" + point_id).hide();
  }, "text");
}

Also, you would be able to handle an error case doing something like this:

function save_edit(point_id) {
  var data = {};
  data.id = point_id;
  var $edit = $("#editval"+point_id);
  var $view = $("#value"+point_id);
  $.ajax({
    method: "POST",
    url: "/foo", 
    data: data, 
    success: function(responseData) {
      $view.show();
      $edit.hide().find('.error').remove();
    },
    error: function(XHR, textStatus, errorThrown) {
      var $err = $edit.find(".error");
      if ($err.length == 0) { $err = $("<div class='error'/>").appendTo($edit); }
      $err.text("Error: "+textStatus);
    }
  });
}   
gnarf
jQuery 1.4 is very strict, however jResig has provided a plugin if you want to run 1.4 and still provide 1.3.2 compatability - link: http://github.com/jquery/jquery-compat-1.3
MJJames
My problem was that the server was using single quote (') instead of double quote ("). It was returning data of the form {'foo': 'bar'} instead of {"foo": "bar"}. Once I fixed that, the javascript now works. Thanks!
eggplant