-1

So I’m working on a To Do App and I used Ajax to send data to PHP when a task is clicked to be marked as completed. PHP then sends an SQL query to MySQL and changes the value in the completed column from 1 to 0 or visa vera. Originally, I tried to send a PHP header to go back to that page but it didn’t work so after the request was sent I wrote some JavaScript code to refresh the page and the task is now marked as completed and I have a css style for that. I was wondering, I thought the purpose of Ajax was to not have to reload the whole page so idk if I’m using Ajax wrong and there is a better way to do this? The project works but I just want some feedback on my code I guess.

main.js:

for(i=0; i < div.length; i++){
    div[i].addEventListener("click", function(e){ 
        let xhr = new XMLHttpRequest();

        xhr.open('POST', 'process_complete.php', true);
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
        let task_num = e.target.getAttribute("id");
        xhr.onreadystatechange = function(){
            if(xhr.readyState === 4 && xhr.status === 200){
                location.reload(); 
            }
        }
        xhr.send(JSON.stringify(task_num));
    });
}

process_complete.php:

if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){

    $data = file_get_contents('php://input');
    $id = json_decode($data);


    $sql = mysqli_query($conn, "SELECT * FROM tasks WHERE Num = '$id'"); 

    if($sql === false){
        printf("error: %s\n", mysqli_error($conn));
    }

    while($row = mysqli_fetch_row($sql)){
        if($row[3] === "1") {
            $mysqli_update = mysqli_query($conn, "UPDATE tasks SET Completed = 0 WHERE Num = '$id';");
        } else {
            $mysqli_update = mysqli_query($conn, "UPDATE tasks SET Completed = 1 WHERE Num = '$id';");
        }
    }
}

2 Answers2

3

I thought the purpose of Ajax was to not have to reload the whole page

It is.

You are supposed to write JavaScript that modifies the DOM of the current page at the point where you have location.reload().

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • yeah but I’m sending data to the PHP. and PHP outputs the data from the database to index.php as completed or not complete based on whatever value is in the col Completed. if I remove the reload(); then the database gets an updated value and the user wont see the changes unless the page is reloaded. So thats where I’m confused. – UntouchedDruid4 Jul 23 '18 at 16:22
  • "PHP outputs the data from the database to index.php" — That doesn't matter since (a) it is `process_complete.php` you are requesting and (b) you are handling the response with JS, not loading it into the browser window as a page. You requested `index.php` in the past. Ajax doesn't make the browser travel back in time and update the page to show what `index.php` would output if you requested it **now**. You have to make the changes yourself. – Quentin Jul 23 '18 at 16:27
  • So when I use Ajax I’m requesting a page... I never thought about it like that. So I shouldn’t have a 3rd page like process_complete.php which is just in the middle of index.php and config.php. But if I request index.php instead of process_complete.php with ajax its still going to reload the page right? – UntouchedDruid4 Jul 23 '18 at 16:43
  • "ajax its still going to reload the page right" — Wrong. The response will be made available to JS. It is up to you to write the JS to make the DOM changes. – Quentin Jul 23 '18 at 16:45
  • "So I shouldn’t have a 3rd page like process_complete.php" — Wrong. Small webservers which do simple things are the bread and butter of Ajax. You don't want to fetch entire HTML documents with JavaScript. – Quentin Jul 23 '18 at 16:45
  • So the response can be the data the I’m sending in the first place. I can send it to php to be stored in the database and send that data back to update the DOM without having to reload the whole page? – UntouchedDruid4 Jul 23 '18 at 17:15
  • Yes, you don't even need to send it back really. If you just sent the data, then you can use the copy of that you already have on the client. – Quentin Jul 23 '18 at 19:35
0

So there is a third step you may be missing. You have passed the data and fetched it into the PHP page, however you need to pass it back. In order to do that, you first place an echo inside the PHP page which will work in much the way that return works with a function in PHP. Once you have done that, you will need to make sure AJAX takes in that returned value, and then make sure you have a function that includes this AJAX and uses that value to replace, append, or removes whatever content the AJAX is using. This is a lot easier to do if you use an extension of AJAX like the .post() found in the JQUERY framework.

Tyler Lazenby
  • 409
  • 5
  • 27
  • In the index.php page the tasks are outputted to the page and the css classes are dynamic based on whatever value is in the Completed col of the table in the db. When a user clicks to mark it completed or not I used ajax to send that data to php and update it in the db and then after that the only way to see the results is to refresh the page bc PHP runs before Js does. It works I just don’t know if thats the right way to do it. And it kinda looks ugly when a users clicks the complete button and the page hard refreshes. – UntouchedDruid4 Jul 23 '18 at 16:35
  • If you pass it to a PHP page that fetches the results and then echo's the result set back as an array (or even an assoc array), then you will be able to use a javascript function to dynamically change the content, as long as your ajax is runs before the change commands in that function. An answer on how to do that is found [here](https://stackoverflow.com/questions/39068662/how-to-receive-data-back-from-server-using-ajax) – Tyler Lazenby Jul 23 '18 at 18:30