fetch in JS is not receiving the appropriate JSON format from json_encode in php

JaJaJaJapan

I have a function in JS that fetches data from a php page.

JS code:

fetch("print.php)
    .then(function (r) {
        return r.json()
    })
    .then(function (values) {
        ......
        ......
    })
}

PHP print.php code:

<?php
if ($_SERVER['REQUEST_METHOD'] == 'GET') {
    $num = $_GET['num'];
    $datas = array_chunk(array_map('rtrim', file('./myFile.txt')), 5);
    $result;
    foreach ($datas as $index => $data) {
        if ($data[0] == $num) {
            $result = $data;
        }
    }

    echo json_encode($result);
}

When I run my code, I am getting the error below:

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Can anyone help me debug this. I have tried echo-ing json_encode([$result]); but it didn't work. I have been trying to fix it for the past 3 hours, but i am hopeless. I have no clue in which direction to go.

UPDATE: screenshot of the header

Reborn

First of all, you have extra closing braces at the end of PHP file if that is not just a typo while pasting in code here.

About the code, well as it is unclear what is in the file myFile.txt, let me show you an example of how it works. You can follow these steps on your local computer to replicate the example and see it working on your end.

let's say I have this simple PHP filename fetch.php

<?php 
if($_SERVER['REQUEST_METHOD'] == 'GET'){
    echo json_encode(['Message'=>'you successfully received the response.']);
}
?>

Create an HTML page sample.htmland add the following inside the body tag.

<ul>
    <li class="print"></li>
</ul>

Now add the following script in the bottom of HTML page before the </body> tag.

<script type="text/javascript">
  $(document).ready(function(){
    var resultContainer = document.querySelector('ul li.print');

    fetch('fetch.php')
    .then(function (response) {
        return response.json();
    })
    .then(function (response) {
        resultDiv.innerHTML = response.success;
    }).catch(function(err){
        resultDiv.innerHTML='There was an error reading the JSON response see here '+err;
    });
   });
</script>

Since we are fetching a PHP file which is returning json, we return response.json() on the response to give it the proper MIME type so it will be handled properly, then display it in the <li> element. Additionally, i am using the .fail to show the error message if the Promise is rejected

This is as simple as it gets and it should show you the text you successfully received the response. inside the li once the Promise resolves. If it does then it means you need to troubleshoot your PHP file first to see what is in the myFile.txt and what is printed in response when it reaches that last line echo json_encode($result);.

Also, your PHP file states that you are sending the query parameter num to the PHP file whereas your script does not contain any query string parameter with the name num.

secondly what is the $result; doing after the line $datas = array_chunk(array_map('rtrim', file('./myFile.txt')), 5);, most of your code makes no sense, you should work on your assignment and provide actual sensible code that others can understand and help you out.

Hope that helps you out

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

PHP Fetch data from database and encode into JSON format Yii framework

From Dev

PHP Fetch data from database and encode into JSON format Yii framework

From Dev

PHP array format for json_encode

From Dev

php json_encode output format

From Dev

PHP json_encode to JS Array of Objects

From Dev

PHP's json_encode and JS's JSON.stringify

From Dev

Format Array Data to JSON_ENCODE using php

From Dev

JSON.parse from php's json_encode issue

From Dev

accessing json data passed from php (json_encode(databaseresults))

From Dev

Strange JSON output from PHP json_encode()

From Dev

Unexplained number in front of json array from php json_encode

From Dev

json_encode with correct format

From Dev

PHP Multidimensional Associative Array to JS Object Using json_encode()

From Dev

PHP sorted Array is not sorted in JS after json_encode

From Dev

php json_encode in js returning undesired result

From Dev

Error passing php array with json_encode to js handler

From Dev

PHP how to json_encode() return from rrd_xport()?

From Dev

Create a json_encode string from PHP array

From Dev

Passing Array From PHP to JQuery json_encode

From Dev

PHP how to json_encode() return from rrd_xport()?

From Dev

Php json_encode from mysql > output without column names

From Dev

passing data from php to javascript problems with json_encode

From Dev

PHP jQuery json_encode

From Dev

PHP json_encode { } characters

From Dev

PHP Echo json_encode

From Dev

json_encode method in PHP

From Dev

PHP json_encode failing

From Dev

PHP json_encode in autocomplete

From Dev

json_encode of array php