AJAX Post - One variable is not being sent properly - php

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/

Related

Jquery Get Reqeust Not Displaying Data

Ok, I have two pages. getprofilecomment.php and getprofilecomment.js. The get getprofilecomment.php is functioning, but the getprofilecomment.js is not working for some reason. It is not displaying any content. The div id is correct. Here is the code:
$(function()
{
var userId = $(#userid).val();
$.ajax({
url: "api/getprofilecomment.php",
method: "GET",
data: userId,
cache: false,
success: function(comment){
$(#usercommentdiv).apprend('<li>' + comment.user_name + ':' + comment.profile_comment + ',' + comment.time_added + '</li>');
}
});
});
Once again, the json_encode is echoing the content successfully to the page.
<?php
include ("../db/database.php");
include ("../classes/profilecommentclass.php");
session_start();
$profileCommentHandler = new ProfileComment($db);
$userId = $_GET['userId'];
$profileComment = $profileCommentHandler->getComment($userId);
echo json_encode($profileComment, JSON_FORCE_OBJECT);
?>
Hi you are missing id (usercommentdiv) in quotes,
success: function(comment){
$('#usercommentdiv').apprend('<li>' + comment.user_name + ':' + comment.profile_comment + ',' + comment.time_added + '</li>');
}

Javascript vairables empty unless I debug code

I have a function which makes a ajax call and gets a list of vehicle make.
var car_make_list_target_id = 'car_make';
var make_year_list_select_id = 'years';
var car_model_list_target_id = 'car_model';function get_car_model(){
var car_model_initial_target_html = '<option value="">--Select Model--</option>';
//Grab the chosen value on first select list change
var selectvalue = $('#car_make').val();
alert('first alert ' + selectvalue);
var yearvalue = $('#' + make_year_list_select_id).val();
//Display 'loading' status in the target select list
$('#' + car_model_list_target_id).html('<option value="">Loading Car Models</option>');
if(selectvalue === ""){
//Display initial prompt in target select if blank value selected
$('#' + car_model_list_target_id).html(car_model_initial_target_html);
} else{
//Make AJAX request, using the selected value as the GET
$.ajax({
url: 'get_model.php?make=' + selectvalue + '&year=' + yearvalue,
success: function(output){
//alert(output);
$('#' + car_model_list_target_id).html(output);
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status + " " + thrownError);
}
});
}
I also have a php if loop to see is session isset. Now I want to display these values within the drop down list if the session is set.
if(isset($_SESSION['vehicle_info'])){
echo '<script>'
.'$("#states option[value=' . $_SESSION['vehicle_info']['state'] . ']").attr("selected","selected");'
.'$("#years option[value=' . $_SESSION['vehicle_info']['year'] . ']").attr("selected","selected");'
. ' $("#years").prop("disabled", false);'
. ' $("#car_make").prop("disabled", false);'
. ' $("#car_model").prop("disabled", false);'
. 'get_car_make();//This works'
. 'get_car_model();//This does not work unless I debug javascript'
. '</script>';
}
The issue is unless I set a breakpoint within the get_car_model on the following lines
var selectvalue = $('#car_make').val();
alert('first alert ' + selectvalue);
the var selectvalue is blank, but if I leave the breakpoint it will alert the value of the option and will display correctly. I have been beating my head for the last 4 hours and I have not been able to figure this out. Is this normal browser behavior or am I missing something? Any input will be great.

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);
});

Retrieving POST Data from AJAX Call to 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;

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
}

Categories