PHP and AJAX allow for seamless data retrieval without the need for page refreshing, and the data can be easily displayed in a modal window

I am currently encountering an issue with sending data to another page without refreshing. I am able to send the data as text, but for some reason, I am unable to send it as a modal. Why might this be happening?

Here is an image of my current page https://i.stack.imgur.com/MLXYa.png

Below is the code snippet from ajax4.html

This section handles data submission and inserts


<h1>AJAX POST FORM</h1>

    <form id="postForm">
        <input type="text" name="name" id="name2">
        <input type="submit" value="Submit">
    </form>

    <script>

        document.getElementById('postForm').addEventListener('submit', postName);


        function postName(e){
            e.preventDefault();

            var name = document.getElementById('name2').value;
            var params = "name="+name
;
            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'process.php', true);
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');

            xhr.onload = function(){
                console.log(this.responseText);
            }
            xhr.send(params);
        }
    </script>

Code snippet from ajax5.html

This part fetches the data and aims to display it within a modal

**EDIT** Here's the current HTML 


            <h1>Users</h1>
        <div id="users"></div>


<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">User List</h4>
      </div>
      <div class="modal-body" id="user-list">
        <p>User list here</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>



<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script>


<script>
var still_fetching = false;

// Fetch data every 3 seconds (3000)
setInterval(function(){ 
     if (still_fetching) {
         return;
     }
     still_fetching = true;
     loadUsers();
}, 3000);

// Need to update this function slightly
function loadUsers(){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'users.php', true);

        xhr.onload = function(){
            if(this.status == 200){
                var users = JSON.parse(this.responseText);

                var output = '';

                for(var i in users){
                output += '<div id="myModal" class="modal">' +    
                    '<div class="modal-content">' +
                        '<span class="close">&times;</span>' +
                        '<p>'+users[i].id+'</p>' +
                        '<p>'+users[i].name+'</p>' +
                      '</div>' +
                    '</div>';

                }

                document.getElementById('user-list').innerHTML = output;
                document.getElementById('myModal').style.display = "block";  
                still_fetching = false;
            }
        }

        xhr.send();
}
</script>
</body>
</html>

process.php

    <?php

$conn = mysqli_connect('localhost','root','','ajaxtest');



echo 'Processing....';


if(isset($_POST['name'])){
    $name = mysqli_real_escape_string($conn, $_POST['name']);
    
    $query = "INSERT INTO users(name) VALUES('$name')";

    if(mysqli_query($conn, $query)){
        echo 'User Added...';
    }else{
        echo 'ERROR: '.mysql_error($conn);
    }
}



if(isset($_GET['name'])){
    echo 'GET: Your name is '. $_GET['name'];
}

Answer №1

Your code has a few issues that need to be addressed.

1. When checking the name parameter, make sure you provide it when making the GET request:

if(isset($_GET['name']))

Ensure the name parameter is provided in your GET request:

xhr.open('GET', 'users.php?name=shingo', true);

2. The response you are receiving is not in JSON format:

echo 'GET: Your name is '. $_GET['name'];

JSON.parse(this.responseText);

Answer №2

If your modal relies on Bootstrap for styling:

<!-- Modal -->
<div id="myModal" class="modal fade" role="dialog">
  <div class="modal-dialog">

    <!-- Modal content-->
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal">&times;</button>
        <h4 class="modal-title">User List</h4>
      </div>
      <div class="modal-body" id="user-list">
        <p>Display user list here</p>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div>
    </div>

  </div>
</div>

Make changes to your JavaScript function:

function loadUsers(){
        var xhr = new XMLHttpRequest();
        xhr.open('GET', 'users.php', true);

        xhr.onload = function(){
            if(this.status == 200){
                var users = JSON.parse(this.responseText);

                var output = '';

                for(var i in users){
                output +=
                    '<div>' +
                        '<p>'+users[i].id+'</p>' +
                        '<p>'+users[i].name+'</p>' +
                    '</div>';

                }

                //document.getElementById('users').innerHTML = output;
                document.getElementById('user-list').innerHTML = output;
                document.getElementById('myModal').style.display = "block";  //show modal
                still_fetching = false;
            }
        }

        xhr.send();
}

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

Smoothly transition between the new and existing child elements in a React component with a

Currently, I am utilizing a React component that renders a child element through props.children. The content within this child element varies dynamically. I am looking for the most effective method to smoothly transition (fade out the old element and fad ...

Discover past stock prices on Yahoo Finance

I'm stuck on tweaking a functioning jfiddle example that I have. Can anyone help me with this two-part question regarding the jfiddle: http://jsfiddle.net/maxmillien/qPVSy/ Part 1) Is there a way to clear the search each time a new search is performe ...

End the Jquery.ajax connection

Is there a way to include a close button in this popup that can be used when clicking on Continue Shopping? The HTML code is as follows: <div id="notification"></div> The modified HTML code after the function call: <div id="notification" ...

The issue with Angular.js webpage routing seems to persist in my single-page application (SPA) despite my utilization of ng-view

I'm having trouble inserting a view into my index.html using $routeProvider and ng-view from the AngularJS libraries. Can anyone assist me in figuring out why it's not being inserted? Below is the code for my index.html, views, and app.js files: ...

Unusual syntax in Symfony framework

I am currently working on a new project for a website using the Symfony3 framework, and I have encountered an issue with understanding the syntax in Twig: <li><a href="{{ path('contact') }}">{{ 'site.template.menu.contact'| ...

Exploring the Excitement of PHP Regular Expressions (preg_replace)

Looking for assistance with a regex preg_replace function to clean up HTML content being submitted to my app's controller/model. The goal is to strip away unwanted HTML and convert specific elements into proprietary tags for the app. $postText = $_PO ...

Combining PHP Variable with URL String

<td><input type="submit" onClick="window.location.href='https://www.'.$myValue.'.test.com'" value="Click!"></td> I am trying to create a button that will redirect to one of eight possible URLs based on a variable. How ...

The proper method for incorporating a hover effect using CSS

Currently, I am facing an issue with integrating a hover effect to an image using CSS. The problem arises when the hover area is not aligned properly and the effect triggers even when the mouse is not directly over the image. <body> <div id=&apos ...

What is the best way to add HTML formatted text into Outlook?

In my Emacs, I've generated this syntax-highlighted code snippet and now want to paste it into an Outlook email with rendered HTML (without the actual HTML code). <pre> <span style="color: #a020f0; background-color: gtk_selection_bg_color;"& ...

Implementing a keypress function that can handle duplicate names

HTML <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="pm" type="text" value="0"/> <input name="total" type="text" value="0" disabled="disabled"/> Javascript $('[name="pm"]' ...

What is the best method for disabling autoscroll for a specific div id when the :target attribute

I created this accordion menu using only html and css, but the buttons are built with the :target id. Is there a way to prevent the automatic scrolling when any button is clicked without using javascript? It currently moves to the anchor #id. I've se ...

Tips for adding a class to the end of the DOM class

Greetings! I'm currently working with the code below: for ( let x: number = 0; x < this._vcr.element.nativeElement.querySelectorAll(".ui-steps-item").length; x++) { let className: any = this._vcr.element.nativeElement.querySelectorAll( ...

Chrome clipping positioned spans

Having trouble positioning a label above inline sections with spans in Chrome, as the labels are getting clipped oddly. Check out these screenshots: Firefox view: Chrome view: In the Chrome screenshot, you can see that the labels are being cut off based ...

Formatting won't assist in aligning Facebook button

I am currently working on a page that includes a div with a Facebook recommend button. In order to style the Facebook code, I enclosed it with this formatting: <div style="align:center"> <div id="fb-root"></div> <script src=" ...

Unable to insert controller into routeprovider

Currently, I am working on an exercise in AngularJS to enhance my skills focusing on routes. However, I am facing issues with getting the controller attributes to function correctly inside the routed template. Despite reading numerous tutorials, the code s ...

Unsupported server component type: undefined in Next.js version 13 is not recognized by the server

Encountered some unusual behavior in Next.js 13 while attempting a simple action. I have provided a basic example demonstrating the issue. Seeking assistance in understanding why this is occurring. This scenario involves 3 components: page: import {Conta ...

Utilizing React to adapt to varying HTML layouts while maintaining consistent component usage

How can I create an App with two different views for mobile and desktop without relying solely on CSS Media Queries? I have been searching for guidance but so far haven't found a solution. Any advice or direction on where to find documentation or oth ...

Is it possible for my OAuth2 callback page to share the same HTML page? Also, what is the process for obtaining the token?

In my setup, I am working with static html and javascript along with C# Web API. One of the scenarios I encountered involves a link that triggers an oauth2 server from my HTML file named index.html. The question arises: Is it appropriate to establish the c ...

Understanding PHP's ability to decode JSON arrays

I received this data in URL call and I am trying to extract the value of "coupon_title". Array ( [success] => 1 [data] => Array ( [0] => Array ( [0] => Array ( [featured] => [exclusive] => [promo_id] => P11757 [offer_ ...

Get the docx file as a blob

When sending a docx file from the backend using Express, the code looks like this: module.exports = (req, res) => { res.status(200).sendFile(__dirname+"/output.docx") } To download and save the file as a blob in Angular, the following code snippet i ...