unable to view ajax response in chrome dev tools - ajax

I'm trying to view the AJAX response in Chrome DevTools. However, I'm greeted with, "the request has no response data available." Am I doing something wrong?
Here's the request (I'm always greeted with the "response false" alert, even if it's a valid email address. Hence, my trying to troubleshoot. However, I'll leave that for another question):
$("#email_address").on("keyup", function() {
request = $.ajax({
url: 'verify_email.php',
data: {email: $("#email_address").val(),
submitted: true},
type: 'post'
});
request.done(function(response) {
if(response == true) {
alert("response true");
} else if(response == false) {
alert("response false");
} else {
alert("heh?");
}
});
request.error(function(response) {
alert("an error occurred");
});
});
Here's my verify_email.php code that's called with the AJAX request, if it helps at all:
<?php
if(isset($_POST['submitted']) and isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
?>

Try:
<?php
if(isset($_POST['submitted']) && isset($_POST['email'])) {
if(filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
echo 'true';
return true;
} else {
echo 'false';
return false;
}
}
?>
I've never used and in an if() myself (does it work?). Probably not your problem though ...
You're not echoing anything onto the page so you're return a page that's got no response data to show.

Related

Return user id along with Ajax Success response

I have Ajax login submit that works just fine. Now i need to send the $user_id back to the login page on success. But cant figure out how.
Below is what i have.
This is the php page
<?
if (!securePage($_SERVER['PHP_SELF'])){die();}
//Prevent the user visiting the logged in page if he/she is already logged in
if(isUserLoggedIn()) { header("Location: account.php"); die(); }
//Forms posted
if(!empty($_POST))
{
$errors = array();
$username = sanitize(trim($_POST["user"]));
$password = trim($_POST["password"]);
//Perform some validation
//Feel free to edit / change as required
if($username == "")
{
$response['success'] = false;
}
if($password == "")
{
$response['success'] = false;
}
if(count($errors) == 0)
{
//A security note here, never tell the user which credential was incorrect
if(!usernameExists($username))
{
$response['success'] = false;
}
else
{
$userdetails = fetchUserDetails($username);
//See if the user's account is activated
if($userdetails["active"]==0)
{
$response['success'] = false;
}
else
{
//Hash the password and use the salt from the database to compare the password.
$entered_pass = generateHash($password,$userdetails["password"]);
if($entered_pass != $userdetails["password"])
{
//Again, we know the password is at fault here, but lets not give away the combination incase of someone bruteforcing
$response['success'] = false;
}
else
{
//Passwords match! we're good to go'
$response['success'] = true;
}
}
}
}
}
//$user_id = $loggedInUser->user_id;
echo json_encode($response);
?>
Here is the ajax that calls the php page. And also where i need to retrieve the ID from php page.
<script type="text/javascript">
//login ajax to send over user and pass LS
function handleLogin() {
var form = $("#loginForm");
//disable the button so we can't resubmit while we wait
$("#submitButton",form).attr("disabled","disabled");
var e = $("#user", form).val();
var p = $("#password", form).val();
console.log("click");
if(e != "" && p != "") {
var str = form.serialize();
//McDOn(str);
$.ajax({
type: 'POST',
url: 'http://vsag.actualizevps.com/loginmobile.php',
crossDomain: true,
data: {user: e, password :p},
dataType: 'json',
async: false,
success: function (response){
//alert ("response");
if (response.success) {
//alert("you're logged in");
window.localStorage["user"] = e;
//window.localStorage["password"] = md5(p);
//window.localStorage["UID"] = data.uid;
window.location = "create.html";
}
else {
alert("Your login failed");
//window.location("main.html");
location.reload();
}
},
error: function(error){
//alert(response.success);
alert('Could not connect to the database' + error);
window.location = "main.html";
}
});
}
else {
//if the email and password is empty
alert("You must enter user and password");
}
return false;
}
</script>
the $response value is just true or false at the moment, you could return an array:
$response = array("Success" => true, "UserId" => $user_id);
and on you AJAX response, the response variable
response.UserId
will contain the user id

AJAX Form Validation to see if course already exist always return true

I want to validate my course name field if the course name inputted already exist using AJAX, but my ajax function always return the alert('Already exist') even if i inputted data that not yet in the database. Please help. Here is my code. Thanks.
View:
<script type="text/javascript">
var typingTimer;
var doneTypingInterval = 3000;
$('#course_name').keyup(function(){
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
});
$('#course_name').keydown(function(){
clearTimeout(typingTimer);
});
function check_course_name_exist()
{
var course_name=$("#course_name").val();
var postData= {
'course_name':course_name
};
$.ajax({
type: "POST",
url: "<?php echo base_url();?>/courses/check_course_name_existence",
data: postData,
success: function(msg)
{
if(msg == 0)
{
alert('Already Exist!');
return false;
}
else
{
alert('Available');
return false;
}
return false;
}
});
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
}
</script>
Controller:
function check_course_name_existence()
{
$course_name = $this->input->post('course_name');
$result = $this->course_booking_model->check_course_name_exist($course_name);
if ($result)
{
return true;
}
else
{
return false;
}
}
Model:
function check_course_name_exist($course_name)
{
$this->db->where("course_name",$course_name);
$query=$this->db->get("courses");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
You could use console.log() function from firebug. This way you will know exactly what the ajax returns. Example:
success: function(msg) {
console.log(msg);
}
This way you also know the type of the result variable.
jQuery, and Javascript generally, does not have access to the Boolean values that the PHP functions are returning. So either they return TRUE or FALSE does not make any difference for the JS part of your code.
You should try to echo something in your controller and then make your Javascript comparison based on that value.

MVC3 ajax action request: handling answer

I'm doing an Ajax request to an MVC3 action and I want to process the JsonResult in the success or error function.
Currently the behaviour is strange: Before hitting my breakpoint in the action it hits the error function.
Can anyone help me please and has a hint?
My view:
<form id="myForm">
//fields go here...
<button id="myButton" onclick="myFunction();">ButtonName</button>
</form>
The ajax call:
function myFunction() {
if ($('#myForm').valid() == false) {
return;
}
var data = {
val1: $("#val1").val(),
val2: $("#val2").val()
};
var url = "/Controller/Action";
$.ajax({
url: url,
type: 'POST',
dataType: 'json',
cache: false,
data: data,
success: function (data, statusCode, xhr) {
alert('1');
if (data && data.Message) {
alert(data.Message);
alert('2');
}
alert('3');
},
error: function (xhr, errorType, exception) {
alert('4');
var errorMessage = exception || xhr.statusText;
alert("There was an error: " + errorMessage);
}
});
return false;
}
My action:
[HttpPost]
public ActionResult Action(Class objectName)
{
var response = new AjaxResponseViewModel();
try
{
var success = DoSomething(objectName);
if (success)
{
response.Success = true;
response.Message = "Successful!";
}
else
{
response.Message = "Error!";
}
}
catch (Exception exception)
{
response.Success = false;
response.Message = exception.Message;
}
return Json(response);
}
If you look in the ajax call I get directly the alert #4 and only then the action gets called which is too late. Unfortunately the exception is null. Directly after that the view gets closed.
You are not preventing the default onclick behavior. Can you try the following instead?
onclick="return myFunction()"

Unauthorized AJAX request succeeds

I have following controller method:
[HttpPost]
[Authorize(Roles="some_role_actual_user_is_NOT_in")
public ActionResult AJAXMethod()
{
return Json(new { message = "server message");
}
and page with script:
function sendReq()
{
$.ajax({
type: "POST",
data: { somedata: "somedata" },
url: "/Path/To/AJAXMethod",
success: onAJAXSuccess,
error: onAJAXError
});
}
function onAJAXSuccess(response, status, xhr)
{
alert("success: " + response.message);
alert(status);
}
function onAJAXError(xhr,status,error)
{
alert("error: " + status);
alert(error);
}
When I call sendReq with user not in the authorized role the AJAX call still suceed - callback onAJAXSuccess is called, but response.message is undefined.
This is correct behaviour. The success of an AJAX call is only determined by the fact the the server responded with a 200 OK. You will need to interrogate the returned response yourself to ensure it is in the format you expect.
For example:
if (typeof response.message != "undefined" && response.message != "") {
// it worked
}
else {
// didn't work || user did not have access.
}

optional $.ajax call

I have html.actionlink in my asp.net MVC 3view and jquery ajax call on link click. In my action method suppose I have this:
if (a == 2) //return ok
return Json(new { Error = "false", Message = "Everything ok" }, JsonRequestBehavior.AllowGet);
else
return Content("");
Ajax call is:
$(function () {
$('#checkExists').click(function () {
$.ajax({
url: $('#checkExists').attr('href'),
global: true,
type: 'GET',
timeout: 5000,
success: function (data) { //invoke when receive response from server
if (data != null && data.Error != '') //return failed
{
alert(data.Error);
}
// else {
// alert('error occurs 1');
// //action ok here
// }
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr + ajaxOptions + "Cannot connect to server to load data"); //sever is not available
},
complete: function () { //ajax done
//alert('complete');
}
});
return false;
});
In case of else , ajax i called, how can I stop $.ajax call ?
you have already made the ajax call there is no way you can undo it in your current scenario
what you can do is send a doNothing response
if (a == 2) //return ok
return Json(new { Error = "false", Message = "Everything ok" }, JsonRequestBehavior.AllowGet);
else
return Json(new { Message = "do nothing" }, JsonRequestBehavior.AllowGet);
and in the ajax success callback
success:function(data){
if(data.Message==='do nothing'){
// simply do nothing
}
}
jsut as a side note you can cancel the ajax call before you have instantiated it see this SO answer Abort Ajax requests using jQuery
update
if (a == 2) //return ok
return Json(new { Error = "false", Message = "Everything ok" }, JsonRequestBehavior.AllowGet);
else
return Content("");
and in the success callback
success:function(data){
if(!data.Message)
//alert(data); //content will be shown
}
What do you mean by stop the AJAX call? You already sent the AJAX call and it hit the controller action. It is this controller action that returned a JSON or a plain text. But at this stage it is too late to stop something that was already done. It's ike trying to bring someone back from death.

Resources