When I make the POST to a PHP page, the echo’ed data still comes back to me but the jQuery AJAX says it’s not a success. Why would this be? And further, how can I actually “print” out the data once I get it back?
My PHP is below:
<?php
$userEmail = $_POST['username'];
$userPassword = $_POST['password'];
//Login Function
$data = array("username" => $userEmail, $userPassword => "password");
$data_string = json_encode($data);
$ch = curl_init('http://*****/****/**/Login');
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, 1 );
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-Type: application/json')
);
$result = curl_exec($ch);
$obj = json_decode($result);
echo $obj;
echo '<br /><br />';
echo '<b>Each array and objects in table:</b> <br />';
echo '<hr>';
echo '<br />';
echo '<table border="1">';
echo '<tr><td>Medical Entity:</td><td>Date:</td><td>Type:</td><td>ID:</td></tr>';
foreach ($obj as $key => $value) {
echo '<tr>';
echo '<td>' . $value->date . '</td>';
echo '<td>' . $value->Name . '</td>';
echo '<td>' . $value->dealType . '</td>';
echo '<td>' . $value->id . '</td>';
echo '</tr>';
}
echo '</table>';
?>
The jQuery AJAX is below:
<div id="test">
Testing Stuff!
</div>
<script>
$(document).ready(function() {
$('#submit').click(function () {
var username = '***@****.com';
var password = 'password';
var data = '&username=' + username + '&password=' + password;
$.ajax({
type: "POST",
url: "/****/data.php",
data: data,
dataType: "json",
success: function(e){
for(var i=0;i<e.length;i++){
document.write(e[i]);
}
},
error: function(e){
for(var i=0;i<e.length;i++){
$('#test').html(e[i]);
}
});
//cancel the submit button default behaviours
return false;
});
});
</script>
My ultimate goal is to write out the data I get from the PHP page to a DIV on my HTML page via AJAX.
You are calling your php function using
dataType: json, meaning jQuery is expecting a JSON result to be returned. Your php file is returning HTML. Remove the dataType: JSON setting.The variable that gets passed to the
successfunction is not an array. You just need to do something like$('#test').html(e);