-3

The script below normally returns values formatted in into JSON object as shown below:

{"Value":null,"Status":2,"Message":"Greetings."}

For the past couple of days, we have been getting:

Record has been added successfully.**[obect Object]**

Any ideas what could have gone wrong?

This is the code below.

 <script type="text/javascript">

    function CallService() {

     //Creating an object to hold token form field
     myToken = new Object();
     myToken.Token =  $("#token").val();

     //Creating an object to hold form fields
     myData = new Object();

      // Creating variables to hold data from textboxes. First building associated details
      myData.Address = $("#Address").val();
      myData.CallerAcctNum = $("#CallerAcctNum").val();
      myData.CallerAddress = $("#CallerAddress").val();
      myData.CallerCellPhone = $("#CallerCellPhone").val();
      myData.CallerCity = $("#CallerCity").val();
      myData.CallerComments = $("#secondarysitecontact").val();
      myData.CallerDistrict = $("#CallerDistrict").val();
      myData.CallerEmail = $("#CallerEmail").val();
      myData.CallerFax = $("#CallerFax").val();
      myData.CallerFirstName = $("#CallerFirstName").val();
      myData.CallerHomePhone = $("#CallerHomePhone").val();
      myData.CallerLastName = $("#CallerLastName").val();
      myData.CallerMiddleInitial = $("#CallerMiddleInitial").val();
      myData.CallerState = $("#CallerState").val();
      myData.CallerWorkPhone = $("#CallerWorkPhone").val();
      myData.CallerZip = $("#CallerZip").val();
      myData.City = $("#City").val();
      myData.Details = $("#comments").val();
      myData.District = $("#District").val();
      myData.Location = $("#Location").val();
      myData.ProblemSid = $("#RequestID").val();
      myData.State = $("#State").val();
      myData.StreetName = $("#StreetName").val();
      myData.X = $("#X").val();
      myData.Y = $("#Y").val();
      myData.SiteContactDisplay = $("#sitecontact").val();
      myData.Comments = $("#comments").val();
      myData.Text1 = $("#deptId").val();
    $.ajax({
        type: "POST",
        url: "proxyCreate.php",
        data: {
            data: JSON.stringify(myData),
           token: myToken.Token
        },
        dataType: "json",
        async: false,
        success: function (response) {
          alert("Record has been added successfully." +  response  );
            window.location.reload();
        }
    });
      return false;
     }
    </script>
Chidi Okeh
  • 1,537
  • 8
  • 28
  • 50

2 Answers2

2

alert() cannot print an {} object [object Object] unless you JSON.stringify it.
If you usually returned from your success this object:

{"Value":null,"Status":2,"Message":"Greetings."}

from your response argument, than you need to access a desired Object property like:

alert( response.Message );

otherwise, if you want to read fully the object do something like:

alert( JSON.stringify( response, null, "\t") );

Furthermore, to simplify your code I made some changes:

function v(id){ return $("#"+id).val(); } // Get value
function CallService() {

  var myToken = v("token");
  var myData  = {
    Token               : v("token"),
    Address             : v("Address"),       
    CallerAcctNum       : v("CallerAcctNum"),
    CallerAddress       : v("CallerAddress"),
    CallerCellPhone     : v("CallerCellPhone"),
    CallerCity          : v("CallerCity"),
    CallerComments      : v("secondarysitecontact"),
    CallerDistrict      : v("CallerDistrict"),
    CallerEmail         : v("CallerEmail"),
    CallerFax           : v("CallerFax"),
    CallerFirstName     : v("CallerFirstName"),
    CallerHomePhone     : v("CallerHomePhone"),
    CallerLastName      : v("CallerLastName"),
    CallerMiddleInitial : v("CallerMiddleInitial"),
    CallerState         : v("CallerState"),
    CallerWorkPhone     : v("CallerWorkPhone"),
    CallerZip           : v("CallerZip"),
    City                : v("City"),
    Details             : v("comments"),
    District            : v("District"),
    Location            : v("Location"),
    ProblemSid          : v("RequestID"),
    State               : v("State"),
    StreetName          : v("StreetName"),
    X                   : v("X"),
    Y                   : v("Y"),
    SiteContactDisplay  : v("sitecontact"),
    Comments            : v("comments"),
    Text1               : v("deptId")
  };

  $.ajax({
    type: "POST",
    url: "proxyCreate.php",
    data: {
      data: JSON.stringify(myData),
      token: myToken
    },
    dataType: "json",
    async: false,
    success: function (response) {
      console.log( response ); // open console and take a look.
      alert("Record has been added successfully." +  response  ); // Nest with "." like response.something to print property you need
      // window.location.reload(); // Do this later after you fix the bug
    }
  });
  return false;

}
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313
  • @RokoCBuljan, Really gorgeous and elegant code. Thank you very much. To all of you, thank you very much for your contribution. You have given me plenty to use and try to resolve this problem. One point I do want to point out is that I do clearly understand the point you guys have made. My point is that nothing has changed on the server side. All my PHP codes are json encoded. For instance, all end with `echo json_encode($results);` Thanks again very much. – Chidi Okeh Dec 17 '14 at 02:35
0

You have to specify which part of the object you want to print, for instance if you wanted the message:

 $.ajax({
        type: "POST",
        url: "proxyCreate.php",
        data: {
            data: JSON.stringify(myData),
           token: myToken.Token
        },
        dataType: "json",
        async: false,
        success: function (response) {
          alert("Record has been added successfully." +  response.Message  );
            window.location.reload();
        }
    });

You're trying to use alert, which takes an string and prints it on a dialog, and giving it an object, which... well, it's not an string. Your object CONTAINS strings, so you can access them and print them instead of trying to print the entire object, like show in the code above, where I whent to the message attribute of the response object.

Even simpler example: http://jsfiddle.net/9c0xLwcq/

vcanales
  • 1,818
  • 16
  • 20
  • FelixKling, please take it easy on me? Where did I go wrong? As I stated, this code has been working for months. So, how did I screw it up? @devJunk, Sorry I miss your point because when I add response.message,now it says, undefined. – Chidi Okeh Dec 16 '14 at 22:03
  • @RokoC.Buljan, where should I have posted it? Also, when I run the script, normally, it returns something like this: `{"Value":null,"Status":2,"Message":"Greetings."}` Now, it returns a bunch of html. Maybe, tha's the reason for the [object Object] message but how do I correct it? – Chidi Okeh Dec 16 '14 at 22:08
  • Updated my answer to be clearer. – vcanales Dec 16 '14 at 22:09
  • @ChidiOkeh: You should have commented on your question. The reason you get `[object Object]` is because `response` is an object and `"[object Object]"` is the default string representation of an object. There is nothing really "wrong" here. One just doesn't usually concatenate an object with a string because it's not that useful. How to correct it depends on what you want as result. If you want to see the JSON data, you have to convert the object back to JSON: `JSON.stringify(response)`. – Felix Kling Dec 16 '14 at 22:11
  • @FelixKling, when the code works fine like it used to work, it returns all those values in JSON format like below example: `{"Value":null,"Status":2,"Message":"Greetings."}` My biggest question is what changed? It is the same code that has been working fine by returning values into JSON object but suddenly it stopped. devJunk, I see the alerts but the code example still doesn't make sense to me. I say this NOT in a bad way. I still don't see how your code is different from mine except the Message you added which now returns null. So, something other than that is wrong. – Chidi Okeh Dec 16 '14 at 22:16
  • @ChidiOkeh I don't know if we can simplify this any further. `alert()` takes a STRING. You are passing an OBJECT. The `response` from your server must have recently changed from a string literal to JSON. You even have `dataType` set to JSON in your AJAX call, so I'm not sure how that alert box worked before. But it really is that simple. You can't call `alert()` with anything other than a `string`. – Antiga Dec 16 '14 at 22:20
  • @ChidiOkeh: Because you tell jQuery to interpret the response as JSON (`dataType: 'json'`) it will convert it automatically for you to an object. It shouldn't have behaved different before, unless you sent a string encoded as JSON before (e.g `"[1,2]"` instead of `[1,2]`). What does `console.log(response);` show you? – Felix Kling Dec 16 '14 at 22:21
  • Most likely the server code changed or was updated to return a proper Content-Type, causing jQuery to automatically convert it to an object. though, `dataType: "json"` should have already been doing that. – Kevin B Dec 16 '14 at 22:42