When PHP echo of json_encode triggers an error, AJAX status 200 will be raised

Despite everything running smoothly in the program below, an AJAX error is triggered:

javascript:

var data = {
    email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="026f6742656f636b6e2c616d6f">[email protected]</a>',
    password: 'secretword'
};

$.ajax({
    type: "POST",
    dataType: "application/json",
    url: "http://localhost/CFBserver/validateUser.php",
    data: data,
    success: function (response) {
        console.log(response.responseText);
    },
    error: function (response) {
        console.log(response.responseText);
    }
});

}

php:

    <?php

    $conn = mysqli_connect('localhost', 'root', '', 'cfbdata');
    if (mysqli_connect_errno($conn)) {
        echo "Failed to connect to MySQL: " . mysqli_connect_error();
    }
    $email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
    $password = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);

    $sql = "SELECT * FROM users WHERE email = '$email' AND password = '$password'";

    if (!mysqli_query($conn, $sql)) {
        die('Error: ' . mysqli_error($conn));
    }

    $result = mysqli_query($conn, $sql);
    $numrows = mysqli_num_rows($result);
    if ($numrows > 0) {
        $message = array('result' => 'found',
            'email' => $email,
            'password' => $password,
        );
    } else {
        $message = array('result' => 'Not found',
            'email' => $email,
            'password' => $password,
        );
    }
    header('Content-type: application/json');
    echo json_encode($message);

    mysqli_close($conn);
    ?>

The console output shows:

<html>
    <head>
        <meta charset="UTF-8">
        <title></title>
    </head>
    <body>
        {"result":"found","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dcb1b99cbbb1bdb5b0f2bfb3b1">[email protected]</a>","password":"secretword"}
    </body>
</html>

Although PHP successfully retrieves the record from the MySQL database, it triggers an error upon returning to AJAX. Any ideas why?

Answer №1

When your AJAX request is expecting a JSON response but receives HTML instead, it causes issues with your JavaScript functionality. This is why the status code returned is 200 (OK), but your JS does not work properly.

If you are using PHP's json_encode, it should not be adding HTML on its own. It is possible that you are outputting to a template or have wrapped your PHP code in HTML tags.

In addition to this issue, there is also a vulnerability to SQL injection. Furthermore, it seems that both your AJAX error and success functions are performing the same action, so there may be uncertainty about error handling.

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

update-post-thumbnail wp-ajax return false

I have been attempting to utilize the media manager within Wordpress. I am using the post editor outside of the admin area, allowing users to create posts with a featured image. I have used the _wp_post_thumbnail_html function to display the image or provi ...

What is the process for determining the default character length in a <p> tag based on its height and width?

I'm trying to determine the default length for the <p> tag in HTML. It should be displayed based on the height and width of the <p> tag. For example: Consider the following code snippet, <p style="height:300px;width:200px;"> </ ...

Utilizing various Firestore requests at varying intervals using the useEffect hook in React

useEffect(async() => { await getWord(); const interval = setInterval(() =>{ time2 = time2 - 1; if (time2 == 0) { clearInterval(interval); let dataURL = canvasRef.current.toDataURL(); const db = firebase.firestore(); ...

Creating Vue.js components dynamically

Is it possible to programmatically insert a modal component in Vue? For instance: Vue.component('modal', {...}) Then, in any component, is there a way to do something like this: Vue.component('login', { methods: { openLoginM ...

Inject nested controller dynamically

I am working on a straightforward ASP.NET MVC application that includes an ng-controller. I am trying to inject another ng-controller inside this controller using a partial view, but I'm having trouble getting the binding to work correctly. You can s ...

The Ajax load() function is malfunctioning

.load() will only function properly when the files are coming from a server, so I anticipate that it will work later once I have it hosted on a server Edit: This code is functional in Firefox but not in Chrome I've been attempting to apply ajax to l ...

Utilize the preg_match_all function to analyze the URL of a form post submission

When utilizing preg_match_all to extract data from URL's using the GET method, how can I obtain data using the POST method instead? My specific scenario involves retrieving PNR details from (which posts data via a form) and gathering all necessary in ...

Trouble with AJAX call to web service function

i'm facing an issue with my ajax call function findPICKey() { filter = document.getElementById('MainCT_dtvJobVac_PIC').value; $.ajax({ type: 'POST', contentType: 'application/json;&a ...

Import the JSON data into the designated storage unit

$(".btn-primary").click(function(){ runSuccessFunction(jsonObj); }); If I need to update the JSON data in the JSFiddle Code example, how can I reload only the container by clicking a button? I want to run the code every time I make a change to the J ...

SelectOneMenu Ajax Update lags behind by a single step

I am currently experiencing an issue with updating Ajax. When using a SelectOneMenu component to select a sorting option, the ajax call is consistently made with the last selected option instead of the current one. Below is the code snippet I am using, w ...

Utilizing Laravel's Array and JSON casting feature for seamless integration with Algolia

I am encountering an issue while attempting to send data to Algolia using the toSearchableArray method. The strings from my database are transferring correctly, but I'm facing a challenge with nested JSON data—it's being sent as an escaped stri ...

Tampermonkey only allows jQuery Click to execute once within a for loop

Attempting to switch the content of a text area to different cars and then trigger a button click to perform an action, repeating this process for each car until all cars have been processed. var index; var cars = ["car1", "car2", "car3"]; var x = documen ...

Enhanced approach to building with React and Express

Quick Summary: How can I set up a project using React on the front-end and Express on the back-end with just one package.json and node_modules folder? When starting a project that combines a React front-end and an Express back-end, my desired structure is ...

"Invalid: string path required" (version 5.10.0)

There's this file (a large bundle of a couple of JS files) that used to work perfectly with browserify (version 5.10.0) until just recently, but now it's not cooperating. Here's the command I'm using: $ browserify index.js -o dist/out ...

Randomly loading Json files in Ionic is a great way to keep your

I have a div using *ngFor which loads values from a JSON file. I want to load values from different JSON files randomly each time the div is loaded. Is there a way to achieve this using Math.random() or any other methods? html file <div class= ...

Tips for sending information from a controller to jQuery (Ajax) in CodeIgniter

Code snippet in controller: $rates['poor'] = 10; $rates['fair'] = 20; $this->load->view('search_result2', $rates); //Although I have attempted different ways, the only successful method is using the code above. Other ...

When working with Node.js, it is important to properly export your Oracle database connection to avoid encountering an error like "TypeError: Cannot read property 'execute

Hey there, I am a newbie when it comes to Node.js and Oracle. I've managed to create an app and establish a successful connection to the database. Now, I'm trying to figure out how to utilize the connection object throughout my application. Any s ...

Establish a predetermined selection for a drop-down menu

How can I set a default value for a dynamically filled dropdown menu featuring all 12 months in KnockoutJS? I want the default value to be the current month. This is how I am populating the dropdown with information: self.setMonthData = (data ...

Is there a way to retrieve MongoDB count results in Node.js using a callback function?

Is there a way to access mongodb count results in nodejs so that the outcome can be easily retrieved by asynchronous requests? Currently, I am able to retrieve the result and update the database successfully. However, when it comes to accessing the varia ...

Tips on how to retrieve the validation message for laravel-validation-rules/credit-card

Following the instructions here, I utilized the Laravel validator for credit card information. After some effort, I managed to get it working. However, my dilemma now is how can I present the validation messages in a user-friendly format. In my Laravel val ...