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.

1
  • I guess your JSON has any special characters, so this string had been cut off. Commented May 11, 2021 at 7:06

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Does this mean I have to save the json to file first?
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
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.

1 Comment

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.