0

I have crated a sample web service to store and retrieve data. The PHP web service has 2 scripts called getData.php and saveData.php, getData returns a json response and saveData saves the json object to database.

getData.php

<?php
    require_once ('../database.php');
    mysqli_select_db($conn, $database);

    $query = "SELECT * FROM user ORDER BY id ASC";

    $result = mysqli_query($conn, $query) or die(mysqli_error($conn));

    $rows = array();

    while($packages = mysqli_fetch_assoc($result)) {
        array_push($rows, $packages);
    }

    header('Content-type: application/json');
    echo json_encode($rows);
?>

saveData.php

<?php

    require_once ('../database.php');
    mysqli_select_db($conn, $database);

    if (isset($_POST['json'])) {
        $jsonObj = $_POST['json'];

        $jsonObj = json_decode($jsonObj);

        $query = "INSERT INTO user (first_name, last_name, description)"
                . " VALUES ('".$jsonObj->{'first_name'}."', '".$jsonObj->{'last_name'}."', '".$jsonObj->{'description'}."')";

        mysqli_query($conn, $query);

        header('Content-type: application/json');
        echo json_encode($_POST['json']);
    }
?>

this is inside my wamp/www folder in a folder called testService. Then i have another folder called testConsume where it has the html page with a simple form that sends the data to the testService/saveData.php file.

HTML

<form role="form">
    <div class="form-group">
        <input name="first_name" id="txtFirstName" class="form-control" placeholder="First Name" type="text" />
    </div>
    <div class="form-group">
        <input name="last_name" id="txtLastName" class="form-control" placeholder="Last Name" type="text" />
    </div>
    <div class="form-group">
        <input name="description" id="txtDescription" class="form-control" placeholder="Description" type="text" />
    </div>
    <a id="submit" class="btn btn-success" onclick="sendData()">Submit</a>
</form>

in the script the sendData() function takes the data and send it as a json object

function sendData() {
    var firstName = $('#txtFirstName').val();
    var lastName = $('#txtLastName').val();
    var description = $('#txtDescription').val();

    var jqxhr = $.ajax({
            url: 'http://localhost:8080/testService/json/saveData.php',
            type: 'POST',
            contentType: 'application/json',
            data: { json: JSON.stringify({
                first_name: firstName,
                last_name: lastName,
                description: description
            })},
            dataType: 'json'
        });

    jqxhr.done(function() {
        alert("Success! " + firstName + " " + lastName + " is a " + description);   
    });
    jqxhr.fail(function() {
       alert("Failed"); 
    });

}

When i run the testConsume/index.html and click on submit, the alert message Failed shows. And when i check the database there is no data added. What am i doing wrong?

Kasun Kodagoda
  • 3,956
  • 5
  • 31
  • 54
  • 2
    **Danger**: You are **vulnerable to [SQL injection attacks](http://bobby-tables.com/)** that you need to [defend](http://stackoverflow.com/questions/60174/best-way-to-prevent-sql-injection-in-php) yourself from. – Quentin Sep 07 '14 at 08:45

1 Answers1

2

Remove contentType: 'application/json'.

You are sending JSON embedded in application/x-www-form-urlencoded data, not plain JSON.


Alternatively. Send and parse actual plain JSON:

contentType: 'application/json',
data: JSON.stringify({
    first_name: firstName,
    last_name: lastName,
    description: description
}),

And in your PHP:

if (stripos($_SERVER["HTTP_CONTENT_TYPE"], "application/json")===0) {
    $jsonObj = json_decode(file_get_contents("php://input"));
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • now the ajax call if successful. But the data is not sent to the database. Is there something wrong in the way im saving to the database? – Kasun Kodagoda Sep 07 '14 at 08:55
  • @KasunKodagoda — See the comment on the question, and make use of the `mysqli_error` function. – Quentin Sep 07 '14 at 09:00