sahar
sahar

Reputation: 569

how to get array element in jquery from php

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?

Upvotes: 1

Views: 1033

Answers (3)

mysterious
mysterious

Reputation: 1478

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

dataType: "json"

Upvotes: 0

Kyle
Kyle

Reputation: 4449

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

Upvotes: 0

Sleeperson
Sleeperson

Reputation: 612

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

Upvotes: 3

Related Questions