Ajax PUT request successful but not updating on database - javascript

I am performing an AJAX PUT request which is coming back as successful but not updating on the database.
Have checked to make sure the variables going into the array are correct before being converted to JSON.
var recycle = {
id:document.getElementById('id').value,
year:document.getElementById('year').value,
materialThousandTonnes:document.getElementById('material').value,
packagingWasteArising:document.getElementById('packaging').value,
totalRecoveredRecycled:document.getElementById('total').value,
achievedRecoveryRecyclingRate:document.getElementById('achieved').value,
euTargetRecoveryRecyclingRate:document.getElementById('target').value
};
$.ajax({
url: '/recycle',
method: 'PUT',
data: JSON.stringify(recycle),
contentType: "application/json;charset=utf-8",
success: function (data) {
alert("hi");
},
error: function (jqXHR, textStatus, errorThrown) {
alert(jqXHR + '\n' + textStatus + '\n' + errorThrown);
}
});
The alert "hi" appears everytime however it doesn't actually PUT the data into my database please help!
EDIT:
Here is server-side code for PUT request
public function performPut($url, $parameters, $requestBody, $accept)
{
global $dbserver, $dbusername, $dbpassword, $dbdatabase;
$newRecycle = $this->extractRecycleFromJSON($requestBody);
$connection = new mysqli($dbserver, $dbusername, $dbpassword, $dbdatabase);
if (!$connection->connect_error)
{
$sql = "update recycledb set year = ?, materialThousandTonnes = ?, packagingWasteArising = ?, totalRecoveredRecycled = ?, achievedRecoveryRecyclingRate = ?, euTargetRecoveryRecyclingRate = ? where id = ?";
// We pull the fields of the book into local variables since
// the parameters to bind_param are passed by reference.
$statement = $connection->prepare($sql);
$id = $newRecycle->getId();
$year = $newRecycle->getYear();
$materialThousandTonnes = $newRecycle->getMaterialThousandTonnes();
$packagingWasteArising = $newRecycle->getPackagingWasteArising();
$totalRecoveredRecycled = $newRecycle->getTotalRecoveredRecycled();
$achievedRecoveryRecyclingRate = $newRecycle->getAchievedRecoveryRecyclingRate();
$euTargetRecoveryRecyclingRate = $newRecycle->getEuTargetRecoveryRecyclingRate();
$statement->bind_param('iisiiss', $id, $year, $materialThousandTonnes, $packagingWasteArising, $totalRecoveredRecycled, $achievedRecoveryRecyclingRate, $euTargetRecoveryRecyclingRate);
$result = $statement->execute();
if ($result == FALSE)
{
$errorMessage = $statement->error;
}
$statement->close();
$connection->close();
if ($result == TRUE)
{
// We need to return the status as 204 (no content) rather than 200 (OK) since
// we are not returning any data
$this->noContentResponse();
}
else
{
$this->errorResponse($errorMessage);
}
}
}

So I found the solution to my issue after much a struggle
On this line:
$statement->bind_param('iisiiss', $id, $year, $materialThousandTonnes, $packagingWasteArising, $totalRecoveredRecycled, $achievedRecoveryRecyclingRate, $euTargetRecoveryRecyclingRate);
The id variable needed to be moved to the end of the statement...
Like this:
$statement->bind_param('iisiiss', $year, $materialThousandTonnes, $packagingWasteArising, $totalRecoveredRecycled, $achievedRecoveryRecyclingRate, $euTargetRecoveryRecyclingRate, $id);

$statement->bind_param('iisiiss', $year, $materialThousandTonnes, $packagingWasteArising, $totalRecoveredRecycled, $achievedRecoveryRecyclingRate, $euTargetRecoveryRecyclingRate, $id);

Related

PHP Undefined index data when I try to POST from Ajax

I am trying to update a mysql database using an Ajax POST request to a php file, but I receive the following error:
Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2
Notice: Undefined index: data in C:\xampp\htdocs\php\php\post.php on line 2
{"d":true}{"d":true}
Here is my Ajax code:
$('#addbut').click(function()
{
console.log($("#firstteam").val());
console.log($("#score1").val());
console.log($("#score2").val());
console.log($("#secondteam").val());
var data = {
firstteam:$("#firstteam").val(),
secondteam:$("#secondteam").val(),
score1:$("#score1").val(),
score2:$("#score2").val()}
$("#firstteam").val('');
$("#secondteam").val('');
$("#score1").val('');
$("#score2").val('');
$.ajax({
type: "POST",
url: "php/post.php",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType:'json',
//if received a response from the server
success: function(response)
{
var res = response.d;
if (res == true)
{
$("#error").html("<div><b>Success!</b></div>"+response);
updateTable();
}
//display error message
else {
$("#error").html("<div><b>Information is Invalid!</b></div>"+response);
}
},
//If there was no resonse from the server
error: function(jqXHR, textStatus, errorThrown)
{
console.log("Something really bad happened " + textStatus);
$("#error").html(jqXHR.responseText);
}
});
});
Here us my PHP code:
<?php
$data = $_POST['data'] or $_REQUEST['data'];
$js = json_decode($data,true);
$t1 = $js['firstteam'];
$t2 = $js['secondteam'];
$s1 = $js['score1'];
$s2 = $js['score2'];
updateFunction($t1,$s1,$s2);
updateFunction($t2,$s2,$s1);
function updateFunction($name, $s1, $s2)
{
$conn = new mysqli("localhost:3306","root","","leagues");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
if ($s1 > $s2)
$sql = "UPDATE league SET playedgames=playedgames + 1,wongames = wongames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 3 WHERE teams='".$name."'";
else
if ($s1 == $s2)
$sql = "UPDATE league SET playedgames=playedgames + 1,tiegames = tiegames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."', points = points + 1 WHERE teams='".$name."'";
else
if ($s1 < $s2)
$sql = "UPDATE league SET playedgames=playedgames + 1,lostgames = lostgames + 1,scoredgoal = '".$s1."', receivedgoal = '".$s2."' WHERE teams='".$name."'";
if ($conn->query($sql) === TRUE)
{
$response = json_encode(array('d' => true));
echo $response;
}
$conn->close();
}
?>
I tried some suggestions, but I don't know why my PHP code doesn't parse the data correctly. The Console.log from my Ajax function prints exactly what I want.
Here is what my debugger shows:
It doesn't work, because by putting
$.ajax({
...
data: '{"key":"value"}',
...});
you just put that string ({"key":"value"}) in raw form into request body.
Therefore there is no form parameter named data.
To retrieve this raw data from body use:
$data = file_get_contents('php://input');
OR
$data = stream_get_contents(STDIN);
instead of
$data = $_POST['data'] or $_REQUEST['data'];

Communication between JavaScript, PHP and MySQL

I'm trying to learn JavaScript to code for Cordova.
I read many tutorials, but none of them helped me with the folowing problem.
My cordova app is for testing very simple. Just a textbox and 2 buttons. Both Buttons calls a PHP script on my server. One button sends data to the PHP script to insert the value of the textfield in a MySQL database, the second button calls the same script and should write the values of the database to my cordova app.
Here is my
<?PHP
$response = array();
require_once __DIR__ . '/db_config.php';
$db_link = mysqli_connect (
DB_SERVER,
DB_USER,
DB_PASSWORD,
DB_DATABASE
);
mysqli_set_charset($db_link, 'utf8');
if (!$db_link)
{
die ('keine Verbindung '.mysqli_error());
}
if(isset($_POST['action']) && $_POST['action'] == 'insert'){
$name = $_POST['name'];
$sql = "INSERT INTO test.testTable (name) VALUES ('$name')";
$db_erg = mysqli_query($db_link, $sql);
if (!$db_erg){
echo "error";
}else{
echo "ok";
}
}
if(isset($_POST['action']) && $_POST['action']=='read'){
$sql = "SELECT * FROM testTable";
$db_erg = mysqli_query( $db_link, $sql );
if (!$db_erg )
{
$response["success"] = 0;
$response["message"] = "Oops!";
echo json_encode($response);
die('Ungültige Abfrage: ' . mysqli_error());
}
while ($zeile = mysqli_fetch_array( $db_erg, MYSQL_ASSOC))
{
//$response["success"] = $zeile['pid'];
//$response["message"] = $zeile['name'];
$response[]=$zeile;
}
echo json_encode($response);
mysqli_free_result( $db_erg );
}
?>
and here are my 2 functions in the cordova app:
function getNameFromServer() {
var url = "appcon.php";
var action = 'read';
$.getJSON(url, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
function sendNameToServer() {
console.log("sendNameToServer aufgerufen");
var url2send = "appcon.php";
var name = $("#Name").val()
var dataString = name;
console.log(dataString);
if ($.trim(name).length>0) {
$.ajax({
type: "POST",
url: url2send,
data: { action: 'insert', name: dataString },
crossDomain: true,
cache: false,
beforeSend: function () {
console.log("sendNameToServer beforeSend wurde aufgerufen");
},
success: function (data) {
if (data == "ok") {
alert("Daten eingefuegt");
}
if (data == "error") {
alert("Da ging was schief");
}
}
});
}
}
My Questions/Problems:
The sendNameToServer funtion works in that case, that the data will be inserted in my Database. But I never get the alert (the success: never called).
How can I pass "action = read" to the PHP script in the getNameFromServer() function?
The third question is a bit off topic, but is this art of code "save" or is it simple to manipulate the data between the cordova app and the server? What's the better way or how can I encrypt the transmission?
Here is one part answer to your question.
$.getJSON has a second optional parameter data that can be an object of information you want to pass to your script.
function getNameFromServer() {
$.getJSON("appcon.php", { action: 'read' }, function (returnedData) {
$.each(returnedData, function (key, value) {
var id = value.pid;
var name = value.name;
$("#listview").append("<li>" + id + " - " + name) + "</li>";
});
});
}
Edit: Since you are using $.getJSON(), the request method is a GET, which means you have to use $_GET in your third if statement in your PHP script.
if(isset($_GET['action']) && $_GET['action'] == 'read'){

Ajax returns success but doesn't change the database

I'm developing a small script of js to edit a profile in the way facebook used to be (click a button, edit and save without reloading the page). The problem is that when I run it, the ajax function returns sucess but akes no changes on the database. The function os js is this:
$('.savebtn').click(function(){
var editdata = $(".editbox").val();
var parameter = $(this).closest("td").find("#parameter").text();
var datastring = "data="+editdata+"&parameter="+parameter;
var $t = $(this);
console.log(datastring);
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function()
{
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
});
});
(Ignore the $t thing, somehow this works like this, but not if I use $(this))
Ajax executes the code for sucess but doesn't update anything on the database.
The PHP code for the database is:
<?php
include_once("../../config/connect_db.php");
include_once("../../database/cliente.php");
$parameter = $_POST['parameter'];
$data = $_POST['data'];
$id = $_SESSION['id'];
var_dump($_POST);
try {
updateProfile($parameter, $data, $id);
}
catch (PDOException $e)
{
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users
SET ? = ?
WHERE id = ?");
$stmt->execute(array($parameter, $data. $id));
}
EDIT: As pointed out, this could be a problem with trying to pass a column name as a parameter. Changed the code to the following, but with no sucess:
function updateProfile($parameter, $data, $id)
{
global $conn;
$query = "UPDATE biofood.users
SET $parameter = $data
WHERE id = $id";
$stmt = $conn->prepare($query);
$stmt->execute();
}
This line:
$stmt->execute(array($parameter, $data. $id));
I think should be
$stmt->execute(array($parameter, $data, $id));
(notice the comma after $data)
This might not solve your problem, but it might give you a better indication on where your problem is.
First, you are not checking whether it works or not as your updateProfile function returns nothing.
Modify your updateProfile function, so that it returns the number of rows affected. (BTW this is a safer way to write your function. If you can check or limit the value of $parameter prior to calling this function, it will be less prone to SQL injection.)
function updateProfile($parameter, $data, $id)
{
global $conn;
$stmt = $conn->prepare("UPDATE biofood.users SET $parameter = ? WHERE id = ?");
$stmt->execute(array($data, $id));
return $stmt->rowCount(); // # of rows affected
}
In the script that calls this function, get the value and send it back as a response. We'll send back a JSON.
$response = array();
try {
$response['success'] = updateProfile($parameter, $data, $id);
} catch (PDOException $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
header('Content-Type: application/json');
echo json_encode($response);
In your JavaScript file, make the following change:
$.ajax({
type: "POST",
url: BASE_URL + "/API/update_profile.php",
data: datastring,
cache: false,
success: function (data) {
if (data.success) {
$t.closest('td').find('.curr_value').html(editdata);
$t.closest('td').find('.curr_value').hide;
console.log(editdata);
$(this).prev(".edit").hide();
$(this).prev(".curr_value").show();
$(this).prev('.edit_link').show();
$(this).hide();
}
},
dataType: 'json'
});

Ajax login issues

I'm having issues with an Ajax login function. There was another question similar to mine that I was able to find but it proved no use.
I have no idea what is the issue, this works on another program as well with no issues, hopefully someone can see my mistake
From testing I think the issue is in the "checkLogIn" function because when I run the application the alert within the function shows
Ajax:
$("#checkLogIn").click(function()
{
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: checkLogIn(),
})
.done(function(data)
{
if(data == false)
{
alert("failure");
}
else
{
alert("Success");
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
function checkLogIn()
{
alert();
return JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
}
I'll also include the PHP but the PHP works 100% after testing it.
PHP:
$app->post('/logIn/', 'logIn');
function logIn()
{
//global $hashedPassword;
$request = \Slim\Slim::getInstance()->request();
$q = json_decode($request->getBody());
//$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName AND password=:password";
try {
$db = getConnection();
$stmt = $db->prepare($sql);
$stmt->bindParam("userName", $q->userName);
$stmt->bindParam("password", $q->password);
$stmt->execute();
//$row=$stmt->fetch(PDO::FETCH_ASSOC);
//$verify = password_verify($q->password, $row['password']);
$db = null;
//if($verify == true)
//{
// echo "Password is correct";
//}
//else
// echo "Password is incorrect";
echo "Success";
} catch (PDOException $e) {
echo $e->getMessage();
}
}
I have commented out any and all hashing until I can get this working properly
There is no problem with the ajax script. From my assumption you always get Error alert. That is because you added dataType: "json", which means you are requesting the response from the rootURL + '/logIn/' as json Object. But in the php you simply echoing Success as a plain text. That makes the ajax to get into fail function. So, You need to send the response as json. For more details about contentType and datatype in ajax refer this link.
So you need to change echo "Success"; to echo json_encode(array('success'=>true)); in the php file. Now you'll get Success alert. Below I added a good way to handle the json_encoded response in the php file.
$app->post ( '/logIn/', 'logIn' );
function logIn() {
global $hashedPassword;
$request = \Slim\Slim::getInstance ()->request ();
$q = json_decode ( $request->getBody () );
$hashedPassword = password_hash($q->password, PASSWORD_BCRYPT);
$sql = "SELECT * FROM users where userName=:userName";
try {
$db = getConnection ();
$stmt = $db->prepare ( $sql );
$stmt->bindParam ( "userName", $q->userName );
$stmt->execute ();
$row=$stmt->fetch(PDO::FETCH_ASSOC);
$verify = false;
if(isset($row['password']) && !empty($row['password']))
$verify = password_verify($hashedPassword, $row['password']);
$db = null;
$response = array();
$success = false;
if($verify == true)
{
$success = true;
$response[] = "Password is correct";
}
else
{
$success = false;
$response[] = "Password is incorect";
}
echo json_encode(array("success"=>$success,"response"=>$response));
} catch ( PDOException $e ) {
echo $e->getMessage ();
}
}
And I modified the ajax code. There I showed you how to get the response from the json_encoded Object.
$("document").ready(function(){
$("#checkLogIn").click(function()
{
var post_data = JSON.stringify({
"userName": $("#enterUser").val(),
"password": $("#enterPass").val(),
});
$.ajax({
type: 'POST',
contentType: 'application/json',
url: rootURL + '/logIn/',
dataType: "json",
data: post_data,
})
.done(function(data)
{
// data will contain the echoed json_encoded Object. To access that you need to use data.success.
// So it will contain true or false. Based on that you'll write your rest of the code.
if(data.success == false)
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Success:"+response);
}
else
{
var response = "";
$.each(data.response, function(index, value){
response += value;
});
alert("Failed:"+response);
$.mobile.changePage("#page");
}
})
.always(function(){})
.fail(function(){alert("Error");});
});
});
Hope it helps.

Parsererror when using AJAX and JSONP with Cordova

I am trying to post 4 variables to a database on an external server using a mobile application created using Cordova 4.0.0.
I have already had a look a countless posts similar to this trying, POST, GET, contentType etc. and none of these seem to work. I have worked with JSONP before and it worked fine (I used that code as a template), but this doesn't seem to work.
Here is the console log:
2015-01-30 09:19:09.817 Alert[1253:353531] {"readyState":4,"status":200,"statusText":"load"}
2015-01-30 09:19:09.817 Alert[1253:353531] parsererror
2015-01-30 09:19:09.817 Alert[1253:353531] {"line":2,"column":2097,"sourceURL":"file:///private/var/mobile/Containers/Bundle/Application/D1746CD9-C9B3-4A31-9965-E4A6AAED3347/Alert.app/www/js/jquery-2.1.3.min.js"}
Here is my AJAX Post request.
function pushToDataLog(beaconid, uuid, timestamp, status)
{
jQuery.ajax({
type: "POST", // HTTP method POST or GET
url: "http://url.co.uk/ips/pushdata.php", //Where to make Ajax calls
dataType:"jsonp", // Data type, HTML, json etc.
jsonp: "callback",
data : {beaconid: beaconid, uuid: uuid, timestamp: timestamp, status:status},
crossDomain: true,
contentType: 'application/json',
success:function(response){
//console.log(JSON.stringify(response));
},
error:function (xhr, ajaxOptions, thrownError){
console.log(xhr);
console.log(ajaxOptions);
console.log(thrownError);
}
});
}
I dont understand what is causing the parse error..
EDIT
Here is my PHP file stored on the server:
<?php
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest') {
$beaconid = NULL;
$entertimestamp= NULL;
$exittimestamp = NULL;
//GET THE VARIABLES FROM JAVASCRIPT
if(isset($_REQUEST['beaconid'])){
$beaconid = $_REQUEST['beaconid'];
}
if(isset($_REQUEST['uuid'])){
$uuid = $_REQUEST['uuid'];
}
if(isset($_REQUEST['timestamp'])){
$timestamp = $_REQUEST['timestamp'];
}
if(isset($_REQUEST['status'])){
$status = $_REQUEST['status'];
}
define('DB_SERVER', 'a');
define('DB_USER', 'a');
define('DB_PASSWORD', 'a');
define('DB_DATABASE', 'a');
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$mysqli) {
trigger_error('mysqli Connection failed! ' . htmlspecialchars(mysqli_connect_error()), E_USER_ERROR);
}else{
print '<p>Database Connected!</p>';
}
//if( isset($name) && $name != '' ){
$stmt = $mysqli->prepare("INSERT INTO a(BeaconID,UUID,Timestamp,Status) VALUES (?, ?, ?, ?)");
if ($stmt === false) {
trigger_error('Statement failed! ' . htmlspecialchars(mysqli_error($mysqli)), E_USER_ERROR);
}
$bind = mysqli_stmt_bind_param($stmt, "isii", $beaconid, $uuid, $timestamp, $status);
if ($bind === false) {
trigger_error('Bind param failed!', E_USER_ERROR);
}
$exec = mysqli_stmt_execute($stmt);
if ($exec === false) {
trigger_error('Statement execute failed! ' . htmlspecialchars(mysqli_stmt_error($stmt)), E_USER_ERROR);
}
printf ("New Record has id %d.\n", mysqli_insert_id($mysqli));
//CLOSE THE SQL QUERY/STATEMENT
mysqli_stmt_close($stmt);
$json = json_encode("Success");
echo $_GET['callback'].'('.$json.')';
//}
mysqli_close($mysqli);
}
?>
With the help of #briosheje I managed to solve this issue. In case anyone has a similar problem in the future here is how I solved it:
The problem AJAX request was fine, the issue was in the PHP file on the server. To solve this I sent a json encoded array back containing success / failure messages.
Here is the full php file:
<?php
$beaconid = NULL;
$uuid = NULL;
$timestamp = NULL;
$status = NULL;
//GET THE VARIABLES FROM JAVASCRIPT
if(isset($_REQUEST['beaconid'])){
$beaconid = $_REQUEST['beaconid'];
}
if(isset($_REQUEST['uuid'])){
$uuid = $_REQUEST['uuid'];
}
if(isset($_REQUEST['timestamp'])){
$timestamp = $_REQUEST['timestamp'];
}
if(isset($_REQUEST['status'])){
$status = $_REQUEST['status'];
}
/*$beaconid = 1;
$uuid = "1213sdfdsdf";
$timestamp = 3424;
$status = 1;*/
define('DB_SERVER', 'xxx');
define('DB_USER', 'xxx');
define('DB_PASSWORD', 'x');
define('DB_DATABASE', 'x');
if($beaconid != '' && $uuid != '' && $timestamp != '' && $status != ''){
$mysqli = mysqli_connect(DB_SERVER, DB_USER, DB_PASSWORD, DB_DATABASE);
if (!$mysqli) {
trigger_error('mysqli Connection failed! ' . htmlspecialchars(mysqli_connect_error()), E_USER_ERROR);
$arr = array ('state'=>'connection failed');
}else{
$stmt = $mysqli->prepare("INSERT INTO datalog(BeaconID,UUID,Timestamp,Status) VALUES (?, ?, ?, ?)");
$arr = array ('state'=>'data pushed to the datalog');
if ($stmt === false) {
trigger_error('Statement failed! ' . htmlspecialchars(mysqli_error($mysqli)), E_USER_ERROR);
$arr = array ('state'=>'statement failed');
}
$bind = mysqli_stmt_bind_param($stmt, "isii", $beaconid, $uuid, $timestamp, $status);
if ($bind === false) {
trigger_error('Bind param failed!', E_USER_ERROR);
$arr = array ('state'=>'build param failed');
}
$exec = mysqli_stmt_execute($stmt);
if ($exec === false) {
trigger_error('Statement execute failed! ' . htmlspecialchars(mysqli_stmt_error($stmt)), E_USER_ERROR);
$arr = array ('state'=>'statemente execute failed');
}
}
$arr = json_encode($arr); //response send to the app
echo $_GET['callback'].'('.$arr.')'; //need this to prevent parsererror
//CLOSE THE SQL QUERY/STATEMENT
mysqli_stmt_close($stmt);
mysqli_close($mysqli);
}
?>

Categories

Resources