ffuentes
ffuentes

Reputation: 1182

How to read the response of a successful Ajax call on jquery/javascript?

I have a function that gets a small json string:

 <script id="local" type="text/javascript">

$( document ).ready(function() {
    $('tr').on('blur', 'td[contenteditable]', function() {
        var that = this;
        $.post("ajax/modQtyModels", {
        modelId: $(this).closest('tr').children('td.idmodel').text(),
        qty: $(this).closest('tr').children('td.editQty').text(),
        ajax: true,     
        dataType: 'json',
        success: function(data) {   
            var myResult = JSON.parse(data);
            if(myResult['success'] == "true") {
                $(that).closest('tr').children('td.editQty').addClass("success");
            } else {
                $(that).closest('tr').children('td.editQty').addClass("danger");
                alert("No changes were made");
            }
        }
        }
);
    });
});
</script>

The problem is I need to read the response but it doesn't get me anything but errors. myResult['success'] doesn't get the value of the json string as I expected.

Method

@PostMapping("/ajax/modQtyModels")
public @ResponseBody String modDevices(Model model, @RequestParam(value = "modelId", required = true) Long modelId,  @RequestParam(value = "qty", required = true) int qty) {
    Optional<com.ffuentese.model.Model> mdl = modelRepository.findById(modelId);
    if(mdl.isPresent()) {
        mdl.get().setQty(qty);
        modelRepository.save(mdl.get());
        return "{\"success\": true}";
    }
    return "{\"success\": false}";
}

EDIT: No luck so far. As long as I don't attempt to access data everything works just fine and if I check the response on Chrome it's there.

Response as seen in the browser when data is not accessed.

EDIT 2: The error I get when I try to access data:

models:27 Uncaught TypeError: Cannot read property 'success' of undefined at success (models:27) at e (jquery.min.js:4) at xb (jquery.min.js:4) at Function.r.param (jquery.min.js:4) at Function.ajax (jquery.min.js:4) at Function.r.(anonymous function) [as post] (https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:4:14657) at HTMLTableCellElement. (models:22) at HTMLTableRowElement.dispatch (jquery.min.js:3) at HTMLTableRowElement.q.handle (jquery.min.js:3) at Object.trigger (jquery.min.js:4)

EDIT 3: Solved after rearranging the elements of the AJAX call as stated in the accepted response edition.

Upvotes: 2

Views: 4817

Answers (2)

terry.qiao
terry.qiao

Reputation: 2065

You don't have to parse JSON manually, JQuery does this for you. So, just remove var myResult = JSON.parse(data); from your code, and use data directly.

Try this:

$.post("ajax/modQtyModels",
    {
        modelId: $(this).closest('tr').children('td.idmodel').text(),
        qty: $(this).closest('tr').children('td.editQty').text()
    },
    function(data) {
        var myResult = data;
        if(myResult['success'] == "true") {
            $(that).closest('tr').children('td.editQty').addClass("success");
        } else {
            $(that).closest('tr').children('td.editQty').addClass("danger");
            alert("No changes were made");
        }
    },
    'json'
});

Upvotes: 0

Taki
Taki

Reputation: 17664

From : https://api.jquery.com/jquery.post/

dataType

Type: String

The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).

you're expecting the server to return a json but you're returning a string , so either you remove dataType : 'json' from your $.post or you keep it and return a json from the server with return {"success": true}; and if your return a json remove JSON.parse(data);

and when you compare the success , use if(myResult['success'] == true) {

const data = '{"success": true}';

let myResult = JSON.parse(data);

if(myResult['success'] == "true") {
	console.log('here with quotes');
} 

if(myResult['success'] == true) {
	console.log('here without quotes');
} 
else {
  console.log("No changes were made");
}

EDIT :

don't mix the data you're sending with the success, use a callback instead, your $.post should be like : $.post(url, dataToServer, callback, dataTypeExpected);

try this :

 $.post("ajax/modQtyModels", 
        {
            modelId: $(this).closest('tr').children('td.idmodel').text(),
            qty: $(this).closest('tr').children('td.editQty').text()
        }, 
        function(data){ 
            //var myResult = JSON.parse(data);
            if(data['success'] == true) {
                $(that).closest('tr').children('td.editQty').addClass("success");
            } else {
                $(that).closest('tr').children('td.editQty').addClass("danger");
                alert("No changes were made");
            } 
        }, "json");

Upvotes: 1

Related Questions