0

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.

Suresh Kamrushi
  • 15,627
  • 13
  • 75
  • 90
yeeshue99
  • 238
  • 2
  • 8

2 Answers2

2

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

Kinglish
  • 23,358
  • 3
  • 22
  • 43
  • Does this mean I have to save the json to file first? – yeeshue99 May 11 '21 at 07:42
  • No, that was just an example. You could have it be something like `fetchJSONFile('pathToFile.php'` and have the php script echo the JSON data using `json_stringify($json)` that your ajax would get – Kinglish May 11 '21 at 16:57
1

You need to provide information on how you're constructing your JSON on the server with PHP. If your string is properly formatted, you can simply use json_encode to grab your Array and do the job for you. You can use your developer console to see the network response on your corresponding ajax call to check the response status or response string as well.

Glorified
  • 56
  • 7
  • 1
    the string is 100% built correctly. Tested with a small set of data, about 15 or so points, it works perfectly. The issue is when I am sending about 200 or so points, the string that is sent over is cut off for some reason. I'm not using Ajax at the moment so I don't know what that means unfortunately – yeeshue99 May 11 '21 at 14:49