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?

asked Sep 7, 2014 at 8:40
1
  • 2
    Danger: You are vulnerable to SQL injection attacks that you need to defend yourself from. Commented Sep 7, 2014 at 8:45

1 Answer 1

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"));
}
answered Sep 7, 2014 at 8:43

2 Comments

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?
@KasunKodagoda — See the comment on the question, and make use of the mysqli_error function.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.