0

I have a php file that fetches the last price and description of item upon selecting an itemcode from a dropdown list.

The Issue:

When the request is made on the front end, the request is sent to the processing page, which returns a JSON data.

It works perfectly well on my local windows Server. Upon migration to a Live Windows Server, it throws the error like this:

SyntaxError: JSON.parse: unexpected character at line 1 column 9 of the JSON data var data4=JSON.parse(data4);

When I inspect the element using firebug on Firefox browser, I discover that the processing script shows 200K OK 581ms, which indicate the processing script is fine. But below that is this error of :

SyntaxError: JSON.parse: unexpected character at line 1 column 9 of the JSON data var data4=JSON.parse(data4);

When I checked further, the processing script which is OK, on the Response and HTML TAB, displays the expected result, which is supposed to show on the requesting (front-end) page.

I need help figuring out why this is happening. Kindly find the pages below.

Front-end page script:

<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
    $("select.partno").change(function(){
       var selectedCustomer = $(".partno option:selected").val();
       $.ajax({type: "POST",url:"process-grpid.php",data:{custid:selectedCustomer}}).done(function(data4){
            var data4=JSON.parse(data4);
           //using php-mysql before
           if(data4.sta == 0){
           $("#desc").html(data4.ref);
           $("#purch").html(data4.lprice);
           }else{
            $("#desc").html(data4.ref);
           $("#purch").html(data4.lprice);   

           }
       });
    });
    });
    </script>

Process-grpid.php script:

<?php
       if(isset($_POST["custid"])){

                include 'includes/session.php';
                include 'includes/db_connection.php';
                include 'includes/functions.php';
                 $partid = $_POST["custid"];
                 if($partid !== 'Select PartNo'){ 
             $gets = "SELECT * FROM tab_stock WHERE itemName='".$partid."'";
             $get = mysqli_query($connection,$gets);

          $row = mysqli_fetch_array($get);


          $desc = $row['description'];
          $lprice = $row['Rate'];
          if($partid=='N/A'){
              $res["sta"]=0;
              $res["ref"]="<input type='text'   class='desc' name='descr'  size='50' required='required'/>";
              $res["lprice"]="<input type='text' id='puch' name='lastpur'   required='required'/>";
          }else{
              $res["sta"]=1;
              $res["ref"]="<input type='text'  value='$desc' class='desc' name='descr'  size='50' readonly='readonly' required='required'/>";
              $res["lprice"]="<input type='text' id='puch' name='lastpur' value='$lprice'  readonly='readonly' required='required'/>";  

          }
          echo json_encode($res);
          }

         }

enter image description here

David Mukoro
  • 467
  • 1
  • 8
  • 25
  • `var data4 = JSON.parse(data4)` -> You haven't defined the variable data4 and yet you run a function on it? –  Jul 08 '16 at 09:55
  • @SuperCoolHandsomeGelBoy It's shadowing a function parameter. – gcampbell Jul 08 '16 at 09:56
  • First, delete the var. Second, show the code in Fiddle so that we can debug more easily, or directly link us to your site –  Jul 08 '16 at 09:56
  • (It's better to use `===` for equality comparisons, especially with things like numbers.) – gcampbell Jul 08 '16 at 09:58
  • And why are you using if statement? The two don't seem to have a difference –  Jul 08 '16 at 09:59
  • Compare the testing AJAX response to the live AJAX response and see if there's differences (e.g. encoding differences could alter characters) – apokryfos Jul 08 '16 at 09:59
  • @SuperCoolHandsomeGelBoy:I needed to use use if, because, it will responsed to N/A and when the itemCode is selected. – David Mukoro Jul 08 '16 at 10:21
  • @Dave please show us the Response, and not HTML part, as revealed in your developing tool –  Jul 08 '16 at 10:23
  • @gcampbell: I have tried the ===, yet it is still showing the same parse error, even after specifying the datatype:json. yet the error: SyntaxError: JSON.parse: unexpected character at line 1 column 9 of the JSON data – David Mukoro Jul 08 '16 at 10:24
  • Can you try `console.log(data4)`? – gcampbell Jul 08 '16 at 10:25
  • @gcampbell:how can i use console.log(data4)? – David Mukoro Jul 08 '16 at 10:26
  • `console.log(data4)` is javascript statement. Type it in the console and see what is in data4 –  Jul 08 '16 at 10:27
  • @SuperCoolHandsomeGelBoy It would have to be inside the Ajax callback. – gcampbell Jul 08 '16 at 10:30
  • @gcampbell: From the console, as I have shown above, the processing script returns the expected values, but only not displaying them in the Requested Page – David Mukoro Jul 08 '16 at 10:30
  • @Dave Show the value to us. Maybe you overlooked smth –  Jul 08 '16 at 10:31
  • {"sta":1,"ref":"Bearing Thrust","lprice":"5000"} – David Mukoro Jul 08 '16 at 10:37
  • No, reviewing the PHP code, ref and lprice should be HTML codes –  Jul 08 '16 at 10:44

2 Answers2

0

One reason the console is returning 200OK because the requested server is there, but the response it is expecting(JSON) was not valid.

You also did not specify the dataType:'json' in your ajax request which tells that you are expecting json data and not just plain text.

graceth
  • 178
  • 8
0

It appears you are declaring data4 twice, once in the function def function(data4) and then again at var data4=.... It should work if you use separate variable names. It's a good idea to avoid reusing a variable name in 2 different contexts in the same function.

$.ajax({type: "POST",
    url:"process-grpid.php",
    data:
    {
        custid:selectedCustomer
    }
}).done(function(response){

       var data4 = JSON.parse(response);

       if(data4.sta == 0){
           $("#desc").html(data4.ref);
           $("#purch").html(data4.lprice);
       }else{
           $("#desc").html(data4.ref);
           $("#purch").html(data4.lprice);   

       }
});

One thing to consider is that JS understands JSON natively. Meaning, you don't need to use JSON.parse. You only need to tell it to expect JSON dataType: 'json',. I would use success: instead of done(). done() may not work as expected because it doesn't care about success. I would also use a truthy if statement. Also your if and else statements do the same thing. One of those appears to be unneeded. Lastly, add an error callback.

$.ajax({
    type: "POST",
    url: "process-grpid.php",

    dataType: 'json', // expected dataType of the response

    data: {
        custid: selectedCustomer
    },
    success: function(response) {

        var data4 = response;

        if (data4.someValueThatShouldBePresent) {
            $("#desc").html(data4.ref);
            $("#purch").html(data4.lprice);
        } else {
            $("#desc").html(data4.ref);
            $("#purch").html(data4.lprice);

        }
    },
    error: function(request, error) {
            // This callback will trigger on an unsuccessful request
            alert('Unable to connect, try again. ');
        }
});
Dieter Donnert
  • 192
  • 2
  • 9
  • I have made the changes. yet display :Json.Parse Error.Any futher assistance? – David Mukoro Jul 08 '16 at 11:37
  • I edited my answer to be more inline with what I actually do. I would also check to see that `process-grpid.php` actually returns JSON by changing the $_POST to $_REQUEST and constructing a GET in the address bar of a browser. – Dieter Donnert Jul 08 '16 at 13:02
  • You need to *look directly at the JSON data stream.* That could be as simple as adding a pop-up message to the code that receives it, before it attempts to decode it. The software is telling you that there's an error in it. ### Also, I specifically *dis*agree with the notion that you should not be using `JSON.parse`: although the JSON format is directly based on JavaScript syntax, there is a potential for JavaScript code-injection if you simply "evaluate" what you get. ("Don't be *that* trusting of anything anywhere ...") It also gives you "reliable detection of errors like these!" – Mike Robinson Jul 08 '16 at 13:36
  • A possible cause of a message like this ... is that what you're actually getting, in this scenario, actually *isn't JSON!* Maybe it's an error-message, instead. **LQQK** at it. – Mike Robinson Jul 08 '16 at 13:38
  • @DieterDonnert: I tried it it just display the alert message, which is the error side of the code. WHat could be the issue? – David Mukoro Jul 08 '16 at 15:46
  • I would suspect a php or mysql error is stopping execution before the json_encode - That php error message would not be valid JSON. The $_REQUEST thing I suggested would show you the error message. Or do as Mike suggests and view the stream before JSON.parse. `alert(response)` maybe. – Dieter Donnert Jul 08 '16 at 22:50
  • @MikeRobinson, jQuery dataType does not use eval. I would never eval anything - ever. http://stackoverflow.com/questions/2449220/jquery-uses-new-functionreturn-data-instead-of-evaldata-to-parse – Dieter Donnert Jul 08 '16 at 22:54
  • "A very wise move ..." In any case: use the browser's debugger features to LOOK AT what you got back. I agree with Dieter, "two replies back," that it's very, very likely that what the server is handing you IS NOT "JSON." (It could well be: "500 Internal Server Error.") :-/ – Mike Robinson Jul 09 '16 at 02:26
  • Please, I am still in a fixed as regards the question above. Still not working. Or Is there a way of getting data from processed script into the Requesting Page without using Json.Parse(data)? – David Mukoro Jul 11 '16 at 15:53
  • Json.Parse is not the problem. The evidence points to the php script. Did you trouble shoot the php script? What were your findings? – Dieter Donnert Jul 12 '16 at 03:37