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'];
Related
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);
I want to write an Ajax request that Returns data from a MySQL-database. But it does not work properly, because the Ajax request does not return the current values of the mysql database, if data has changed. Instead it always returns the old data of the database. The php-file is working properly, if I open it in a browser, it shows the correct current data values. I found out, that the Ajax request only shows the correct current data values, if I first open the php-file manually in a browser. If I then again use the ajax request, it returns the correct current data. What am I doing wrong?
This is the code for the Ajax request:
var scannedTubes = (function() {
var tmp = null;
$.ajax({
async: false,
url: "ajaxtest.php",
success: function(response) {
alert("RESPONSE: " + response);
tmp = response;
},
error: function(jqXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
return tmp;
})();
The code of the ajaxtest.php file is the following:
<?php
$con = mysqli_connect("", "root");
if(mysqli_connect_errno()){
echo "FAIL: " . mysqli_connect_error();
}
mysqli_select_db($con, "multitubescan");
$queryStr = "SELECT code FROM scan WHERE row = 0 AND code <> 'EMPTY'";
$res = mysqli_query($con, $queryStr);
$num = mysqli_num_rows($res);
$scannedTubes = "";
while($data = mysqli_fetch_assoc($res)){
$scannedTubes = $scannedTubes . " " . $data["code"];
}
$scannedTubes = $num . " " . $scannedTubes;
mysqli_close($con);
echo $scannedTubes;
?>
I suppose data is cached by your browser.
Make the url unique:
url: "ajaxtest.php",
to
url: "ajaxtest.php?rnd=" + Math.random() ,
I have an unknown situation that AJAX request does not reach to the PHP server.
There is no error code in the Chrome browser, but it's not reaching the PHP GET method.
In my code
function GetLectureData(SID){
$.ajax({
url: "test.php",
dataType: "jsonp",
jsonpCallback: 'callback',
data: {"SID_key": SID},
Type: 'GET',
success: function(data) {
console.log('DB정보 접근성공- ', data);
if(data != null) {
for(var i=0; i<data.length;i++)
{
var flags=true;
lectrueInfo=data[i].classroom.split('-');
Lecture[i] = lectrueInfo[1];
Lecture[i] = Lecture[i].slice(1,4)+"호";
console.log(Lecture[i]+" "+count);
count++;
if(typeof Lecture[i]== "undefined")
{
break;
}
for(var j=0;j<i; j++)
{
if(Lecture[i]==Lecture[j])
{
flags = false;
}
}
if(flags == true)
{
Create(Lecture[i]);
}
}
}
},
error: function(xhr) {
console.log('실패 - ', xhr);
}
});
}
<?php
header('Content-Type: application/javascript;charset=UTF-8');
$user = 'hyumini';
$pw = 'hyu(e)mini';
$db = 'hyumini';
$host ='localhost';
$port = 3306;
$table = 'LectureSchedule';
$my_db = new mysqli($host,$user,$pw,$db,$port);
mysqli_query($my_db,"set names utf8");
if ( mysqli_connect_errno() ) {
echo mysqli_connect_errno();
exit;
}
$q=$_GET["SID_key"];
$callback = $_REQUEST['callback'];
$return_array = array();
$count = 0;
$rs = mysqli_query($my_db, "select DISTINCT LectureSchedule.classroom
from ConnectLecture JOIN LectureSchedule
ON ConnectLecture.SID = $q AND ConnectLecture.lectureID = LectureSchedule.lectureID");
while($data = mysqli_fetch_array($rs))
{
$array[] = $data;
}
$my_db->close();
$json_val = json_encode($array);
echo $callback."(".$json_val.")";
?>
this is my result
pending situation
I'm really wondering why this is occurring in this situation.
Click on that request in your result you show in network panel, the connection established and if request pending cause of Time To First Byte (TTFB)-> it means problem in php code,
Else if connection not established firstly then this request is in stole mode. which means few more request is in pending before this request. so this request will response after previous request complete.
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.
I do not understand because when the data were entered into the login are correct and I make this comparison response.success == "success" nothing happens, I check with firebug and the result is this:
Response
[{"ncontrol":"09680040","nombre":"Edgardo","apellidop":"Ramirez","apellidom":"Leon","tUser":"Admin","status":"success"}]
jQuery.ajax script to send data
// jQuery.ajax script to send json data to php script
var action = $("#formLogin").attr('action');
var login_data = {
ncontrol: $("#ncontrolLogin").val(),
password: $("#passwdLogin").val(),
is_ajax: 1
};
$.ajax({
type: "POST",
url: action,
data: login_data,
dataType: "json",
success: function(response)
{
**if(response.status == "success")** {
$("#status_msg").html("(+) Correct Login");
}
else {
$("#status_msg").html("(X) Error Login!");
}
}
});
return false;
And is PHP Script for processing variables from jQuery.ajax
$ncontrolForm = $_REQUEST['ncontrol'];
$passForm = $_REQUEST['password'];
$jsonResult = array();
$query = "SELECT * FROM users WHERE ncontrol = '$ncontrolForm' AND cve_user = SHA('$passForm')";
$result = mysqli_query($con, $query) or die (mysqli_error());
$num_row = mysqli_num_rows($result);
$row = mysqli_fetch_array($result);
if( $num_row >= 1 ) {
$_SESSION['n_control'] = $row['ncontrol'];
$_SESSION['t_user'] = $row['tUser'];
$jsonResult[] = array (
'ncontrol' => $row['ncontrol'],
'nombre' => $row['nombre'],
'apellidop' => $row['apellidop'],
'apellidom' => $row['apellidom'],
'tUser' => $row['tUser'],
'status' => 'success',
);
header('Content-Type: application/json');
echo json_encode($jsonResult);
}
You have an array, so do it this way:
if(response[0].status == "success") {
The object is the first item in the array.
EDIT:
Looking more closely at your PHP, it looks like you might be intending to loop through several rows in your query response and add them to your $jsonResult. Am I seeing it right?