PHP: Dynamically update div content upon submission

I am attempting to update the "refresh" div after clicking the Submit button and also at regular intervals of 5 seconds. Despite looking through various resources, I have not been able to find a solution that meets my requirements.

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <?php 
    echo '<div id="refresh">';
        while ($r = $q->fetch()):
            echo 'Sender: ';
            if($r['senderid'] == $a) {echo $query1['username'];}
            elseif($r['senderid'] == $b) {echo $query2['username'];}
            echo '</br>';
            echo $r['message'];
            echo '</br></br>';
        endwhile;
    echo '</div>';
    ?>

    <form method="post">
        <input type="hidden" name="a" value="<?php echo $a;?>">
        <input type="hidden" name="b" value="<?php echo $b;?>">
        <textarea name="message" rows="3" cols="30"></textarea><br><br>
        <input id="submit" type="submit" value="Submit" />
    </form>

    <script>
    $(document).ready( function() {
        $("form").on("submit", function(e) {
            e.preventDefault(); // Prevent default form submission
            $.post("submit.php", $("form").serialize()); // Post the data
            $('textarea[name=message]').val('')
        });
    });
    </script>

Answer №1

Could you please conduct a basic investigation on $.post and setTimeout

Take a look at this example - there are several questions for you to think about

var val = "";
function updateContent() {
   var $text = $('textarea[name=message]');
   val = $text.val() || val; // what should happen if the user clears the input field?
   if (val == "") return; // stop if nothing is entered
   $.post("submit.php", $("form").serialize(), function(data) {
     $("#refresh").html(data); // display the retrieved data
     setTimeout(updateContent, 5000); // call the function again in 5 seconds
     // $text.val(''); // uncertain about whether to clear the input field here...
   });
}
$(function() {
    $("form").on("submit", function(e) {
      e.preventDefault(); // Prevent default form submission behavior
      updateContent();
    });
});

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

Generating an HTML table using data from a specified URL source

As a beginner, I am working on creating a dashboard for my smart home using OpenHab2.0. One of the key features I want to include is a widget that displays the next 5 tram departures from my local stop. The table structure for this information looks like: ...

What is the best way to use shortcodes to display custom fields for post objects, specifically products, within WordPress posts

I'm in the process of displaying 'featured products' within my blog posts. These specific products need to be chosen using custom post objects on the backend for each individual post. I've outlined what I believe the PHP code should lo ...

Troubles arising while submitting data from AngularJS to Amazon S3

I am currently in the process of developing an application using the MEAN (MongoDB, Express, AngularJS, node.js) stack where I need to upload image files to Amazon S3. Here is my approach: Initially, an http get request is sent to my API which outlines th ...

Unresponsive jQuery Ajax JSON Request

I am working with a basic Ajax function: insertInto = function(){ console.log("Hello "); var power = $("#power").val(); var vehicle = $("#vehicle").val(); var sendData = { "power": power, "vehicle": vehicle }; $.ajax({ type: ...

I'm finding it difficult to grasp the purpose of $inject within controllers

I'm feeling completely lost when it comes to understanding inject in Angular. I can't seem to grasp where it should be utilized and its purpose. Is it specifically tied to factory methods, as outlined here? myController.$inject = ['$scope&a ...

"Dynamically populate dropdown options based on the selection made in another dropdown menu

On a JSP page, I have two dropdown fields and a type4 connection with Oracle 10g. I want the second dropdown to be automatically filled based on the selection from the first dropdown by fetching data from the database. This should happen without refreshing ...

Tips for executing a function in the HC-Sticky plugin?

Currently, I am utilizing the HC-Sticky JavaScript plugin and endeavoring to utilize the documented reinit method. However, I am facing difficulty in understanding how to execute it. In this CodePen demo, a basic setup is displayed along with an attempt t ...

Using JavaScript regular expressions for email validation criteria

Hey there, I am struggling with Regular Expressions, especially when it comes to client side validation for a specific field. Can you please help me come up with a Regular Expression that would verify if an email address is valid based on these criteria: ...

What is the solution for fixing the Typescript error in formik onSubmit?

I encountered an error while using the onSubmit prop of Formik: The type '(values: { email: string; password: string; }) => { type: string; payload: { email: string | null; password: string | null; }; }' is not compatible with the type '(( ...

Is the textarea functioning properly with the inclusion of mysterious character variables?

As per the documentation When using an unknown named character reference like &this, it results in an ambiguous ampersand error. This situation is confusing <textarea> &this </textarea> What am I misunderstanding here? Any re ...

Execute JavaScript code via URL injection

One interesting aspect of the HTML is that it has a feature where it opens a webpage. The specific webpage it opens is determined by the URL, for example: https://mywebsite.com/index.html&audio=disabled In addition to this, there is a useful JavaScri ...

Styling Tip: Aligning text to the baseline of a height-adjusted input field using CSS

As per the information from the Mozilla documentation, it states that I can align the text in an input field to the baseline if the element's display property is set to inline-block. I have made adjustments to the height of several input elements, bu ...

The Battle of node.js Modules: Comparing socket.io and express.static

The server.js file I am currently running is set up as follows: module.exports = server; var express = require('express'); var fs = require('fs'); var server = express.createServer(); var port = 58000; server.listen(port); var ...

What is the best way to highlight titles that are unique but still prominent?

.test{ display:none; } .title:nth-child(odd){ background: #ddd; } <div class='title'>lorem</div> <div class='title'>lorem</div> <div class='title test'>lorem</div> <div class='tit ...

The class name is not defined for a certain child element in the icon creation function

Currently, I am developing a Vue2 web application using Leaflet and marker-cluster. I am encountering an issue with the iconCreateFunction option in my template: <v-marker-cluster :options="{ iconCreateFunction: iconCreateClsPrg}"> ...

Exploring the Functionality of Using Multiple Middlewares in Vue.js 3

For my web app project using vue.js 3 and vue-router, I followed a helpful tutorial on implementing middleware pipelines. The tutorial can be found at: https://blog.logrocket.com/vue-middleware-pipelines/. This tutorial demonstrated creating middleware to ...

Customize the background color of a popup modal except for one element

After much searching without finding a solution, I am reaching out here for help. Whenever I click on a Bootstrap modal, a popup appears with a background color and CSS applied. My issue is that I want to prevent the Bootstrap modal from applying the backg ...

Importing a library dynamically in Next.js

I'm currently facing a challenge in dynamically importing a library into one of my next.js projects. The issue arises when I don't receive the default export from the library as expected. Initially, I attempted to import it the next.js way: impo ...

My React setup is causing some problems that I need to address

React is not my strong suit, but I need to test a React application. The issue arises when attempting to run the server using gulp nodemon, resulting in numerous errors. It seems that the application is built on an outdated version of React and some libra ...

Splitting a PHP string without any restrictions

I am trying to understand the explode function with a positive limit parameter of 2. What exactly does this limit parameter do, and is there a way for me to remove it if needed? $array = explode(' ', $str, 2); ...