1

I have read other questions but my problem is little different. I am getting the response in a format like this from an eloquent query in Laravel.

[{"id":1,"message":"sdfsdf","message_for":1,"message_by":2},{"id":2,"message":"hello","message_for":4,"message_by":2},{"id":4,"message":"hi how are you?","message_for":1,"message_by":2}]

There is no variable attached to each object like in this question div1 , div2 etc. This is my ajax code

$.ajax({
        url: '/chat',
        type: 'POST',
        dataType: 'json',
        data: { id: sessionStorage.getItem('user_id') },
        //cache: false,
        success:function(data){
            /*var x;
            for(x in data){
                /!*$("span.messages").fadeIn("slow").append(data[x]);
                $("span.messages").append("<br>");*!/

            }*/
        },
        error: function(data) {
            console.log('data is :'+data.id);
            console.log("error");
        }
    });

And this is my controller function from where I am returning the response.

public function getUserMessages(Request $request){

        $id = (int)$request->request->get('id');
        $messages = Message::where('message_by' , $id)->get()->toJson();

        return $messages;
    }

I tried using data["message"] but it does not work. Using data[0] will return [.

Community
  • 1
  • 1
StealthTrails
  • 2,281
  • 8
  • 43
  • 67

3 Answers3

1

I used foreach to get the data

$.each(data, function(i, obj) {
  alert(obj.message);
});
StealthTrails
  • 2,281
  • 8
  • 43
  • 67
0

Using data[0] will return [

That seems like data is a String, not an Object.

One solution is to modify your PHP code so it tells the browser it is sending JSON:

header('Content-Type: application/json');

Another solution is to explicitly parse the JSON to get the object.

var data = JSON.parse(response);

Additionally, you have an array. The conventional way to iterate through an array is to increment an index. The newer way is to use the built-in .forEach() method. Alternatively, use jQuery's $.each() as another answer suggested.

success:function(response){
        var data = JSON.parse(response);
        var x;
        for (i = 0; i < data.length; i += 1)
            {
            var record = data[i];
            $("span.messages").fadeIn("slow").append(record.message);
            $("span.messages").append("<br>");
        }
    },
dsh
  • 12,037
  • 3
  • 33
  • 51
0

you are getting a collection of object from the controller. so you can do like this.

   success:function(data){    
        var x;
        for(x in data){
            $("span.messages").fadeIn("slow").append(data[x]['message']);
            $("span.messages").append("<br>");

        }

  },

the x will be your index.. based from your return.. you can call

data[x]['id']
data[x]['message']
data[x]['message_for']
data[x]['message_by']

depending what you need

Winston Fale
  • 1,316
  • 2
  • 11
  • 18