简体   繁体   中英

Jquery ajax syntaxerror json.parse unexpected character at line 1 column 1 of the json data

I have this web application that I just use four scripts that is a dynamical.

Brief:

  • Init.php = Database,
  • index.php = webpage,
  • api.php = grabs info from server/post info to server,
  • drive.js = grabs info from api.php and displays it to index.php or when post, went to api.php

So I'm just trying to add a person through post method by jquery ajax. But I have this syntaxerror in my code, which mainly goes to my drive.file of addPerson function:

json.parse unexpected character at line 1 column 1 of the json data

    // populate people/states, also person/visit form submit
    $(document).ready(function(){
        populatePeople();
        populateStates();
        displayData();

        $('#addPersonSubmit').click(function(e){
            e.preventDefault();
            addPerson();
        });

        $('#addVisitSubmit').click(function(e){
            e.preventDefault();
            addVisit();
        });
    });

    //display selected person
    function displayData()
    {
        $("#SelectHumanDropDown").change(function(){
            $.ajax({
                type: "GET",
                url: "api/visits",
                dataType: "json",
                success: function(data)
                {
                    var i = $("#SelectHumanDropDown").val();
                    $("#displayInfo").empty();

                    var firstName = data[i]["firstname"];
                    var lastName = data[i]["lastname"];
                    var food = data[i]["food"];
                    var stateAbb = data[i]["stateabb"];
                    var stateName = data[i]["statename"];
                    var dateVisit = data[i]["date_visited"];

                    $("#displayInfo").append(
                    "First name: " + firstName +
                    "<br> Last name: " + lastName +
                    "<br> Favorite food: " + food +
                    "<br> Visited : " + stateAbb + " " + stateName +
                    "<br> on " + dateVisit);
                }
            });
        });
    }

    //populate people's dropdowns
    function populatePeople()
    {
        $.ajax({
            type:"GET",
            url:"api/people",
            dataType:"json",
            success : function(data)
            {
                //console.log('success');
                //console.log(data);
                $("#SelectHumanDropDown").empty();
                $("#humanNameDropDown").empty();
                var len = data.length;
                for(var i = 0; i < len; i++)
                {
                    var id = data[i]["id"];
                    var firstname = data[i]["firstname"];
                    $("#SelectHumanDropDown").append("<option value='" + id + "'>" + firstname + "</option>");
                    $("#humanNameDropDown").append("<option value='" + id + "'>" + firstname + "</option>");
                }
            },
            error : function(data)
            {
                console.log('failed');
                console.log(data);
            }
        });
    }

    //populate state dropdown
    function populateStates()
    {
        $.ajax({
            type:"GET",
            url:"api/states",
            dataType:"json",
            success : function(data)
            {
                //console.log('success');
                //console.log(data);
                $("#stateNameDropDown").empty();
                var len = data.length;
                for(var i = 0; i < len; i++)
                {
                    var id = data[i]["id"];
                    var stateName = data[i]["statename"];
                    $("#stateNameDropDown").append("<option value='" + id + "'>" + stateName + "</option>");
                }
            },
            error : function(data)
            {
                console.log('failed');
                console.log(data);
            }
        });
    }

        //Add person to database
        function addPerson()
        {
            $.ajax({
                type: "POST",
                url: "api/people", // api/people
                data: $("#personForm").serialize(),
                 success: function(data,status,xhr)
                {
                    console.log(data);
                    console.log(status);
                    console.log(xhr);
                    console.log($("#personForm").serialize());
                    console.log("You have added a person");
                    populatePeople();
                    displayData();
                },
                 error: function(data,status,xhr)
                {
                    console.log(data);
                    console.log(status);
                    console.log(xhr);
                    console.log($("#personForm").serialize());
                    console.log("error");
                    //populatePeople();
                    //displayData();
                }
            });
       }

        //Add visit to database
    function addVisit()
    {
        $.ajax({
            type: "POST",
            url: "api/visits", // api/visits
            data: $("#humanNameDropDown, #stateNameDropDown, #visitForm").serialize(),
            success: function(data)
            {
                console.log(data);
                console.log($("#visitForm").serialize());
                console.log("You have added a visit");
            },
            error: function(data)
            {
                console.log(data);
                console.log($("#visitForm").serialize());
            }
        });
    }

I also have my database which is init.php

        <?php
    // Define variables. 
    $host = "localhost";
    $user = "root";
    $password = "root";
    $database = "myDB";

    //Create connection
    $connection = mysqli_connect($host, $user, $password);

    // Check connection
    if(!$connection){
    die("Could not connect: " . mysqli_connect_error());}
    else{
        echo "Connection successfully \n";
    }

    // Drop database
    $dropDB = "DROP DATABASE myDB";

    // Check drop database
    if($connection->query($dropDB) === TRUE){
         echo "Database myDB was successfully dropped \n";
    } else {
        echo "Error dropping database: \n" . $connection->error;
    }

    //Create Database called "myDB"
    $db = "CREATE DATABASE IF NOT EXISTS myDB";

    //Check Datebase
    if($connection->query($db) === TRUE){
        echo "Database created successfully \n";
    } else {
        echo "Error creating database: \n" . $connection->error;
    }

    // Select Database
    $connection->select_db($database);

    //Create States Table
    $statesTable = "CREATE TABLE IF NOT EXISTS States
    (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    stateabb varchar(2) NOT NULL,
    statename varchar(40) NOT NULL
    )";

    // Create People Table
    $peopleTable = "CREATE TABLE IF NOT EXISTS People
    (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    firstname varchar(40) NOT NULL,
    lastname varchar(40) NOT NULL,
    food varchar(40) NOT NULL
    )";

    // Create Visit Table
    $visitTable = "CREATE TABLE IF NOT EXISTS Visits
    (
    id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
    p_id INT(40) NOT NULL,
    s_id INT(40) NOT NULL,
    FOREIGN KEY (p_id) REFERENCES People(id),
    FOREIGN KEY (s_id) REFERENCES States(id),
    date_visited varchar(40) NOT NULL
    )";

    //Check States Table
    if($connection->query($statesTable) === TRUE) 
    {
        echo "States Table created successfully \n";
    }
    else
    {
        echo "States Table wasn't created \n" . $connection->error;
    }

    //Check People Table
    if($connection->query($peopleTable) === TRUE) 
    {
        echo "People Table created successfully \n";
    }
    else
    {
        echo "People Table wasn't created \n" . $connection->error;
    }

    //Check Visit Table
    if($connection->query($visitTable) === TRUE) 
    {
        echo "Visit Table created successfully \n";
    }
    else
    {
        echo "Visit Table wasn't created \n" . $connection->error;
    }

    // Insert data into states table
    $insertData = " INSERT INTO States (stateabb, statename) 
                    VALUES ('LA', 'Louisiana');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('FL', 'Florida');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('TX', 'Texas');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('NM', 'New Mexico');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('ID', 'Idaho');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('IA', 'Iowa');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('ME', 'Maine');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('NV', 'Nevada');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('NY', 'New York');";
    $insertData .= "INSERT INTO States (stateabb, statename) 
                    VALUES ('UT', 'Utah');";

    // Insert data into people table
    $insertData .= "INSERT INTO People (firstname, lastname, food) 
                    VALUES ('Paul', 'Chu', 'Rice');";
    $insertData .= "INSERT INTO People (firstname, lastname, food) 
                    VALUES ('Chui', 'Chu', 'Steak');";
    $insertData .= "INSERT INTO People (firstname, lastname, food) 
                    VALUES ('Pandalord', 'Chu', 'Cookies');";
    $insertData .= "INSERT INTO People (firstname, lastname, food) 
                    VALUES ('LordBabyPanda', 'Chu', 'Milk');";

    // Insert data into Visits table
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('1', '1', '1994/07/14');";
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('1', '2', '1994/07/14');";
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('2', '10', '1994/07/14');";
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('3', '9', '1994/07/14');";
    $insertData .= "INSERT INTO Visits (p_id, s_id, date_visited) 
                    VALUES ('4', '7', '1994/07/14');";

    // Check stateData in table
    if($connection->multi_query($insertData) === TRUE)
    {
        $lastID = $connection->insert_id;
        echo "insertData create successfully. Last inserted ID is: \n" . $lastID;
    }

    else
    {
        echo "Error: \n" . $connection->error;
    }

    //Close Connection
    $connection->close();
    ?>

Also, I have my index.php and api.php as links so this page wouldn't be dreadful long.

index.php

api.php

So, hello everyone, I figured out my own problem but with help with @RoryMcCrossan,

So when I checked for my responseText it was undefined . But then I remembered it was a parsing error, so I look through the web, and I saw someone had a similarly case, but they echo json_encode() their data back when they post.

So I did the same thing to test it and it works! So happy.

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