简体   繁体   中英

Fetching Data Using Ajax

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);
          }

         }

在此处输入图片说明

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.

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. ');
        }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM