Unresponsive AJAX calls in jQuery causing div elements to not display properly

I have created a simple form that dynamically retrieves data and sends it to another page. I want certain divs to be displayed on my page based on the retrieved data. The divs are being displayed successfully when checking without AJAX, but when AJAX is implemented, it's not working. Any suggestions?

AJAX

$("document").ready(function() {
    $("#search_keyword").on("submit", function (e) {
        e.preventDefault();
        $.post("keyword_search.php?query="+encodeURIComponent($("#keyword").val())+"category="+encodeURIComponent($("#category").val())+"store="+encodeURIComponent($("#store").val()), function (data) {
            var res = JSON.parse(data);
            if (res.divs) {
                $('#search_result').html("");
                for (var i = 0; i < res.divs.length; i++) {
                    $('#search_result').append(res.divs[i]);
                }
            } else {
                $('#search_result').html("No matched coupons found !");
            }
        });
    });
});

Form

<form class="form-horizontal select-search" id="search_keyword" method="post">
    <label class="control-label ">Keyword</label>
    <input class="form-control" id="keyword" name="keyword" type="text">
    <!-- Select Category -->
        <label class="control-label " for="category">Select category</label>
        <select class="category" id="category" name="category">
            <?php 
                $sm=mysqli_query($con,"select * from categories ");
                while ($row1 = mysqli_fetch_array($sm,MYSQLI_ASSOC)){
                    $cat_id = $row1['cat_id'];
                    $name = $row1['cat_name'];
                    echo '<option value="' . $cat_id . '">' . $name . '</option>';
                }  
            ?>
        </select>

    <label class="control-label " for="store">Select a store</label>
    <select class="storesname" id="store" name="store">
      <option selected="selected">Select Stores</option>
   </select>
   <button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>
</form>

<div id="search_result"> </div>

Answer №1

Ensure that your button can actually submit by changing the type from button to submit.

Here is how you should change it:

<button id="search_btn" name="search_btn" class="btn btn-danger">Search coupons</button>

To this:

<input type="submit" id="search_btn" name="search_btn" class="btn btn-danger" value="Search coupons"/>

Note: Make sure to include the jQuery library before your script code for it to work.

Update your code as shown below:

$("document").ready(function() {
    $("#search_keyword").on("submit", function (e) {
        e.preventDefault();
        var data = {'query':encodeURIComponent($("#keyword").val()),'category':encodeURIComponent($("#category").val()),'store':encodeURIComponent($("#store").val())};
        $.post("keyword_search.php",data, function (data) {
            var res = JSON.parse(data);
            if (res.divs) {
                $('#search_result').html("");
                for (var i = 0; i < res.divs.length; i++) {
                    $('#search_result').append(res.divs[i]);
                }
            } else {
                $('#search_result').html("No matched coupons found !");
            }
        });
    });
});

In your keyword_search.php, check like this:

<?php
echo "<pre/>";print_r($_POST); //check how post data are coming
// adjust code accordingly
?>

Also remove method="post" from your current <form>

Answer №2

If you want to make a change in jQuery, try this:

I made a simple modification by replacing "submit" with "click" and "#search_keyword" with "#search_btn"

$("document").ready(function() {
  $("#search_btn").on("click", function (e) {
  e.preventDefault();
  $.post("keyword_search.php?query=" + encodeURIComponent($("#keyword").val())+encodeURIComponent($("#category").val())+encodeURIComponent($("#store").val()), function (data) {
   var res = JSON.parse(data);
   if (res.divs) {
   $('#search_result').html("");
    for (var i = 0; i < res.divs.length; i++) {
     $('#search_result').append(res.divs[i]);
      }
     } else {
      $('#search_result').html("No matched coupons found !");
    }
            });
        });
    });

Give it a try and see if it improves things!

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

Request Denied: Ajax communication to external origin blocked

Hello everyone, I am currently attempting to send data via ajax to my API website in order to insert it into my database. However, I am encountering an error that reads: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote re ...

How can I add multiple filters to a Kendo Grid?

Is there a way to include two separate filter fields for date filtering in Kendo Grid UI? Currently, the method I am using only allows for one date filter to be displayed. filterable: { ui: function (element: any) { element.ken ...

I am having trouble with my Vue nested For loop as it is only returning the first value of the second array. What could be

I am currently utilizing a nested For loop to retrieve data from JSON and then returning a variable for Vue frontend access. Oddly enough, I am only able to retrieve values from the initial element of the nested array. Can anyone assist with this issue? It ...

Table with expanded width, cut off cell content

As I work on building an HTML table, I've encountered a challenge. The table code looks like this: This is the structure of my table: <table class="table" style="font-size:22px; width:100%"> I want to ensure that everything fits within the pa ...

Encountering issue with passing ID to Controller via Ajax in Laravel - Error 404 Unresolved

I'm just starting out with Laravel and I'm encountering an error when trying to pass the ID from the view to the controller. POST 404 (Not Found) This is how my View BuffaloMonitor looks like: $(document).on('click', '.viewmoni ...

Implementing logic with multiple columns in JavaScript

Looking for a way to display an array of data in multiple columns using Java Script, like this: 1 2 3 4 5 6 7 8 9 instead of 1 4 7 2 5 8 3 6 9 Any suggestions would be greatly appreciated. Thank you. ...

Is there a native horizontal divider available in Bootstrap 4?

Is there a predefined horizontal divider in Bootstrap 4? I currently have this: <style type="text/css> .h-divider{ margin-top:5px; margin-bottom:5px; height:1px; width:100%; border-top:1px solid gray; } </style> However, I would prefer t ...

Unable to send event from JavaScript to Component in Ionic

My goal is to notify a component that a script file has finished loading. My approach involves using the onload event of an element to dispatch an event. A service will then register an event listener for this event, waiting for clients to subscribe to an ...

The style was not applied as the MIME type ('text/html') is not a compatible stylesheet MIME type

Currently, I am in the process of creating a todo-list application. However, I have encountered an issue where the stylesheet is not being applied when accessing localhost:3000/lists/customList. Instead, I am receiving the following error message: "Refused ...

Styling a <slot> within a child component in Vue.js 3.x: Tips and tricks

I'm currently working on customizing the appearance of a p tag that is placed inside a child component using the slot. Parent Component Code: <template> <BasicButton content="Test 1234" @click="SendMessage('test') ...

The CSS code conceals the icon within the background

Could someone please help me out? I am new to this and can't seem to figure out what's wrong. The phone icon seems to be hidden behind a white background. Everything else looks fine, but I really want the icon to be in the front with a border and ...

Utilizing the hover() function in jQuery to emphasize a button along with jQuery to trigger a button click

I added a button to my webpage that reveals a hidden menu when clicked. However, I wanted the button to have a hover effect in which it would highlight when the mouse hovers over it. To achieve this, I decided to use JQuery's hover() and click() metho ...

Guide to creating a sidebar within a single column

I am trying to create a responsive column on the left side of the screen with a specific width and height. In this column, I want to include the user's picture on the top and their name and position right below the picture. Under this information, I p ...

"Troubleshooting issue: Module fails to reload following JSON.parse error

For QA testing purposes, we have a test page that allows our QA team to replicate server behavior by passing JSON to a mock service. Everything functions correctly when valid JSON is used, but if invalid JSON is provided, an error is returned - which is ex ...

Trouble getting proper alignment displayed with JavaScript and CSS

If anyone has a solution for printing content in a div using JavaScript and CSS, please help. The main div with the id 'preview' contains content taken from a database using PHP and MySQL. However, the data on the print page appears vertically an ...

Experiencing an unexpected wait before the requestAnimationFrame?

Surprisingly, Internet Explorer is actually performing the way I want it to in this case :-) I developed a function for SVG animations using requestAnimationFrame (for simplicity, I left out the value calculations here ... but my initial test involved an ...

What is the best way to output the leaf nodes from an array of object lists in TypeScript?

Having trouble with TypeScript, specifically working with arrays and filtering out leaf nodes. I want to print only the leaf nodes in the array, resulting in ['002', '004', '007']. Can someone please assist me? Excited to lear ...

Transmit information and control instructions to an executing Puppeteer script

I'm a beginner when it comes to using Puppeteer and I've encountered a few issues while working with it. My main goal is to have the script respond to user input, such as changing pages or displaying element contents while it's running. The ...

Effective ways to transfer data between services and controllers

Is there a way to pass values from services to controllers effectively? Despite researching on stackoverflow, I haven't found a solution that addresses my issue. My goal is to access google spreadsheets using tabletop.js. Interestingly, when I log val ...

What is the reason behind flex causing the hr element to have a width of 0?

Whenever I attempt to place an hr element inside a container that has display: flex, it mysteriously disappears. (Removing display: flex makes it reappear, leading me to believe that this is indeed the cause.) I stumbled upon a blog post that suggested fl ...