jqueryajaxjquery-easyui

easyui return undefined from ajax


I make form submit, when I check in console it returns JSON data. But I can't use object in JSON data.

$('#ff').form({
                type: 'POST',
                cache: false,
                url: base_url + 'Api/lapor/submit',
                dataType: 'json',
                iframe: false,
                onSubmit: function(param) {
                    param.id_item = sessionStorage.id_item;
                    param.token = sessionStorage.token;
                },
                onProgress: function(percent) {
                    $.messager.progress();
                },
                success: function(msg){
                  console.log(msg.status); //it will return undefined
                  $.messager.progress('close');
                },
                onLoadError: function(){
                    $.messager.alert('Error', 'Gagal', 'error');
                }
            });

I try console.log(msg) and it return JSON data console


Solution

  • When you log the return message using console.log(msg.status);, if it write the result as {message: "Data 1 telah disimpan", status: true} then you can call it by using either msg.status or msg['status']

    But in your case it's logged as {"message": "Data 1 telah disimpan", "status": true}, so you should try calling it with the " included like msg['"status"'] or msg["\"status\""]

    var msg1 = {"message": "Data 1 telah disimpan", "status": true}
    var msg2 = {'"message"': "Data 2 telah disimpan", '"status"': true}
    
    function checkdata1() {
      console.log(msg1);
      alert(msg1.message);
    }
    
    function checkdata2() {
      console.log(msg2);
      alert(msg2['"message"'])
    }
    <btn onclick="checkdata1()">Check Data 1</btn>
    <br/>
    <btn onclick="checkdata2()">Check Data 2</btn>

    Update Here's the difference between the msg1 and msg2 when logged using console.logdifference

    Update 2 Because the return type of jeasyui $.form is a string, so you need to parse it first to a JSON / javascript object by using JSON.parse or the one found in the jeasyui docs section Handle submit response here