I have been searching everywhere and I am not getting anywhere. This is what I am using: Custom PHP MVC this is what I am trying to get: From userView.php I want to replace an id="ShowName" with JSON data from a ajax Call using JQuery
This is what I have: userController.php
if (isset($_POST['id'])) {
$this->getView('users', $this->object->getUser($_POST['id']));
}
userModel.php
public function getUser($id) {
$this->user = array();
parent::getConnection();
$this->sql = $this->dbh->query("SELECT * FROM User WHERE idUser='". $id ."'");
parent::errorHandler();
$this->results = $this->sql->fetch(PDO::FETCH_ASSOC);
$this->user[] = array(
'name' => $this->results['name'],
'lastname' => $this->results['lastname'],
'email' => $this->results['email']
);
$obj['user'] = $this->user;
parent::closeConnection();
header('Content-Type: application/json');
print json_encode($obj);
}
userView.php
<select class="form-control blue select" id="getUserID">
<option value="default">Seleccione un Usuario</option>
<?php $this->object->getUserslist();?>
</select>
<span id="name"></span>
Method getUsersList() inside userModel
public function getUsersList() {
parent::getConnection();
$this->sql = $this->dbh->query("SELECT * FROM User ORDER BY name ASC");
parent::errorHandler();
while($this->results = $this->sql->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $this->results['idUser'] . "'>" . $this->results['name'] . "</option>";
}
parent::closeConnection();
}
JQuery
$("#getUserID").change(function(){
var userID = $("#getUserID").val();
$.ajax({
type: 'POST',
url: 'user',
data: 'id='+userID,
dataType: 'json',
success: function(data){
var obj = $.parseJSON(data);
alert(obj.name)
}
});
});
It retrieves JSON data at the very top of the html file, but the alert is not prompting, so I guess it gets data before the success is called.
Direct Question: How can I retrieve the JSON data from PHP so I can use it in html from JQUERY ajax Response?
Thanks!!!!