If you like DNray Forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...

 

Difficulties with AJAX, JavaScript & PHP

Started by vizzmedia, Oct 19, 2022, 12:51 AM

Previous topic - Next topic

vizzmediaTopic starter

How can I handle this situation? On my webpage, there's a registration form that triggers the database entry file upon clicking the button. To ensure validity, the JavaScript event handler examines the fields, and it cancels the form submission on the markup using `e.preventDefault`. However, things get complicated when I try to add an ajax request that uses the GET method to test the database login in real-time. The issue arises because the program first calls ajax, which executes the PHP script, while the JavaScript code has already finished its job.

I tried to make ajax synchronous, but it was of no help. To fix this problem, I need to pause the JavaScript code until the PHP script completes execution, and then continue working. Alternatively, I could disable the default button click execution, and then create a function that sends the form data to PHP and the database using JavaScript after validation from the database. How can I best solve this problem?
  •  


jacksonbird03

Can you display your JavaScript code?
  •  

kanesimicart

I apologize for being direct; please don't take it personally. In my opinion, AJAX is the best way to communicate with a database. The server processes select, update, insert, and delete operations while leaving minimal load on the server.

Regarding graphics, I think it's impractical to rebuild all the charts simultaneously every time there's a change. If ten people are working on the same data concurrently, the graphs will be rebuilt each time a cell is saved. Even if all ten clients save at the same time, the server will have to rebuild the charts ten times. This doesn't make sense. Instead, I suggest running the graph generation script once per second, thereby reducing the server's workload.

This is my personal approach when creating websites, where the server works with the database, and everything else is done on the client-side.
  •  

lawyersonia

To solve this problem, you can use asynchronous JavaScript and XML (AJAX) to send the form data to the PHP script and handle the response without refreshing the page. Here are a few steps to guide you in solving this issue:

1. Disable the default button click execution by adding e.preventDefault() in your JavaScript event handler. This will prevent the form from being submitted traditionally.

2. In your JavaScript code, create an AJAX request using the XMLHttpRequest or fetch API. Set the method to GET or POST, depending on your requirements. Include the form data as parameters to be sent to the PHP script.

3. Attach an event listener to the AJAX request to handle the response when it returns. This can be done using the `onreadystatechange` event or the `.then()` function if you're using the fetch API.

4. In the PHP script that receives the AJAX request, process the received data and perform the necessary database operations. Return a response indicating the success or failure of the operation.

5. In the event listener for the AJAX request's response, check for the successful completion of the PHP script execution. Use the returned response data to inform the user about the result of the registration attempt.

Here's a more detailed breakdown of the steps involved in solving your problem:

1. Disable default form submission: In your JavaScript event handler, add the line `e.preventDefault();` to prevent the form from being submitted traditionally and the page from refreshing.

2. AJAX request creation: Use either the XMLHttpRequest or fetch API to create an AJAX request. Set the method to "GET" or "POST", depending on your needs. Pass the form data as parameters to be sent to the PHP script. For example:

  ```javascript
  var xhr = new XMLHttpRequest();
  xhr.open("GET", "your_php_script.php?param1=value1&param2=value2", true);
  xhr.send();
  ```

3. Event listener for AJAX response: Attach an event listener to your AJAX request to handle the response when it returns. You can listen for the `readystatechange` event or use the `.then()` function if using the fetch API. For example:

  ```javascript
  xhr.onreadystatechange = function() {
    if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
      // Handle the response here
      var response = xhr.responseText;
      // Process the response data and update the webpage accordingly
    }
  };
  ```

4. PHP script execution: In your PHP script (`your_php_script.php` in the example above), receive the AJAX request and process the received data. Perform the necessary validation and database operations.

5. Return a response from PHP: After processing the data in PHP, return a response that indicates the success or failure of the operation. You can use `echo` or `return` statements to send a response back to the AJAX request.

6. Handle AJAX response: In the event listener for the AJAX request's response, check for the successful completion of the PHP script execution and handle the returned response data accordingly. Update the webpage to inform the user about the result of the registration attempt. For example:

  ```javascript
  if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
    var response = xhr.responseText;
    if (response === "success") {
      // Registration successful, update webpage accordingly
    } else {
      // Registration failed, display error message to user
    }
  }
  ```
  •  

SmutSia

I'd suggest that instead of trying to pause the JavaScript code, you should restructure your code to handle the asynchronous nature of the AJAX request. One way to do this is to use a callback function that gets executed once the AJAX request is complete.

For example, you can modify your code to create a function that sends the form data to PHP and the database using JavaScript after validation from the database. This function can be called in the success callback of the AJAX request.

Here's a sample code snippet that demonstrates this approach:

$('#myForm').submit(function(e) {
  e.preventDefault();
  var formData = $(this).serialize();
  $.ajax({
    type: 'GET',
    url: 'validate.php',
    data: formData,
    success: function(data) {
      if (data == 'valid') {
        // Call the function to send the form data to PHP and the database
        sendData(formData);
      } else {
        // Handle the case where the data is invalid
      }
    }
  });
});

function sendData(formData) {
  $.ajax({
    type: 'POST',
    url: 'process.php',
    data: formData,
    success: function(data) {
      // Handle the case where the data is successfully sent
    }
  });
}

In this code, the sendData function is called only after the AJAX request to validate.php is complete and the data is valid.

Alternatively, you can use Promises or async/await to handle the asynchronous nature of the AJAX request.
  •  


If you like DNray forum, you can support it by - BTC: bc1qppjcl3c2cyjazy6lepmrv3fh6ke9mxs7zpfky0 , TRC20 and more...