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
}
Related
custom.js file:
$(document).ready(function() {
$("#company_name").keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost/capms_v2/ca_autocomplete/getcompanyName",
data: {
keyword: $("#company_name").val()
},
dataType: "json",
success: function(data) {
//alert(data);
if (data.length > 0) {
$('#DropdownCompany').empty();
$('#company_name').attr("data-toggle", "dropdown");
$('#DropdownCompany').dropdown('toggle');
} else if (data.length == 0) {
$('#company_name').attr("data-toggle", "");
}
$.each(data, function(key, value) {
if (data.length >= 0)
$('#DropdownCompany').append('<li role="displayCountries" ><a role="menuitem DropdownCompany" id=' + value['company_id'] + ' Address1=' + value['company_address1'] + ' Address2=' + value['company_address2'] + ' city=' + value['company_city'] + ' state=' + value['company_state'] + ' pincode=' + value['company_zip'] + ' class="dropdownlivalue">' +
value['company_name'] + '</a></li>');
});
}
});
});
$('ul.txtcountry').on('click', 'li a', function() {
$('#company_name').val($(this).text());
$('#company_id').val($(this).attr("id"));
// $('#company_address1').val($(this).text());
$('#tableCityID').html($(this).attr("id"));
$('#tableCityName').html($(this).text());
$('#Address1').html($(this).attr("Address1"));
$('#Address2').html($(this).attr("Address2"));
$('#city').html($(this).attr("city"));
$('#state').html($(this).attr("state"));
$('#pincode').html($(this).attr("pincode"));
});
});
I was getting id in span id="tableCityID" but if I store the value and pass the value to mysql it was not fetching the value
$com = '<span id="tableCityID">';
and if I echo the select query
echo $sql="select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '".$com."'";
I get the result with not completed single codes
select * from ca_job WHERE job_status!='Closed' AND job_customer_name = '15
If anybody faces this problem, please help me. Thanks in advance.
just use the </span>
like this
$com = '<span id="tableCityID"></span>';
My function seems to return nothing for the destination element when the link is referred to from Instagram. It works fine if I directly visit the page.
function getTeamsByLeague(league) {
//console.log("League Set: " + league);
$.ajax({
url: "<?php echo SITE_BASE_URL; ?>json.php",
data: {method: "getteamsbyregion", league: league},
success: function (data) {
if (data && data.length > 0) {
$("#destination").empty();
var selected = "";
$.each(data, function (index, item) {
if (item.team == teamSelected) {
selected = " selected";
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
} else {
selected = "";
}
$("#destination").append('<option ' + selected + ' value="' + item.lat + ',' + item.lng + '">' + item.team + '</option>');
if (index == 0) {
$("#latitude").val(item.lat);
$("#longitude").val(item.lng);
}
});
}
},
type: "GET",
dataType: "json"
});
}
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);
});
I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});
I need to extract the URL's from the php datas, how can i achieve this?
PHP
$query = 'SELECT * FROM picture LIMIT 3';
$result = mysql_query($query);
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url.=$rec['pic_location'].";";
}
echo json_encode($url);
Ajax
<script type="text/javascript">
$(document).ready(function() {
$(".goButton").click(function() {
var dir = $(this).attr("id");
var imId = $(".theImage").attr("id");
$.ajax({
url: "viewnew.php",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret);
var arr = ret;
alert("first: " + arr[0] + ", second: " + arr[1]);
alert(arr[0]);
$(".theImage").attr("src", +arr[0]);
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});
});
});
</script>
the alert message isn't working its just printing H T ( i think these are http://... )
You're returning a string which is not parsed as JSON.
Just add dataType: "json" to the ajax settings.
And since you're reading it as an array in your javascript you should return it like so:
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[] = $rec['pic_location'];
}
You are sending a string in your PHP and expecting an array as response in javascript. Change you PHP to
while ($rec = mysql_fetch_array($result, MYSQL_ASSOC)) {
$url[] = $rec['pic_location'];
}
And javascript to
$.ajax({
url: "viewnew.php",
dataType: "JSON",
data: {
current_image: imId,
direction : dir
},
success: function(ret){
console.log(ret[0]);
var arr = ret;
alert(arr);
alert("first: " + arr[0] + ", second: " + arr[1]); // THIS IS NOT WORKING!!!!
if ('prev' == dir) {
imId ++;
} else {
imId --;
}
$("#theImage").attr("id", imId);
}
});