0

I am trying to encode my array results to json and pass them to a ajax successful event in javascript.

PHP

    $results = array(
        "time1" => 1,
        "time2" => 2,

    );
    echo json_encode($results); 

JAVASCRIPT / JQUERY

   $.ajax({
             type: "POST",
             url: "actions/myphp.php",
             data: PassArray,
             dataType: 'json',
             beforeSend: function (html) { // this happens before actual call
             //    alert(html);
             },
             success: function (html) { 
                 // $("#loginoutcome").text(html);
                // alert(html);
                 var obj  = jQuery.parseJSON(html ); 
                // Now the two will work
                $.each(obj, function(key, value) {
                    alert(key + ' ' + value);
                });

             },

Leaving the JQUERY.parseJSON there throws a json parse unexpected character, I dont think I that I need it anyway as I specify in the dataType: 'json', above?.. But how can I retrieve the values ??

Thanks

0

1 Answer 1

2

As you pass datatype as JSON, jQuery will give you back the JSON object, you don't have to parse it anymore.

So make it like this:

success: function (obj) { 
            $.each(obj, function(key, value) {
                alert(key + ' ' + value);
            });

         },

If you know its time1 or time2, you can do this:

success: function (obj) { 
            alert(obj.time1);
            alert(obj.time2);
         },
Sign up to request clarification or add additional context in comments.

1 Comment

thanks, good answer the other problem that I had is that I had more than one echo and I needed only one.

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.