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 [.

4
  • You need to json_encode : return Response::json($message); Commented Sep 4, 2015 at 8:23
  • 1
    actual problem is how to loop through> Commented Sep 4, 2015 at 10:13
  • Please show what returns data by editing your post Commented Sep 4, 2015 at 10:14
  • data is returned by $messages as i described above. Commented Sep 4, 2015 at 10:20

3 Answers 3

1

I used foreach to get the data

$.each(data, function(i, obj) {
  alert(obj.message);
});
Sign up to request clarification or add additional context in comments.

Comments

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>");
        }
    },

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.