0

Have such php array

Array
(
[Title] => Text for title  
[Description] => Text for: description.
)

Then from php send back to jquery with echo json_encode($meta_back, JSON_HEX_QUOT|JSON_HEX_TAG|JSON_HEX_AMP|JSON_HEX_APOS);

In jquery with alert see this

{"Title":"Text for title  ","Text for: description."}

then

$.each( [ meta_from_url ], function( title, description ) {
alert( 'title_ ' + title + ' description_ ' + description );
});

And with alert see

title_ 0 description_ {"Title":"Text for title  ","Description":"Text for: description."}

What is incorrect in my code? title is 0 and whole data is in description

2
  • 1
    Have you tried using JSON.parse on the return value before attempting to loop over it? Commented Aug 14, 2014 at 11:26
  • Tried with $.parseJSON( meta_from_url ); and get something like Object.. Commented Aug 14, 2014 at 11:36

4 Answers 4

1

Why loop over the properties of an object? Just access them directly

alert( 'title_ ' + meta_from_url.Title + ' description_ ' + meta_from_url.Description );
Sign up to request clarification or add additional context in comments.

Comments

1

Your code is correct and is functioning properly.

$.each( [ meta_from_url ], function( title, description ) {
alert( 'title_ ' + title + ' description_ ' + description );
});

Here title is KEY and description is VALUE for the array. Your first entry has KEY value 0. Thus it is printing 0.

What you need is :

$.each( [ meta_from_url ], function( title, description ) {
alert( 'title_ ' + description.Title + ' description_ ' + description.Description );
});

1 Comment

hmmm, also see title_ undefined description_ undefined
1

Use it like this

var data = $.parseJSON( meta_from_url );
alert( 'title_ ' + data.Title + ' description_ ' + data.Description );

2 Comments

wit alert see title_ undefined description_ undefined
sorry all is ok. I was missing var meta_from_url = $.parseJSON( meta_from_url ); But in answer instead of data should be meta_from_url
0

The callback of your $.each expects ( index, object ) as parameters. Not two strings. That's why title_ is 0 (index) and description_ is the string representation of your whole object.

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.