I am a beginner in Javasript.Now I trying to make a http request to my php server,which will return a Json response like this:
{
"error": false,
"user_id": 1,
"user": {
"username": "abc",
"email": "[email protected]",
"http://192.168.1.1/abc/v1/profilepic/defaultmale.jpg"
}
}
I make the Ajax call like the following,but I didn't get any response from my browser,and as I see is didn't do anything.
What I tried so far
<script type="text/javascript">
$(document).ready(function () {
$("#loginBtn").click(function () {
var vEmail = $("#email").val();
var vPassword = $("#password").val();
if(vEmail ==='' &&vPassword === ''){
alert("please enter email and password");
}else if(vEmail !== '' && vPassword===''){
alert("password required");
}else if(vEmail ==='' && vPassword !== ''){
alert("email required");
}else{
$.post("http://localhost/abc/v1/login",
{email:vEmail, password:vPassword},
function(response){ // Required Callback Function
//"response" receives - whatever written in echo of above PHP script.
alert(response);
}
);
}
});
});
</script>
I cant get alert in my browser,I tried console.log(response) as well,I also cant see in my inspect element in Google Chrome.
I tried like below as well,also no luck
var obj = $.parseJson(response);
alert(obj['user_id']);
What I need to know
1) Is this the correct way to make the Http request via Jquery?If not,what is the correct way?
2) How can I test whether I successfully get the response?can it be print out anyway for testing purpose?
3) How can I parse the Json correctly using Jquery?
Thanks for advance.
UPDATE
I adding the fail function as well,but when I filled in email and password,it still nothing happen(means the browser just refresh,no alert,console log just blank).
$.post("http://localhost/abc/v1/login",
{email:vEmail, password:vPassword},
function(response,status){ // Required Callback Function
//"response" receives - whatever written in echo of above PHP script.
alert(JSON.stringify(response));
},fail(function () {
alert("failed");
})
);
Can somebody show me the correct way to do it?
UPDATE
After following @Mendax answer,I get the response in console.log with this response.What is this means?
Error
Object {readyState: 0, getResponseHeader: function, getAllResponseHeaders: function, setRequestHeader: function, overrideMimeType: function…}
failfunction so that you can catch erros.