I am using an MVC approach here. In my javascript code, under the success function.. when I use the console.log(data.msg) code, my expected result comes up.
But when I use the $('#res').text("".data.msg) .. the output is TypeError: "".data is undefined from the console..
And if I use $('#res').text(data.msg)... There is no output in the console..
I expect the result to show in the text field having the id of res.
Here is the html code
<form action="" method="post">
<input type="text" id="uname">
<input type="submit" id="submit">
<input type="text" id="res">
</form>
Here is the javascript code
$(document).ready(function(){
$('#submit').click(function() {
$.ajax({
type : 'POST',
url : 'ajax/checkLogin',
dataType : 'json',
data: {
uname : $('#uname').val(),
},
success : function(data){
$('#res').text("".data.msg);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error");
}
});
return false;
});
});
And here is the method code of the controller named Ajax
public function checkLogin()
{
$return['error'] = false;
while (true) {
if (empty($_POST['uname'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you username.';
break;
}
if ($_POST['uname'] == "tin") {
$return['msg'] = 'successful';
break;
}else{
$return['error'] = true;
$return['msg'] = 'Wrong username:'.$_POST['uname'];
break;
}
break;
}
echo json_encode($return);
}
console.log(data);???And if I use $('#res').text(data.msg)... There is no output in the console..How this code will output the data in the console..?console.log(JSON.stringify(data));