1

I want to send array from php to jquery using json. the array in received but I have a problem to take elements from array.

I did this:

<?php
    $result[0] = 1;
    $result[1] = 6;
    echo json_encode($result);
?>

<script type="text/javascript">
$("#saveOrder").click(function(){           
    var customerName = $('input#customerName').val();
    var param = {"customerName":customerName,"action":"addOrder"};
    $.ajax({
            url: "controllers/Order.controller.php",  
            type: "POST",     
            data: param,                
            cache: false,       
            success: function (result) {        
        alert("result"+result);
        $.each(result,function(i,elem){
            alert(i+"_"+elem); 
        });

        var suc = result[0];
        alert("suc"+suc);
        var orderId = result[1];
        alert("id"+orderId);
                if (suc==1) {     
                    $('#resultMsg').text("success");  

                } else {              
            $('#resultMsg').text("error");  
        }
            }       
        });
        });
</script>

when I iterate through array, it display strange elements!

first,second, third and forth 
       loops : display nothing
fifth loop   : display [
sixth loop   : display 1
seventh loop : display ,
eighth loop  : display 6
ninth loop   : display ]

how can I get the elements?

2
  • The strange elements are the characters of the JSON array string [1,6] being returned. Commented Aug 9, 2011 at 12:51
  • yes I know that, but the first four element are empty, what they are? Commented Aug 9, 2011 at 13:27

3 Answers 3

3

The result is a JSON string. Use JSON.parse to get the array.

Sign up to request clarification or add additional context in comments.

Comments

0

Inside your AJAX call, try adding dataType: "json" or you can use JSON.parse(result) to get a JSON object from your result.

Comments

0

you have not set the dataType parameter, please do the following:

dataType: "json"

1 Comment

I use jquery 1.7, so I don't have to add (dataType: "json")

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.