Failure to trigger AJAX Success or Error Events

I'm struggling to understand why this code isn't working or find any relevant resources. When I check the json object in Firebug, it either returns success: false or success: true from the post request, so I'm confused as to why the function isn't triggering.

AJAX

$("#login").submit(function (e) {
    e.preventDefault();

    $.ajax({
        url: "../process/login-process.php",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: { 'username': $('[name=username]').val(), 'password': $('[name=password]').val() },
        beforeSend : function (){
            //$("#login").hide();       
        },
        success: function(data){
            window.localation=data.redirect;            
        },
        error: function(data) {
            $(".error").html('');
            alert('wtf');
            if(data.empty) {
                $(".error").html(data.empty);
            }
            if(data.incorrect) {
                $(".error").html(data.incorrect);
            }       
        }
    });
});

PHP

<?php 
    session_start();
    include "../inc/connect.php";
    $username = mysqli_real_escape_string($con, $_POST['username']); 
    $password = mysqli_real_escape_string($con, $_POST['password']); 
    $password = hash('sha256', $password); 
    $sql = "SELECT * FROM admin WHERE username ='$username' AND password ='$password'";
    $result = mysqli_query($con, $sql) or die(mysqli_error($con));
    $row = mysqli_fetch_array($result);
    $count=mysqli_num_rows($result); 
    if ($username == "" || $password == "") {
        $data['empty'] = 'All fields are required.';
    } else if(($count==1) && ($username)) {
        $_SESSION['user'] = $row['firstName']; 
        $_SESSION['userID'] = $row['adminID'];
        $data['success'] = true;
        $data['redirect'] = '../pages/dashboard.php';
     } else { 
        $data['success'] = false;
        $data['incorrect'] = "Incorrect Username or Password.";
     } 
    echo json_encode($data);
?> 

Answer №1

Here are two corrections you need to make in your code:

  1. Change window.localation to window.location in the success callback.
  2. Add dataType: 'JSON' in the ajax request or use $.parseJSON in the success callback.

Therefore, your success callback should look like this:

success: function(data){
            data = $.parseJSON(data); // <- Only if you don't include dataType: 'JSON' in ajax
            window.location=data.redirect;        //<- Location spelling corrected   
        }

Answer №2

When you send a string (in this case, a JSON) without specifying any header, the response will always be 200 OK.

Therefore, an error will never be triggered.

success: function(data){
        window.localation=data.redirect;   <----- error here. location         
    },

This is why nothing seems to be happening.

To trigger an error if the data is incorrect:

Instead of:

} else { 
    $data['success'] = false;
    $data['incorrect'] = "Incorrect Username or Password.";
 } 

Use:

} else { 
    header('HTTP/1.0 403 Forbidden');
    echo 'Incorrect Username or Password.';
    exit;
 } 

This will display a 403 Forbidden message.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Assistance with JavaScript Regular Expressions for formatting BBCode

A few weeks ago, I stumbled upon this regex expression: /([\r\n])|(?:\[([a-z\*]{1,16})(?:=([^\x00-\x1F"'\(\)<>\[\]]{1,256}))?\])|(?:\[\/([a-z]{1,16})\])/ig It's designe ...

What causes a React Ref callback to be invoked multiple times during the initial loading of a page?

To find more information, please visit this URL within the React DOCS. You can also access a version of this code here. I acknowledge that it is recommended to use the useCallback hook in a Functional React Component to create a ref callback according to ...

Guide: Implementing material-ui theme with redux in gatsby

I'm currently utilizing the material-ui theme in conjunction with redux-toolkit within a gatsby project. This is my theme.ts file: import { createMuiTheme } from "@material-ui/core"; import { useSelector } from "react-redux"; import { State } from ". ...

HTML stubbornly resists incorporating Javascript [UIWebView]

Currently, I am facing an issue while trying to animate a color property using jQuery 1.7.1 and the jquery color plugin downloaded from this link. I have ensured that all necessary files are included and part of the build target. Here is a simplified versi ...

The model in Phalcon is encountering an issue with saving due to an invalid datetime value of '1540564519' in the 'date_updated' column of row 1

I am encountering an issue while attempting to store data in a table. The error message that is being thrown upon saving is as follows: SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect datetime value: '1540564519' for column 'da ...

What steps should I follow to have my edit form component extract values from HTML in Angular?

I created a detailed listing page that includes a picture URL, title, phone number, description, and price. When the user clicks on the Edit button, it redirects them to a page with input forms for each of these fields. The form automatically populates the ...

The reset function for the selector is failing to properly reset the data within the table

I need help with a selector that has multiple options and a reset button. When the reset button is clicked, it should reset the selector back to the first option. Although the selector resets as expected when the button is clicked, the data in the table r ...

Seeking assistance with implementing Styles using the .css() function in Jquery. Any guidance is appreciated

This particular style is exactly what I am looking for. body{ background: url("img/Background_Home.jpg") no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; ...

Unable to receive a response in React-Native after sending a post request

My current challenge involves sending a response back after successfully making a post request in react-native. Unfortunately, the response is not arriving as expected. router.route("/addUser").post((req, res) => { let name= req.body.name; connection ...

Strategies for managing multiple openIDs linked to a single user account

Currently, I am implementing a login system on my website similar to the one used on SO. Users have the option to log in with their Facebook, Google (Gmail openID), or Twitter accounts. This inquiry does not focus on specific oAuth or OpenID implementatio ...

Modifying button attribute through dropdown selection

In my project, I have a dropdown that gets its data from a database. Depending on the selection made in the dropdown, I would like to change the attribute of a button (data-uk-modal="{target:'#modal-'value of dropdown'}"). <select id "ci ...

The JQuery mobile navigation menu effortlessly appears on your screen

I am experiencing an issue with a JQuery mobile navigation that is designed for screens @979 pixels wide. The problem arises when the screen is resized to 979px - the menu pops up fully extended and covers the content of the web page. I suspect that this ...

Strategies for avoiding a hover component from causing distortion to its parent component in React

I am encountering an issue with a hover component that is causing distortion in its parent component when displayed. Essentially, I need to prevent the hover component from affecting the layout of its container. Below is the code snippet: Styling for Lang ...

Employing DOM manipulation within Vue unit tests as a last resort

What steps should I take to update my unit test in order to accurately validate the following scenario? Method: close(event) { const element = !!event?.target?.closest('#target') if (!element) { this.isVisible = false } }, Jest test: ...

delete specific elements from an associative array

I am working with two arrays: $pool = array( 'foo' => array('foobar1'), 'bar' => array('foobar2'), 'lou' => array('foobar3'), 'zuu' => array('foobar ...

Tips for selecting multiple potions from a JSON file in a React Native project

I need help with highlighting multiple options from an array in React Native. Currently, when I click on an option, it highlights that option but de-highlights the previous one. How can I modify my code to allow for selecting and highlighting multiple opti ...

Angular JS encountered an issue with executing 'removeChild' on 'Node' for HTMLScriptElement.callback, leading to an uncaught DOMException

I am currently using Angular's JSON HTTP call. When making a post request, I experience an error during runtime: Uncaught TypeError: Cannot read property 'parentElement' of undefined at checklistFunc (masterlowerlibs.67785a6….js:42972 ...

Setting up the current user's location when loading a map with Angular-google-maps

I am currently utilizing the library in conjunction with the IONIC framework. To manually set the center of the map, I have implemented the following code snippet: .controller('mainCtrl', function($scope) { $scope.map = { cen ...

How come my CodeIgniter emails are consistently ending up in the spam folder despite being properly configured?

Hey there! I've been working with CodeIgniter and PHP to send emails from my application, but unfortunately they keep ending up in the spam folder of the recipients. $this->load->library('email'); $config['protocol'] = &apo ...

Having trouble with a JavaScript function as a novice coder

Hello, I'm still getting the hang of JavaScript - just a few days into learning it. I can't figure out why this function I'm calling isn't functioning as expected. Here's the content of my HTML page: <!doctype html> <htm ...