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

Searching for the row value of specific data within a table using Javascript

I have a PHP table populated with values, and I want to make two of the table data cells editable. The table headers include: Task, Due Date, Staff, and Department. The values in the table data are retrieved from a database using Laravel Eloquent. &l ...

Displaying VueJS property inside an array of HTML elements

Currently, I am working with an HTML array that contains the following data: data-groups='["category_all", "data goes here"]' In my project, there is a prop named "title" that holds the specific string needed to be displayed in the "data goes he ...

What is the correct method for setting a scope variable from a service in Angular?

Is there a way to retrieve the return value from a service method and set it into the scope for further processing in the template? I've discovered that I cannot directly access the scope within services. While I could use Rootscope, I believe there ...

Exclude certain labeled posts from appearing on the homepage of a Blogger website

I am managing a website dedicated to the best WhatsApp status on my blogger blog. I am in search of a way to conceal certain category posts from appearing on the homepage using coding techniques. Despite extensive research, I have been unsuccessful in fi ...

Swap out the HTML tags with JavaScript code

I've been looking everywhere, but I couldn't find the answer. Here is my issue / question: I have a page from CKEDITOR with: var oldText = CKEDITOR.instances.message.getData(); So far, so good. The string looks something like this: <table ...

Can loading HTML and js through ajax be considered secure?

I am currently utilizing the Jquery load function $('#result').load('test.php'); in order to dynamically load a page within another page when clicking on a tab. The page being loaded contains javascript, php, and a form. Upon inspecting ...

Struggling to extract a substring from a lengthy multi-line string in Swift

After extracting some HTML code and storing it in a string named "html", I needed to retrieve the number of stars from this HTML code. Initially, my approach was to search for the word "stars" within the html string itself. Here's the code snippet I u ...

Choose Dropdown Option in PDF Using Data from FDF Document

Currently, I have been successfully saving data to an editable PDF with defined fields using a FDF file and PDFtk. However, I am facing an issue where I need to select a dropdown value but cannot figure out how to do it. Below is the field data extracted f ...

Adjusting the parent with CSS transitions to perfectly align with the final height of a

Jade example div.parent div.child1 div.child2 Upon initial load, Child1 is visible. Clicking will hide Child1 and make Child2 visible. Another click will reverse this action. During the transition between hiding and showing the children, there s ...

What is a way to center content vertically without using extra containers?

I've been facing challenges in vertically aligning an item within its container. Despite trying multiple suggestions that advise wrapping the content in another div or container, I encountered various issues which I won't delve into. Therefore, ...

The PHP code exclusively recognizes the echo function within this particular if statement

$con = mysqli_connect('localhost', 'login', '*mypass*', 'login'); $check = "SELECT * FROM users"; $rs = mysqli_query($con, $check); if(isset($_POST['submit'])) { $username = strtolower($_POS ...

Is there a way to confirm that the content of two files is identical?

Currently, I am utilizing mocha/supertest/should.js for testing a REST Service. When I make a request to GET /files/<hash>, it returns the file as a stream. I am seeking guidance on how to use should.js to assert that the contents of the file are i ...

Verify the validation of the text box

Checking a textbox control for validation is necessary. Validation Criteria: Value should be between 0 and 1000, with up to 2 decimal places (e.g. 1.00, 85.23, 1000.00). Once 2 decimal points are used, users should not be able to enter additional ze ...

Is there a way to use jQuery to hide rows in a data table that contain a specific code, such as "1.1" or "1.2," that includes a

When using ajax, I pass data from two inputs to another page. These values are then used in a query to display the results in a data table on the main page within the success function. Now, I'm looking to implement a condition where any data containi ...

What is the reason for the incompatibility between $.ajaxSetup and $.post methods

What is the difference in behavior between these two code snippets? $.post("ajax/p_getOnePosition.jsp", { positionNo: positionNo, sessionID: v_sessionID, }, function(response2) { And why does this one not include the sess ...

The challenge of mocking methods/hooks remains when utilizing `jest.spyOn` in Jest

I am attempting to create mock methods and hooks in a file, then import those mock functions as needed in my test files. useMyHook.jsx const useMyHook = () => { const [val, setVal] = useState(200) return { val } } export { useMyHook } Hello.jsx: ...

Error: Attempting to access the 'clipboard' property on an undefined object results in a TypeError when invoking this.$q.electron.clipboard

I'm currently working on incorporating copy to clipboard functionality into my app using Electron. This is the command I am using: methods: { copyToClipboard () { if (process.env.MODE === 'electron') { this.$q.electro ...

Modify the value of a CSS property through JavaScript

Hey there, I'm wondering how to change a CSS value of the document itself, rather than targeting a specific element. I've already looked into solutions like Change :hover CSS properties with JavaScript, but they all involve adding CSS rules. I a ...

The specified container is not a valid DOM element

Recently, I decided to implement Redux into my React application. However, as I began setting everything up within my index.js file, I encountered an error message: https://i.sstatic.net/4kL2T.png. After some research, I learned that this error is related ...

A PHP function that decodes HTML entities to their corresponding special characters

Here is a function that converts html entities back to html special characters: function decodeEntities($value, $double_encode = TRUE) { return htmlspecialchars( (string) $value, ENT_QUOTES, "UTF-8", $double_encode); } Now, I want to display the ...