Skip to content
Advertisement

Sending a JSON string to HTML that is too large

I’m using Codeigniter4, and I generate a rather long JSON so that I can make map points with it. However, when I pass along the string with

echo view('pages/' . $page, $data);

And attempted to unpack the string on the html side with

var geojson = JSON.parse('<?php echo $geoJSON; ?>')

I get a syntax error because the entire json string was not sent. I have tested my setup with a smaller amount of data, so I am sure that the issue is the length of the string.

Is there any way to send large strings? If not, is there a better way? I have heard of something called AJAX, but MapBoxGL needs a json object with specific keys, so that is why I am passing along a complete json from my php side.

Advertisement

Answer

If you want to load that data after the page loads, so as not to block your UI, you could use this generic ajax function. No library needed

function fetchJSONFile(path, callback) {
    var httpRequest = new XMLHttpRequest();
    httpRequest.onreadystatechange = function() {
        if (httpRequest.readyState === 4) {
            if (httpRequest.status === 200) {
                var data = JSON.parse(httpRequest.responseText);
                if (callback) callback(data);
            }
        }
    };
    httpRequest.open('GET', path);
    httpRequest.send(); 
}

// this requests the file and executes a callback with the parsed result once
//   it is available
fetchJSONFile('pathToFile.json', function(data){
    // do something with your data
    console.log(data);
});

from https://stackoverflow.com/a/14388512/1772933

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement