I try at the moment to get a Multiarray response from a ajax Post json request. After hours of trys iam now hope to get help here...
JS AJAX RESPONSE
var data = {
"myid": "1234"
};
$(".the-return").html("");
$.ajax({
type: "POST",
dataType: "json",
url: "../post_test/ajax.php",
data: data,
success: function(data) {
$.each(data, function (i, item) {
$(".the-return").append("JSON: " + data["messages"]+"<br>");
});
alert("Form submitted successfully.
Returned json: " + data["json"]);
}
})
return false;
PHP
$personen = array(
//for each loop from Database
array("message","from","to ","datetime"),
//pushing a Array in a Array ?????
);
So my Question is now...
-> How to return a stable Array to the Ajax Success Function?
-> And how to read the Return at the Sucess Function so i can Add it with
$("#chatbox_"+chatboxtitle+" .chatboxcontent").append('<div class="chatboxmessage"><span class="chatboxmessagefrom">'+item.f+': </span><span class="chatboxmessagecontent">'+item.m+'</span></div>');
I already searched about 40 Sites in Google about Arrays and Ajax Returns but iam not able to figure out the right Way.
My try with
$.each(data.items, function(i,item){
And on PHP Site
$items .= <<<EOD
{
"s": "0",
"f": "{$chat['from']}",
"m": "{$chat['message']}"
},
EOD;
Crashs the Trigger of the Ajax completetly ...
THANKS for all Answers
EDIT Its Encoded already in PHP -> I need something on JS Side like for each message in messages from ajax response message is FROM going TO with TEXT
Example of how to do it. File varex2.php returns an array of arrays in JSON format. File varex1.php decodes the JSON data and displays it in "alert" windows. To test next codes, create two text file, use the given names, copy-paste the codes, open your browser and run localhost/varex1.php
, here they are:
varex2.php
<?php
// THIS IS AN ARRAY OF ARRAYS.
$products = Array( Array( "code" => "0401",
"name" => "shoes",
"price" => 700
),
Array( "code" => "0992",
"name" => "shirt",
"price" => 250
),
Array( "code" => "5800",
"name" => "glasses",
"price" => 400
)
);
$json = json_encode( $products );
echo $json; // ARRAY RETURNED IN JSON FORMAT.
?>
varex1.php
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'varex2.php',
success: function ( data ) {
var i;
var obj = JSON.parse( data ); // DECODE JSON DATA.
for ( i = 0; i < obj.length; i++ ) // WALK THE SUB-OBJECTS.
alert( obj[ i ].code + "
" +
obj[ i ].name + "
" +
obj[ i ].price );
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
<button onclick="myAjax()">Click here to get the data</button>
</body>
</html>