skip to Main Content

I’m getting "Unexpected token N in JSON at position 0" for ajax & php coding files.
Can someone help me solve this? I’ve just started coding.

I can get the query to work and insert data, if the datatype is text.
But when I try to get the data, the result of echo stuff from php file shows up for function(data). What can I do?

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Build an API</title>
    <style>
        .btn {
            border: 1px solid black;
            padding: 10px;
            display: inline-block;
        }
    </style>

</head>

<body> 

ID :
    <input type="number" name="xid" id="xid" value="1">
    <br> Name :
    <input type="text" name="name" id="name" value="tester">
    <br> Company :
    <input type="text" name="company" id="company" value="company">
    <br> Cost :
    <input type="number" name="cost" id="cost" value="10">
    <br>
    <div class='btn' id="btn1">Send Data</div>
    <div class='btn' id="btn2">Get Data</div>

    <div id="result"></div>
    <div id="sample"></div>



    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 
    <script>
        $(function () {
            //FIRST BUTTON
            $('#btn1').on('click', function () {
                var vars = {
                    xid: $('#xid').val()
                    , name: $('#name').val()
                    , company: $('#company').val()
                    , cost: $('#cost').val()
                    , action:'ADD'
                }
                $.ajax({
                    url: "api.php"
                    , data: vars
                    , type: "POST"
                    , dataType: 'json'
                }).done(function (data) {
                    $("#result").html(data).message;
                    console.log(data);
                    alert('DONE: ' + data);
                }).fail(function (xhr, textstatus,errorThrown) {
                    console.log(xhr);
                    console.log(textstatus);
                    //alert('xhr, textstatus: ' + xhr + textstatus);
                    alert("errorThrown    : " + errorThrown.message);
                    console.log("errorThrown    : " + errorThrown.message);
                })
            })
        })
    </script>
</body>

</html>


<?php
header('Content-Type: application/json; charset=utf-8');

$con = new mysqli("localhost","[name]","[password]","myDB");
if (!$con) {
    die("Connection failed: " . mysqli_connect_error());
}
$arr = [];

if($con->ping()){$arr['connected']=true;}else{$arr['connected']=false;}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $arr['xid'] = $_POST['xid'];
    $arr['name'] = $_POST['name'];
    $arr['company'] = $_POST['company'];
    $arr['cost'] = $_POST['cost'];   
    $arr['action'] = $_POST['action'];    
}else{
    $arr['xid'] = '100';
    $arr['name'] = 'noname';
    $arr['company'] = 'company';
    $arr['cost'] = '100';    
    $arr['action'] = 'ADD';
}

$xid = $arr['xid'];
$name = $arr['name'];
$company = $arr['company'];
$cost = $arr['cost'];  

if($arr['action']=='ADD'){   
    if(isset($xid) && isset($name) && isset($company) && isset($cost)){
        $sql = "INSERT INTO api (xid, cost, name, company) VALUES ('$xid', '$cost', '$name', '$company')";
        if (mysqli_query($con, $sql)) {
            echo "New record created successfully";
        } else {
            echo "Error: " . $sql . "<br>" . mysqli_error($con);
        }
        mysqli_close($con);
    }
}   
?>

2

Answers


  1. With this you announce that the response will be in JSON format:

    header('Content-Type: application/json; charset=utf-8');
    

    But a few lines later you return plain text:

    echo "New record created successfully";
    

    Either you change the header to

    header('Content-Type: text/plain; charset=utf-8');
    

    or you change the response to something like this

    echo json_encode(["message"=>"New record created successfully"]);
    
    Login or Signup to reply.
  2. since you put the dataType: 'json' in javascript, so you have to put all the returns from the php page (success and failure returns) with json_encode("...");

    OR

    change dataType: 'json' to dataType: 'text' in javascript

    and change in php

    header('Content-Type: application/json; charset=utf-8');
    

    to

    header('Content-Type: text/plain; charset=utf-8');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search