The onprogress event for the XMLHttpRequest object threw an error due to an Uncaught SyntaxError, indicating

I have implemented an ajax function successfully

However, I am facing an issue where when using onprogress, I sometimes receive incomplete HTML response and the console displays

Uncaught SyntaxError: Invalid or unexpected token
but the function still continues.

Below is the function in question:

function xhrAJAX ( divID , param2 ) {

    var pcache = (Math.floor(Math.random() * 100000000) + 1);
    var params = "divID="+encodeURIComponent(divID)+"&param2="+encodeURIComponent(param2);
    var xhr = new XMLHttpRequest(); xhr.open("POST", "/file.php?pcache="+pcache, true);
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.onprogress = function(e) { $("#"+divID).html(e.currentTarget.responseText) ; }
    xhr.send(params);

}

***** I understand that replacing .onprogress with

xhr.onreadystatechange = function(e) { if (xhr.readyState == 4) { $("#"+divID).html(e.currentTarget.responseText) ; } }
would resolve the console error. However, in some cases, PHP execution may take a long time and I need to show progress.

My installed PHP8 is set up with NGINX without output buffer. Therefore, running

echo 'stuff'; sleep(3); echo '2';
would display 'stuff' first and then '2' after 3 seconds.

PLEASE NOTE: The PHP section mentioned here is not the main concern.

THE MAIN QUESTION: Is there a way to prevent receiving "half returned html" during onprogress (from the JavaScript side)?

Answer №1

After discovering the new javascript fetch replacement, I delved into it and managed to generate some streamable HTML content.

Notably, this solution also functions seamlessly within webviews on both Android and iOS platforms ;)

In my specific setup, I have PHP 8 and NGINX configured with output buffer turned off. This means that each echo statement is pushed out while the script continues its execution...

function fetchsrteam ( divid , sub , buttonid ) {
    
    var pcache = (Math.floor(Math.random() * 100000000) + 1); 
    var postix = [];
    postix["preventCache"] = pcache;
    postix["divid"] = encodeURIComponent(divid);
    postix["buttonid"] = encodeURIComponent(buttonid);
        
    fetch("/.........php?pcache="+pcache, {
      method: "POST",
      body: JSON.stringify(Object.assign({}, postix)),
      headers: {"Content-type": "application/json; charset=UTF-8"}
    }).then(response => response.body)
      .then(rb => {
        const reader = rb.getReader();
          return new ReadableStream({
            start(controller) {
              function push() {
                reader.read().then( ({done, value}) => {
                  if (done) {
                    console.log('done', done); controller.close(); return;
                  }
                  controller.enqueue(value); $("#"+divid).append(new TextDecoder().decode(value)); push();
                })
              }
            push();
            }
          });
    });

}

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

Save the current time and date to a database by executing a mysql_query

<form action="actionMAppointment.php?stu_id=<?php echo $row_RecEdit['stu_id'] ?>" method="post"> Time: <input type = "time" name="appointmentTime" id = "appointmentTime" /> Date: <input type = ...

How can I achieve auto-refresh functionality in SQLite using PHP and JavaScript without refreshing the entire page

I am currently working with a straightforward php code that retrieves data from a SQLite database by using the query "$query ="Select A from B"". The process works smoothly, and upon updating the SQLite database, I can refresh the page to display the new d ...

unleashing the magic of AJAX: a guide to extracting

In my Symfony project, I am attempting to retrieve the content of an AJAX request in order to check the data using dump(). The purpose is to process this data and perform a SQL query. However, when I use dump() in my controller, there doesn't appear t ...

React doesn't have file upload configured to update the state

I am working on integrating a file upload button that sends data to an API. To ensure only the button triggers the upload dialog and not the input field, I have set it up this way. Issue: The File is not being saved to state, preventing me from using a ...

A guide on enabling or disabling a combobox in vuejs3

In VueJs 3, I am looking for a way to toggle the Disable/Enable status of a combo-box based on a specific property. Below is my code snippet: <template> <div class="combobox"> <label for={{selector_name}}> <p> ...

retrieve information instantly on AngularJS by utilizing $http or $resource

I designed a plugin for field customization. angular.module('ersProfileForm').directive('ersProfileEditableField', ['$templateCache', '$compile', 'profileFieldService', 'RolesService', ...

Using cascading style sheets to switch a page into editing mode

Is it possible to change the view of a page after clicking a button without using javascript, and instead relying solely on CSS? I want to display a page with information where users can click an edit button and make changes within the same view rather th ...

Is it possible to toggle all parent targets in Bootstrap?

When trying to showcase my point, I believe it is best demonstrated by visiting Bootstrap documentation at https://getbootstrap.com/docs/4.0/components/collapse/ and viewing the "multiple targets section." In this section, you will find three buttons: togg ...

The ajax function is malfunctioning when called from an external JavaScript file

I am having an issue with a Registration page that only has UserName and Password fields. When I click on the Submit button, I want to be able to submit the new User Details using an ajax call with jQuery. I have tried defining an Insert function on butt ...

Using Angular to open a modal by invoking the href function

Current Project Context I am currently following a tutorial on CRUD operations with DataTables, but I am using Asp.Net WebApi with Angular for this project. At step 9 of the tutorial, it introduces partial views for pop-up windows. However, instead of us ...

Using Typescript in React to render font colors with specific styling

Attempting to utilize a variable to set the font color within a react component, encountering an error with my <span>: Type '{ style: "color:yellow"; }' is not assignable to type 'HTMLProps<HTMLSpanElement>' The use of yel ...

Unable to create a new collection in Firebase Firestore

I encountered an issue while trying to add a collection in Firebase Firestore using the function .collection(doc).set. Despite finding the new user in authentication in Firebase, the collection was not created and the console displayed an error message. ...

Using JavaScript or JQuery, move an image from one location to another by removing it and adding

Firstly, feel free to check out the JSFiddle example My task involves moving an image with the class "Full" after a div with the class "group-of-buttons" using JavaScript. Here is the snippet of HTML code: <img src="http://i.telegraph.co.uk/multimedia ...

Having issues with UTF8 encoding when utilizing AJAX to send the complete HTML source in JavaScript

I'm encountering difficulties when trying to send a complete page source using AJAX. Despite attempting to escape the content with escape(), encodeURI(), and encodeURIComponent(), I cannot successfully transmit utf8 characters. Below is my code snipp ...

Unable to retrieve information from the API server (with a public IP) using ngResource

This may seem like a naive question, but I am stuck and new to Angular. Despite searching extensively, I have not been able to find a solution. var app=angular.module('myApp',['ngResource']); app.controller('myCtrl',['$s ...

Utilizing jQuery to create a recursive AJAX poll with setTimeout to regulate the polling frequency

$(document).ready(function() { (function pollUsers() { setTimeout(function() { $.ajax({ url: "/project1/api/getAllUsers", type: "GET", success: function(userData) { ...

The comments are visible in the database, but they only appear on my index page once I refresh the page

Trying to create a simple website with AJAX, PHP, jQuery, and MySQL. The goal is to have a text area that sends data to the database and displays it on the index page using AJAX/jQuery. However, after submitting the data, I have to manually refresh the pag ...

Particles are not appearing when using the Three.js shader material

Hey there, I've been working on a simple scene with a grid of particles in the shape of a cube. Check it out here: https://codepen.io/sungaila/pen/qqVXKM The issue I'm facing is that when using a ShaderMaterial, the particles don't seem to ...

Issue with $.ajax() functionality persists across all browsers except for Firefox

Whenever the page loads, a small script I have retrieves rental dates. Additionally, if the user selects a different month from the drop down, new dates are also fetched. Unfortunately, the site is using jQuery 1.2.3 and I'm unable to update to 1.4 d ...

Every time I navigate to a new page in NextJs, the useEffect hook

I am working on developing a new blog app with Next.js. In the current layout of the blog, I have successfully fetched data for my sidebar (to display "recent posts") using the useEffect/fetch method, as getInitialProps only works on Pages. However, this ...