Repetitive retrieval of HTML file using Php and Ajax

I've been tackling notifications in PHP lately. Within the header file, I've included this function:

  $(document).ready(function() {      
      setInterval(getNotifys, 10000);      
      function getNotifys(){
            $.ajax ({                  
            method: "POST",
            url : 'get_notification.php',          
            success : function(data){
                console.log(data);            
                $('.notifications').html(data);                
            }
        });  
     }
 });    

Here's the content of get_notification.php:

<?php
include("global.php");
if($logged==0){
    header("location:".$baseurl."login.html");
    exit();
}
$data=mysqli_query($con,"select * from notifications where admin=1 and resolved=0") or die (mysqli_error());
$count = mysqli_num_rows($data);
?>
<span class="badge badge-danger" style="margin-bottom:25px"><?php echo $count; ?></span>

While it functions flawlessly on most pages, there are instances where instead of displaying the notification count on the icon, it renders the entire HTML page. Even when checking the console within the success function, the whole page's HTML is logged. I'm quite puzzled as to why this is happening. Any insights?

Answer №1

Implement JSON and generate the required span elements in your JavaScript code.

    <?php
include("global.php");
if(!$logged) {
    http_response_code(401); // handle this error through ajax
    exit();
}

$data = mysqli_query($con,"select * from notifications where admin=1 and resolved=0");

if(!$data) {
    http_response_code(500); // handle this error through ajax
    exit(); 
}

$count = mysqli_num_rows($data);

echo json_encode(['count' => $count]);

JS:

      $(document).ready(function() {      
      setInterval(getNotifys, 10000);      
      function getNotifys(){
            $.ajax ({                  
            method: "POST",
            url : 'get_notification.php',          
            success : function(data){
                let jsonData = JSON.parse(data);
                console.log(jsonData);
                $('#notifications_count').html(jsonData.count);                
            },
            error: function(jqXHR, textStatus, errorThrown) {
              console.log(textStatus, errorThrown);
            }
        });  
     }
 });

HTML:

<span class="badge badge-danger" style="margin-bottom:25px" id="notifications_count"></span>

This example demonstrates how you could implement it, although it has not been tested.

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

Error message: Unknown modifier encountered during date validation

I am currently using a specific string for validating dates in the formats 'dd/mm/yyyy' and 'dd-mm-yyyy': '/^(0?[1-9]|[12][0-9]|3[01])[\/\.- ](0?[1-9]|1[0-2])[\/\.- ](19|20)\d{2}$/' However, I encoun ...

Unable to Validate Ajax Form if Enclosed within <form> Elements

Could you please take a moment to review this link and help me understand why I am unable to validate the form when it is enclosed within a <form> ... </form> tag? Upon examining the code, I noticed that validation works fine when the form is ...

Laravel is powerfully integrated with PHP's infinite script capabilities

Looking for a way to continuously upload a table of users and relaunch the command directly after updating? Currently, I'm using Laravel with a cron job that runs every minute ($schedule->command('update:users')->everyMinute();), but t ...

I am encountering a problem with navigating through the CodeIgniter routing system

Currently, I am tackling a routing issue while working on PHP Codeigniter. Specifically, I am trying to set up dynamic software lists within my application. (:any) = 'Softwareproductslist'; (:any)/(:num) = 'Softwareproductslist'; T ...

Having trouble with uploading an image in Laravel using a modal?

For my laravel inventory system, I am facing an issue with uploading images for products. The old code I used for image upload is not working in my current project where I am utilizing a modal and ajax request to save inputs in the database. Can anyone pro ...

Executing a PHP function that invokes itself with an identical set of arguments

I have a PHP function with the ability to handle a dynamic number of arguments by using the func_get_args() method. class Test { private $flag = FALSE; public function test() { $arguments = func_get_args(); if ($this->flag) { ...

Is there a way to trigger elements to burst at random?

Here is the code snippet I am working with: function get_random(){ $filter_word = '1,2,3,4,5,6,7,8,9'; $array = explode(',', $filter_word); $randomKeys = array_rand($array, 2); $str = ''; foreach($rand ...

Invalid index when trying to add to an array

I am currently faced with a challenge in modifying an array that I have at hand; +rows: array:31 [▼ 0 => array:2 [▼ 0 => "20190101" 1 => "5" ] 1 => array:2 [▼ 0 => "20190102" 1 => "15" ] ...

Issue with Ajax filtering on the frontend of October CMS (Uncaught TypeError: $form.request is not a function)

I'm currently working on integrating a price filter into my October CMS project using AJAX on the frontend. However, I keep encountering an error stating (Uncaught TypeError: $form.request is not a function) whenever my JavaScript code is executed. $( ...

Utilize jQuery ajax to pull in data from an external website

I've been doing some research on using jQuery ajax to extract links from an external website, but I'm a bit lost on where to begin. I'm taking on this challenge just to push my skills and see what I can accomplish. While reading about the S ...

"Unique AJAX feature for manual, customized one-time payment subscriptions for adding items to cart

Hello, I am currently working on manually ajaxing this process: <a href="/cbg-gummies?add-to-cart=55337&convert_to_sub_55337=0" class="testing"> Add to cart </a> The purpose of this is to add a one-time purchase option ...

Implementing Object Value Assignment to an Element Using jQuery

I recently received a set of data via an API request: https://i.stack.imgur.com/YGe2D.jpg In order to display this data as selectable options, I included the following code snippet in my AJAX script: $.each($(value.routes), function(index, route){ $ ...

Sending a subdomain to a specific subfolder

I've been trying to redirect the subdomain to a subdirectory without success. Below is what I have attempted so far. RewriteEngine On RewriteCond %{HTTP_HOST} ^name\.site_url RewriteRule ^(.*)$ http://site_url/name/$1 [L,R=301] ...

Which is more efficient: Implementing caching on the frontend or on the

Currently, I am using ajax to send requests to the backend server, where operations are performed and responses are received: function getData() { new Ajax().getResponse() .then(function (response) { // handle response }) .catch(functi ...

There seems to be an issue with the AJAX REST call failing to transmit data

Whenever I attempt to submit the form, the page refreshes and nothing gets saved in the database. The code in subforum.js $(document).on('click','#submit',function(e) { var user = JSON.parse(sessionStorage.getItem("ulogovan")); consol ...

Error in .ajax - 'a' is not defined. If 'a' exists, call it, otherwise, display an

I am trying to understand why the following code works: var addresses = {"2-avenue-bir-hakiem": "2 Avenue Bir Hakiem", "56-rue-marcel-pagnol": "56 rue Marcel Pagnol"}; but this code does not work: var addresses = json.val; Even though my JSON output is ...

Basic emailing list linked to database

Currently, I am working on developing a mailing list feature that will save email addresses into an existing MySQL database after the user enters their first name, last name, and email and clicks on a submit button. Once this process is completed, I want a ...

Explore the wonders of Google Maps with the convenience of bpopup through ajax

I am currently using the bpopup plugin for ajax popups on my website. I have successfully implemented a popup with a Google map, but I am facing some issues when loading the map asynchronously. JavaScript $(document).on('click', '.aboutBranc ...

Arranging data in CodeIgniter Pagination

After successfully implementing Pagination in CI using a tutorial I found online, I decided to tackle Sorting on my own. However, I encountered an issue where the pagination links did not include the necessary URI Segments for "sortfield" and "sortorder," ...

Obtain PHP array after making an AJAX request

I'm using $.post() to send a JavaScript object and I need to receive an array in return. JavaScript Code var ajaxData = {action:"createuser"} $("input[required]").each(function(){ var attr = $(this).attr("name"); ajaxData[attr] = $(this).val ...