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

Issue with Yeoman webapp generator and Gulp, encountering error when using Gulp-jade package

I'm encountering some difficulties integrating jade with yeoman's gulp webapp generator. The watch task is functioning properly, but when I attempt to build the project, I encounter the following error: stream.js:94 throw er; // Unhandled ...

Using Next-Image Relative Paths can lead to 404 errors when being indexed by web crawlers

I have implemented next-image in my project, and all the images are hosted on Cloudinary. The images display correctly, but when I run a website analysis using tools like Screaming Frog, I receive numerous 404 errors. This is because the tools are looking ...

Get tabular information in xlsx format by utilizing the xlsx npm package for download

I have been attempting to convert my json-like data into an xlsx file format. I utilized the xlsx npm package and followed various code samples available online, however, when trying to open the file in Excel, I encountered the following error: https://i.s ...

Displaying a DIV inside an embedded DIV when selecting an option in HTML by utilizing JavaScript

My goal is to create a page where users initiate a questionnaire by clicking START in a web form - this action will open the DIV for the first question. As users answer each question (with yes/no choices), it will either display a specific DIV related to ...

Anticipate the arrival of the getJSON response

Currently, I am working on a script that utilizes Yahoo's YQL within a web application. This script is designed to scan through a text paragraph, identify references, and display them as popups within the text. Everything works smoothly until I reach ...

Currently operating a PHPWebSocket server by executing the command `.php`

Exploring phpwebsocket has been an interesting experience for me. I found the code on http://code.google.com/p/phpwebsocket/. The way it works is that I need to run the server.php using command line in order to start the socket listening on a specific port ...

Offering fields for modules, main, and browser that meet the needs of ESM, CommonJS, and bundlers

I have upgraded a number of my published npm packages to include both commonjs and esm builds. Some of these packages are meant for use in both node and the browser, and they are all compiled using webpack or rollup. Additionally, all of them are written i ...

What is the best way to send a POST request to my Rails controller using Ajax?

I'm facing an issue trying to transmit data from my JavaScript game-state on the front end to my controller and ultimately store it in the database. Unfortunately, I haven't received any response so far, and I'm struggling to pinpoint the re ...

Dynamic Selection List Population in jqGrid

Using jqGrid 4.13.3 - free jqGrid In the Add form, there is a static input element and a select list element. The keyup ajax function is bound to the input element using dataEvents in the beforeInitData event. Once the Add form is displayed, entering a va ...

What methods can I employ to utilize the name attribute for POST requests instead of the ID attribute in TinyMCE?

My inline TinyMCE form sends content to qry.php with the key "edit_me". I prefer the default behavior of sending content using the name attribute instead. <script type="text/javascript"> tinymce.init({ selector: '#edit_me', ...

Adding an element to a jsonb array in PostgreSQL, but ensuring it is unique

For my PostgreSQL (v10.0) database setup, I followed these steps. CREATE TABLE test (id INT, animals jsonb) INSERT INTO test VALUES (1, '["[monkeys, 10]", "[hamsters, 7]", "[foxes, 3]"]'), (2, '["[monkeys, 10]", "[hamsters, 7]", "[fo ...

Angular 6 seems to be having issues loading Bootstrap

I've run into an issue while trying to incorporate Bootstrap into Angular 6. I have already installed Bootstrap using npm install bootstrap and added it to angular.json, but it's still not functioning. Is there something else I should be doing? A ...

Using jQuery to alter an href link's attribute

I am currently attempting to modify the content of a href using jQuery. After researching various solutions on this platform, I came across one that I am trying to use for implementation: How to change the href for a hyperlink using jQuery My current app ...

What is the best way to display a success message after saving in Laravel 5.1?

When working with Laravel 5.1, I successfully save data in the database. However, I am now looking to display a success message. How can I achieve this? Below is the code snippet from my Controller's save method: public function store(Request $reques ...

Are you interested in using jQuery and/or AJAX to retrieve the latest images from a website?

I had to utilize a Wikipedia API in order to retrieve images from the New Jersey website, and I devised two methods to carry out similar tasks. The initial approach involved using JSON, but it ended up pulling the entire page content. <script type="tex ...

Remove duplicate values from a specific key in an associative array of arrays using PHP

I have an array of associative arrays array(xxx) { [0]=> array(3) { ["group_id"]=>2 ["contact"]=> "foo" ["contact_email"]=> "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="22444d4d62454f434b4e0c414d ...

Using Axios with Mongoose to Update Documents in Not Working State

I'm currently working on implementing an edit feature for updating posts. My goal is to initially update a specific post by its ID and then make it more dynamic. Although I am able to successfully send a PUT request using axios, I'm not getting ...

Struggling to understand the concept of utilizing Promises for data retrieval

I'm currently facing an issue with my async function that awaits a GraphQL call. Even though the call returns a Promise containing the desired data, I'm struggling to access it effectively. Below is the snippet of code in question: export async ...

What situations warrant the use of unescaped !{} in pug for string interpolation?

Is there a practical application for utilizing !{} - string interpolation in an unescaped format, despite the potential risks associated with its use? I have reviewed the information provided at these sources: Using !{ } and #{ } interpolation in a jade ...

Utilize AJAX, jQuery, and Symfony2 to showcase array information in a visually appealing table format

I have a requirement to showcase data utilizing ajax and jQuery in a table on my twig file. The ajax call is made with a post request to the controller, where the controller attempts to input several rows from a csv file into the database. However, there ...