Retrieving POST Data from AJAX Call to PHP - php

Three days had passed and still having problems to get this things work.
This AJAX Call on my js file seems working when it comes to sending JSON data:
var _lname = $('#ptLastName').val();
var _fname = $('#ptFirstName').val();
var _mname = $('#ptMiddleName').val();
var _gender = $('#ptGender').val();
var _bday = $('input[name="birthdate"]').val(); // $('#ptBirthDate').val();
var _ssn = $('#ptSSN').val();
$.ajax({
type: "POST",
url: ".././CheckPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var res = response.d;
if (res == true) {
jAlert('Person Name already exists!', 'Error');
return;
}
})
but in my PHP file:
$lastname = json_decode($_POST['lastName']);
$firstname = json_decode($_POST['firstName']);
$middlename = json_decode($_POST['middleName']);
$response = array();
mysql_connect ("*****", "****") or die ('Error: ' . mysql_error());
mysql_select_db ("********");
$query = "SELECT Lastname, Firstname, MiddleName FROM tbl_people WHERE Lastname = '$lastname' || Firstname = '$firstname' || MiddleName = '$middlename'";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
if ($row) {
$response = json_encode(array('d' => true, 'test' => $lastname));
}
else {
$response = json_encode(array('d' => false, 'test' => $lastname));
}
echo $response;
print json_encode($_POST);
some error from firebug console says:
<br />
<b>Notice</b>: Undefined index: lastName in <b>C:\xampp\htdocs\..\CheckPerson.php</b> on line <b>2</b><br />
<br />
<b>Notice</b>: Undefined index: firstName in <b>C:\xampp\htdocs\..\CheckPerson.php</b> on line <b>3</b><br />
<br />
<b>Notice</b>: Undefined index: middleName in <b>C:\xampp\htdocs\..\CheckPerson.php</b> on line <b>4</b><br />
{"d":false,"test":null}[]
i believe that json_decode() is working fine in my php file but $_POST[''] can't recognize my posted data from my ajax call w/c variables had been declared:
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
I believe I am doing right with my codes seems i had read many questions here and done what they had said but don't know why the error occurred.
Is there any problem/bug you had seen? please tell me.

Can you see the ajax request data using the firebug console?
You cannot get the lastname, firstname from $_POST. It's inside the json string. First, you have to get the data using
$data = $_POST['data'] or $_REQUEST['data']
Then, decode the $data using json_decode() and access your attributes.
json_decode($data);

$post = file_get_contents('php://input');

instead of this
data: "{'lastName':'" + _lname + "','firstName':'" + _fname +
"','middleName':'" + _mname + "'}",
use this
data: {lastName:_lname,firstName:_fname,middleName:_mname},

try with this solution
$lastname = isset($_POST['lastName'])?json_decode($_POST['lastName']):null; $firstname =isset($_POST['firstname'])?json_decode($_POST['firstname']):null; $middlename=isset($_POST['middlename'])?json_decode($_POST['middlename']):null;

Related

PHP 'Insert Into' Query Returning error result on Ajax

I php code that will insert into database but it always returns false even if it is inserting values into the database.
Here is my code: PHP
<?php
require_once 'connection.php';
if (isset($_POST['borrowBook']))
{
newBorrowRequest();
}
function newBorrowRequest()
{
$b_id = $GLOBALS['db']->real_escape_string($_POST['b_id']);
$userID = $GLOBALS['db']->real_escape_string($_POST['userID']);
$dateBorrowed = $GLOBALS['db']->real_escape_string($_POST['dateBorrowed']);
$remarks = $GLOBALS['db']->real_escape_string($_POST['remarks']);
$sql = "INSERT INTO `tbl_requestbook`(`b_id`, `userID`, `dateBorrowed`, `remarks`) VALUES ('$b_id','$userID','$dateBorrowed','$remarks')";
if($GLOBALS['db']->query($sql))
{
$GLOBALS['db']->close();
header("location:../../admin/Book-Items.php?r=success", true);
}
else
{
header("location:../../admin/Book-Items.php?r=failed", true);
}
}
>?
And here is my Ajax Code:
<script>
$("#borrowBook").click(function(event) {
var bookID = $("#bookBorrow").val();
var userID = $("#borrowBook").val();
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
$.ajax({
url: '../assets/php/functions-book.php',
type: 'POST',
data: {borrowBook: 'true', b_id: bookID, userID: userID, dateBorrowed: output, remarks: $("#remarks").val() },
success: function(result) {
window.location.reload();
},
error: function(result) {
//window.location.reload();
console.log(result);
}
});
});
</script
There is something wrong with the php query, it will not iterate with the condition thus, it will call the ajax error function.
[EDITED]
I solved this by changing 'header("location:../../admin/Book-Item.php?r=success");' to 'header("location:../../admin/Book-Items.php?r=success");'. It was a wrong call.
My problem now is, after success the header remains. It can't be replace by the new header that I want to change. I already changed the php code to the latest.

How to pass an array from PHP using AJAX

I'm having some issues displaying an array which I created in a PHP file. The response data in question is data["vessel"]
I have some jQuery:
j$('select[name=vessel]').change(function(e) {
var tour_ID = j$('select[name=tour]').val();
var trip_Date = j$('input[name=trip_Date]').val();
var data = {
"action": "Count_Vessels",
"trip_Date": trip_Date,
"tour_ID":tour_ID
};
data = j$(this).serialize() + "&" + j$.param(data);
j$.ajax({
type: "POST",
dataType: "json",
url: "../include/booking_Modify.php",
data: data,
success: function(data) {
//console.log("vessel stack: " + data["vessel"][0]);
var arr=JSON.parse(data["vessel"]);
console.log("vessel stack: " + arr[0]);
console.log("Form submitted successfully.\nReturned json: " + data["json"]);
},
error: function (request) {
console.log(request.responseText);
}
});
});
The PHP:
function count_Vessels(mysqli $conn, $trip_Date, $tour_ID){
$return = $_POST;
$vessel_Stack = array();
$vessel_Query = "SELECT * FROM Vessel";
if(!$vessel_Results = $conn->query($vessel_Query)){
die('There was an error running the query [' . $conn->error . ']');
}
while( $vessel_Row = $vessel_Results->fetch_assoc() ){
$vessel_Stack[$vessel_Row['ve_ID']] = $vessel_Row['vessel_Name'];
}
$return['vessel'] = $vessel_Stack;
$return["json"] = json_encode($return);
echo json_encode($return);
}
when I display data["json"] in console, I get Returned json: {"vessel":{"1":"Thriller","2":"Jammin","3":"Thunderstruck","4":"Wildthing","6":"Joyride"}
Which is awesome, but I don't know how to do that using the data["vessel"] Any help would be greatly appreciated.
I solved my own riddle. Because data["vessel"] is an array, I had to loop through it. Doing so like this worked:
j$.each(data["vessel"], function(key, val) {
console.log('index ' + key + ' value ' + val);
});

Return Values from PHP to JSON/AJAX

A friend of mine had given me this snippet for a js file that can be useful for me:
$.ajax({
type: "POST",
url: "../CheckPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var res = response.d;
if (res == true) {
jAlert('Patient Name already exists!', 'Error');
return;
}
else {
$.ajax({
type: "POST",
url: "../NewPerson.php",
data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "','gender':'" + _gender + "','birthDate':'" + _bday + "','ssn':'" + _ssn + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var _id = response.d;
if (_id.length != 0) {
$('#patientName').removeAttr('disabled');
$('#patientName').val(_lname + ", " + _fname + " " + _mname);
$('#patientId').val(_id[0].patientID);
$('#dateOfBirth').val(_bday);
$('#referringDoctor').removeAttr('disabled');
$('#referringDoctor').focus();
$('#patientAge').val(_id[1]);
$('#ptLastName').val('');
$('#ptFirstName').val('');
$('#ptMiddleName').val('');
$('#ptGender').val('');
// $('input[name="birthdate"]').val(); // $('#ptBirthDate').val();
$('#ptSSN').val('');
}
// if (_id == true) {
// }
insertCallback(_id);
// $('#diagnosis tbody>tr:last').attr('dinfo', '_IEDiagnosis|' + _id);
},
failure: function (msg) {
alert(msg);
}
});
}
}
});
I'm using PHP but I'm new to using JSON. Is there a way to return a true value for "response.d" in my PHP file:
success: function (response) {
var _id = response.d;
}
Here's my logic but don't know the code to use:
$lastname = isset($_REQUEST['lastName'])?$_REQUEST['lastName']:'';
$firstname = isset($_REQUEST['firstName'])?$_REQUEST['firstName']:'';
$middlename = isset($_REQUEST['middleName'])?$_REQUEST['middleName']:'';
$response = array();
mysql_connect ("localhost", "root") or die ('Error: ' . mysql_error());
mysql_select_db ("healthpal");
$query = "SELECT Lastname, Firstname, MiddleName FROM db_patients WHERE Lastname = '$lastname' || Firstname = '$firstname' || MiddleName = '$middlename'";
$qrytest = mysql_query($query);
if (isset($qrytest)) {
//"response.d" will be true if the query return not NULL
}
Try something like this:
header('Content-type: application/x-json');
echo json_encode( array( 'd' => true ) );
What you need is the php json_encode function:
json_encode(array('response'=>'true')));
You have to construct JSON string in your PHP file, some thing like this
{"result":"true"}
this constructed JSON string should return as PHP response. In Javascript parse the JSON as,
var obj = eval(response)
if(obj.result == 'true'){
//Do your code here
}

AJAX Post - One variable is not being sent properly

I have four variables I'm trying to pass via AJAX to be processed by some PHP on the same page: newJudgeName, newJudgeSection, newJudgeStatus, and originalJudgeName. The success function echos them out and they're the correct values, it's just the newJudgeStatus variable is not being picked up by my PHP. I've switched newJudgeStatus with newJudgeName in the data line on the AJAX request and then the value is sent just fine (I can see it in the db under Judge Name)... it's only when it's in the original spot in the ajax request that it doesn't work. I'm completely new to Ajax. Any help would be much appreciated.
AJAX:
$.ajax({
type: "POST",
url: "test.php",
data: 'newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus + '&originalJudgeName=' + originalJudgeName,
success: function(){
alert('newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName);
}
});
PHP:
if(isset($_POST['newJudgeName'])){
$newJudgeName = $_POST['newJudgeName'];
$newJudgeSection = $_POST['newJudgeSection'];
$newJudgeStatus = $_POST['newJudgeStatus'];
$originalJudgeName = $_POST['originalJudgeName'];
$judgeID = judgeNametoID($originalJudgeName);
$con = mysql_connect("-","-","-");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
else {
// connected to database successfully
}
mysql_select_db("cm", $con);
$query = ("UPDATE `casemanagers`.`judges` SET `Name`='$newJudgeName' , `Section`='$newJudgeSection', `Active`='$newJudgeStatus' WHERE `judgeID`='$judgeID';");
$result = mysql_query($query);
mysql_close($con);
}
You have an errant space in your data string:
'&newJudgeStatus =' + newJudgeStatus +
---------------^^^^
// Should be
'&newJudgeStatus=' + newJudgeStatus +
You should send the data this way:
$.ajax({
type: "POST",
url: "test.php",
data: {
'newJudgeName' : newJudgeName,
'newJudgeSection' : newJudgeSection,
'newJudgeStatus' : newJudgeStatus,
'originalJudgeName' : originalJudgeName
},
success: function(){
alert('newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName);
}
});
Instead of manual processing, I'll recommend to put all these inside a form & use following code to send data:
$('#id_of_the_form').serialize();
instead of buggy:
newJudgeName=' + newJudgeName + '&newJudgeSection=' + newJudgeSection + '&newJudgeStatus =' + newJudgeStatus +'&originalJudgeName=' + originalJudgeName ...
See http://api.jquery.com/serialize/

PHP Arrays - jQuery referencing issue

I have the following php:
1) echo json_encode(array('message' => 'Invalid Login Details: '.$user));
I also have the following:
2) $row = mysql_fetch_assoc($result);
echo(json_encode($row));
Now consider the following jQuery:
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
}
})
This succeeds for (1) but not for (2). This is obviously because jQuery expects a php response containing a message variable. (2) does not conform to this...I don;t know how to make this work as I am using different methods for creating the arrays...
How can I make $row in the php compatible with the data.message in the jQuery?
try:
$data = array();
$data["message"] = "Valid request";
$data["row"] = mysql_fetch_assoc($result);
echo(json_encode($data));
message = row:
$data = array();
$data["message"] = mysql_fetch_assoc($result);
echo(json_encode($data));
or two line solution (inspired by val):
$row = mysql_fetch_assoc($result);
echo(json_encode(array("message" => $row)));
Try
$row = mysql_fetch_assoc($result);
echo(json_encode(array('message'=>'I am the message','result'=>$row));
Then to answer your second question on the comments something similar to this could show the information ....
$.ajax({
type: "POST",
url: "get_login.php",
data: {username: getusername, password:getpassword, usertype:getusertype},
dataType: "json",
success: function(data) {
$("#message_ajax").html("<div class='successMessage'>" + data.message +"</div>");
var html = '';
for(var i = 0; i<data.result.length;i++){
html +='<div>'+data.result[i].fname+'</div>';
}
$('#result').html(html);
}
})
ofcourse you need to edit it abit where applicable .
i believe you don't have $row['message'] from mysql_fetch_assoc.
you have to explicitely define the message key on the array before json_encode.
$row = mysql_fetch_assoc($result);
$row['message'] = 'Hello '.$row['username'];
echo(json_encode($row));

Categories