Unusual issue with jQuery's AJAX functionality

Utilizing jQuery AJAX, I am fetching data from a PHP page and displaying a loading GIF image in the placeholder to indicate that results are being processed.

$(".project").change(function(){
            $(".custName").html("<img src='/admin/images/ajax-loader.gif' />");
            $(".projectDesc").html("<img src='/admin/images/ajax-loader.gif' />");
            var project_num=$(this).val();
            var dataString = 'project='+ project_num;

                $.ajax
                    ({
                        type: "POST",
                        url: "customerfilter.php",
                        dataType: "json",
                        data: dataString,
                        cache: false,
                        success: function(data)
                        {
                            $(".custName").html(data.message1);
                            $(".projectDesc").html(data.message2);
                        }
                    });


        });

After clicking the trigger and checking the Firebug console, I can see the POST request being sent and received with correct data. However, the loading gif remains visible and is not replaced by the actual data - unable to determine the reason behind this issue!

Here is a screenshot from Firebug showing the RESPONSE window:

PHP code handling the response:

while ($row = mysql_fetch_array($result)) {
                echo json_encode(array(
                    "message1" => $row['cust_name'],
                    "message2" => $row['description'],
                ));

$result corresponds to a mysql_query

Answer ā„–1

The data you received is not in valid JSON format. You can fix this by using the following code:


$output = [];
while ($row = mysqli_fetch_array($result)) {
                $output[] = [
                    "name" => $row['customer_name'],
                    "description" => $row['product_description'],
                ];
}
echo json_encode($output);

UPDATE: Don't forget to update your 'success' callback function in JavaScript as well:


success: function(response) {
  $(".customerName, .description").empty();
  for(var x in response) {
     $(".customerName").append(response[x].name);
     $(".description").append(response[x].description);
  }
}

Answer ā„–2

Encountering similar issues arises when the data type is set to JSON. If PHP does not return accurate JSON, jQuery will not execute the success function.

Follow these steps:

  1. Add a

    console.log("success was called")
    statement inside the success method to track its execution.

  2. Validate that your PHP code generates valid JSON using the json_encode function.

  3. Share any new details you have for further assistance in debugging :-)

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

NodeJs took an unexpected turn

Iā€™m encountering an issue with an http request to forecast.io. When I make a normal request using $.ajax, everything works fine. However, when I try using the ajax-request module, I receive the following output: SyntaxError: Unexpected token u in JSON at ...

Using jQuery to automatically select a specific radio button after the load() function is executed

I'm trying to dynamically load radio buttons into a div using the JQuery load() function. However, I'm facing an issue when it comes to checking a specific radio button by its value. The problem is that the code doesn't seem to be working w ...

Implementing CSS styles to Iframe content

I have written the following code snippet to display an iframe: <iframe scrolling='no' frameborder='1' id='fblike' src='http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fwww.XYZ.com%2F&amp;send=false& ...

Comparing two tables in jQuery/Javascript for matching data

I want to check for matches between the rows of two HTML tables, where the data in the first cell can be duplicated but the data in the second cell is always unique. The goal is to determine if the combination of values in the first and second cells of tab ...

Stopping jQuery fadeOut from setting the display property to 'hidden'

I am currently working on a project that involves creating a lightbox effect. I am using jQuery's fadeIn and fadeOut functions to display enlarged div elements. However, I have encountered an issue - when I use fadeOut on the enlarged div, the smaller ...

Saving information from MySQL database into a CSV file using PDO through a web browser

I'm struggling with a form that writes data to a MySQL database. My goal is to allow users to download their submitted data in CSV format once they complete the form. Currently, my code is displaying the database contents on the browser instead of ge ...

The BBCode seems to be malfunctioning

I created a custom BBCode for my PHP website to display tabbed content on a page. After testing the BBCode on a separate webpage and confirming there are no errors, I am facing an issue where the tabbed content is not showing up on the actual posting page. ...

Step-by-Step Guide: Crafting a Non-Ajax Popup Chat Application

Recently, I created a unique dating website with a one-to-one chat feature similar to Facebook. However, I implemented this using the ajax technique and the setInterval function in JavaScript for regular updates. Upon reflection, I believe that this appr ...

Is there a way to update page content without having to refresh the entire page?

My goal is to refresh specific content on a page without having to reload the entire page using JavaScript or jQuery. Since my project is built in PHP and JavaScript, I encountered this issue. Note : I want the page content to refresh when a user performs ...

Modify the error message in jQuery validation when the dropdown selection changes

I'm a beginner in jquery and I'm using the validation plugin from . It has been working well for me so far, but I encountered an issue on a specific page where I need to change the error message when a dropdown is changed, rather than when the su ...

What could be causing the console to display undefined?

Can anyone help me with an issue I'm having while making an AJAX call using fetch and promises? I have successfully displayed the temperatures, but for some reason, the location is showing up as undefined. Here is the code snippet: function getWeat ...

In order for Jquery's html() and dialog functionalities to work seamlessly, the inclusion of an alert box is imperative

I've encountered a strange issue that I can't explain. For some reason, the code below only works correctly (fetching the HTML from the Action in the controller) if an alert box is displayed before the dialog opens. var ticks; function In ...

Form containing unchecked checkbox

I am trying to send a false value via post for a checkbox that is not checked by default. Here is how my checkbox is defined: <label><input type="checkbox" id="rez" name="rezerwowanie" value="false" />Rezerwowanie</label> After submitti ...

Array offset is undefined even though it exists in the array

In my code, I am creating a MySQL connection array and passing it to a connect method like this: $database->connect(array(ROOT_DB_HOST, ROOT_DB_NAME, ROOT_DB_USERNAME, ROOT_DB_PASSWORD)); After using print_r() on the array inside the connect method, I ...

Django: Utilizing AJAX to send a POST request for a form submission and updating the

Do you need assistance with creating a status view for your form? The current setup involves taking user input, submitting to a view where calculations are processed, and then redirecting to the output. However, the user must wait with no indication of pro ...

What is the best way to incorporate arrow buttons on my website in order to unveil various sections on the homepage?

A colleague and I are collaborating on a website for his cookery business. He has sketched out some design ideas on paper, one of which involves having a homepage with 4 different sections stacked on top of each other. Each section would have an arrow butt ...

What is the best way to incorporate an if else condition using the <?php if($loggedin): ?> statement within JavaScript code to display a button push or pop response from the server side?

I would like to verify this php if condition code ''<?php if($loggedin) : ?>'' inside JavaScript code in order to display one of the buttons, either push or pop. I want to keep this button hidden from the client side by embedding ...

What is causing the inability to update fields in Laravel?

I am facing an issue with updating fields in a table for my project. I have tried using both PUT and PATCH methods, but they are not working. I even removed the foreign key and repeated the check, but the problem still persists. I used Laravel debugger and ...

Using jQuery to incorporate a variable into JSON schema markup

For my current project, I am attempting to extract the meta description and incorporate it into JSON schema markup. However, I am facing difficulty in passing the variable properly into the JSON structure. My initial approach was as follows: <script&g ...

What is preventing me from accessing the JSON return values in my .NET MVC project?

I've been stuck on this seemingly minor issue for hours now. Every time I look at the console, it's showing 500 errors and nothing is coming up in alerts. It appears that the Json() function isn't working as expected. I even tried setting a ...