1

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

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
  • Can I see the request header? I would like to see `Content-Type` of it. – IzumiSy Nov 25 '17 at 04:06
  • @IzumiSy http://localhost:8080/print.php?num=abc123 – JaJaJaJapan Nov 25 '17 at 04:13
  • That's not a request header. Read this thread: https://stackoverflow.com/questions/4423061/view-http-headers-in-google-chrome to retrieve it with Google Chrome, and please paste the screenshot of yours. – IzumiSy Nov 25 '17 at 04:31
  • @IzumiSy updated the post – JaJaJaJapan Nov 25 '17 at 04:39
  • why is it that the request `URL` is sent as a value to the `id` parameter in the query string. – Muhammad Omer Aslam Nov 25 '17 at 04:46
  • @MuhammadOmerAslam this is a homework, and we were given these lines of code to use : const ident = document.querySelector('ul li .print'); fetch("afficher.php?id=" + ident ) .then(function (r) { return r.json() }) – JaJaJaJapan Nov 25 '17 at 04:55
  • What is `$result` doing on line 4 of your php file ? why have you written it there.? –  Nov 25 '17 at 10:26
  • Your PHP function is very ambiguous. First of all, we need to know the contents of the file to point you in the right direction. Secondly, you should not look for HW answers on StackOverflow; you may get them, but you'll just hurt yourself. `$result` is always being overridden, regardless of what you found, so in the end the _last_ value that mapped correctly will sit inside of $result, and what is `$datas`? We don't know. We need more context information. – kevr Nov 25 '17 at 11:01
  • @kevr $num is unique and $result will be overwritten once. Yes, I will look for answers on Stackoverflow because this is how you learn. People will explain to you things and show you how to solve something you didn't learn in class. I learned a lot of stuff from StackOVerflow. – JaJaJaJapan Nov 25 '17 at 14:26
  • hey @LearnShareBuild updated my answer please verify if it works for you – Muhammad Omer Aslam Nov 25 '17 at 21:18

1 Answers1

-1

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

Muhammad Omer Aslam
  • 22,976
  • 9
  • 42
  • 68
  • my php is not sending JSON, because the json I am sending seems to be in the wrong json format thus the error. – JaJaJaJapan Nov 25 '17 at 04:58
  • i added the header to change the content type and i am still getting the error – JaJaJaJapan Nov 25 '17 at 05:03
  • 1
    and what is in the `ui li .print` can you add the html provided to you along with this script? also what are the contents of the file `myFile.txt` – Muhammad Omer Aslam Nov 25 '17 at 09:04
  • in your OP you have provided different JS code than you wrote in comments so please update your OP if the code being used is `const ident = document.querySelector('ul li .print'); fetch("afficher.php?id=" + ident ) .then(function (r) { return r.json() })` OR `fetch("print.php) .then(function (r) { return r.json() }) .then(function (values) { ...... ...... }) }` – Muhammad Omer Aslam Nov 25 '17 at 09:10
  • I agree with @MuhammadOmerAslam until it is clear what are the contents of `myFile.txt` file it would be unsure to decide what response is received. –  Nov 25 '17 at 10:17
  • @MuhammadOmerAslam I did as you suggested to debug it. – JaJaJaJapan Nov 26 '17 at 02:03
  • So?, were you able to sort out where the problem was in your code? – Muhammad Omer Aslam Nov 26 '17 at 02:05
  • I don't find anything to downvote without leaving a reason :( . please leave a comment along with downvote so the person getting downvoted gets to correct himself too. – Muhammad Omer Aslam Jan 13 '18 at 12:11