My AJAX seems like not working. It should load patient details into a dropwdown.
this is my ajax code:
function PopulatePatient()
{
$("#PatientDropDown").empty();
$("#PatientDropDown").append("<option>Loading.....</option>");
$.ajax({
type:"POST",
url:"../listener/populatePatientName.php",
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(data){
$("#PatientDropDown").empty();
$("#PatientDropDown").append("<option value=''>-Select Patient-</option>");
$.each(data,function(i,item)
{
$("#PatientDropDown").append('<option value="'+ data[i].patientUserId +'">'+ data[i].patientFirstName +'</option>');
});
},
complete: function()
{
}
});
}
This is my PHP Code (populatePatientName.php):
<?php
include '../core/init.php';
$sql = mysql_query("SELECT patientUserId,patientFirstName FROM patientdetails");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[]=array
(
'patientUserId' => $row['patientUserId']
'patientFirstName' => $row['patientFirstName']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
This is my HTML Code:
<select class="form-control" id="PatientDropDown">
</select>
This code works in my friend PC. My database and query are running well. Table contained data.
My code stop at this point :
$("#PatientDropDown").append("Loading.....");
It does not enter ajax. Any solution?
try this line before $.each() function in ajax success
data= JSON.parse(data);
Use "GET" instead of "POST" into your ajax type.
Your script is absolutely fine, but you do not have any event which will trigger PopulatePatient() function. Run the function to get data. Use console.log(data) to check whether your php is sending data or not.
Try to go to populatePatientName.php using web browser, it should return JSON data
I found the solution, I forgot the comma,
<?php
include '../core/init.php';
$sql = mysql_query("SELECT patientUserId,patientFirstName FROM patientdetails");
if(mysql_num_rows($sql))
{
$data=array();
while($row=mysql_fetch_array($sql))
{
$data[]=array
(
'patientUserId' => $row['patientUserId'],
'patientFirstName' => $row['patientFirstName']
);
}
header('Content-type: application/json');
echo json_encode($data);
}
?>
$data[]=array
(
'patientUserId' => $row['patientUserId'],
'patientFirstName' => $row['patientFirstName']
);
Two questions:
- It is included jquery in head tag like this?
<script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
- To populate try using a button like:
<input type="button" onClick="populatePatient()" />
Related
I am making an ajax call using jquery to post data as json to a php file, however nothing is happening on success. My code is below :
AJAX section
$.ajax({
url:"myData.php",
dataType: 'json',
method:"POST",
data:'country',
success:function(j){
var $country = $("#country");
$.each(j, function () {
$country.append($('<option></option>').attr("value", this.country_id).text(this.country_name));
});
}
});
PHP section
if(isset($_REQUEST['country'])){
$conn=new MySQLi("localhost","root","","newdb");
$myQuery="select * from country";
$result=$conn->query($myQuery);
while($country=$result->fetch_assoc()){
echo json_encode($country);
}
}
HTML section
<label >country:</label>
<select class="form-control" id="country" >
<option>---select---</option>
</select>
You need to collect all countries in array then echo json.
$countries = [];
if(isset($_REQUEST['country'])){
$conn=new MySQLi("localhost","root","","newdb");
$myQuery="select * from country";
$result=$conn->query($myQuery);
while($country=$result->fetch_assoc()){
$countries[] = $country;
}
echo json_encode($countries);
}
Also in js send country as parameter.
...
method:"POST",
data: {country : true},
...
I really have never done this before and I am getting frustrated because I'm not sure how it fits together. I have a function that I want to call my php (one php file selects info from a database and the second inserts into the database)... I need to use ajax in the way my site is setup but I don't know how to pass data from and to the php files.
In first .js file:
q1LoadVar();
This is my ajax function in second .js file that I have so far (not working):
//ajax code has been edited here since original post:
function q1LoadVar() {
alert("called"); //works!
$.get( "q1LoadVar1.php", function( data ) {
console.log(data); //nothing happens!
// alert(data); //nothing happens!
}, "json" );
}
And here is the code I have in q1LoadVar1.php that I want to select data back from and be able to populate a text area in my html:
/*works when I type this file path directly into the url;
but the file is not communicating back to the ajax function on the
.js file that is calling it*/
<?php
$config = parse_ini_file('../config.ini');
$link = mysqli_connect('localhost',$config['username'],$config['password'],$config['dbname']);
if(mysqli_connect_errno()){
echo mysqli_connect_error();
}
echo '<script type="text/javascript">alert("working from php!");</script>';
$query = "SELECT * FROM Game1_RollarCoaster";
$result = mysqli_query($link, $query);
while ($row = mysqli_fetch_array($result)) {
$newRow[] = $row;
}
$json = json_encode($newRow);
echo $json; //works on php file directly!
/*while ($row = mysqli_fetch_array($result)) {
echo $row[Q1_AnswerChoosen];
}*/
mysqli_free_result($result);
mysqli_close($link);
?>
Can someone help me understand how to make this all work together? Thank you, Kristen
You can retrieve post data from ajax in php with
$_POST['action']
//in your case will return: test
To return data to ajax you need to use echo
If the success: callback function doesnt get called try to remove datatype: 'json'
I also think that you need to echo $newrow instead of $row.
If this still doesnt work you can catch the error with the error: callback function to see what is wrong.
Try to start with a simple request and work from there.
$(document).ready(function() {
$.ajax({
type: "POST",
url: "yourphp.php",
data: {simplestring: "hi"},
success: function(result){
alert(result);
}
});
});
and yourphp.php
<?php
$simplestring = $_POST['simplestring'];
echo $simplestring;
I really like the help here and normally i figured out any Problem so far just by reading the existing Posts. However this time i can't quiet figure out whats wrong in my code.
I want to write dataildata values of a specific Tablerow in a form. The Data is stored in an mysql database and I access it with php.
The Probleme is that it seems that the Ajax request isn't working. neighter the success nor the error Event get triggered. Although the alter(id) works just fine.
Here is the Ajax call of the function:
$( "#table1 tbody tr" ).on( "click", function() {
var id = $(this).attr('id');
alert( id );
$.ajax({
type: 'POST',
url: 'getDetailData.php',
dataType: 'json',
data: {id : id },
success: function(data){
$("#inputWstId").val(data.WST-ID);
$("#inputSerialNumber").val(data.SERNO);
$("#inputName").val(data.NAME);
alert(data.NAME);
alert ("Test");
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
and here is the .php File:
<?php
header('Content-Type: application/json');
$connect = include 'connect.php';
if (isset ($_POST['id'])){
$id= $_POST['id'];
}
$query = " select * FROM pci WHERE id= ". $id ;
$result = mysql_query($query);
$ligne = mysql_fetch_array($result);
$data = array(
"WST-ID" => $ligne["WST_ID"],
"SERNO" => $ligne["SERNO"],
"NAME" => $ligne["NAME"]
);
mysql_close($connect);
echo (json_encode($data));
?>
If you Need more sourcecode or anything else just let me know- Thank you so much for your help!!
WST_ID instead of WST-ID really worked - thank you so much !!
Why is it, that I can't use a "-" in my values ... guess there is a lot more to learn ;)
In the PHP part you need add two more headers :
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
Add the two line of coding with the:
header('Content-Type: application/json');
change the:
echo (json_encode($data));
to:
print $my_json = json_encode($data);
or:
print_r ($my_json);
Hope it will work.
I think you need to give absolute url. Only getDetailData.php will not work. Try http://xyzabc.com/getDetailData.php
I want to fetch data from mysql, and echo it by a json_encode. then my JQUERY will catch JSON via $.getJSON and append the result into my <ul>.
im trying to figure out why the data being captured by JQUERY is not printing on my index.php
this is my index.php
<html>
<?php
include_once('connect.php');
$sql = "SELECT * FROM data";
$query = mysql_query($sql);
$result = array();
while($row = mysql_fetch_array($query))
array_push($result,
array(
'name' => $row[1],
'msg' => $row[2]));
echo json_encode(array("key" => $result));
?>
<body>
<ul>
//insert fetch data here
</ul>
<script type="text/javascript" src="./js/jquery.js"></script>
<script type="text/javascript" src="./js/custom.js"></script>
</body>
</html>
and here is my JQUERY
function my_function() {
$.getJSON("index.php", function(data) {
$.each(data.key, function(){
$("ul").append("<li>Name: "+this['name']+"</li>"
"<li>message: "+this['msg']+ "</li>");
});
});
}
You don't need to fetch your data via JSON as you're echo-ing the JSON on the same page.
you could do something like this:
<ul id="jsonData" data-json-data="<?php echo json_encode($result;)?>"
And in your js file:
var myData = $('#jsonData').data('json-data');
first: check your index.php output by itself to see if it's displaying valid json. ¿Are there invalid UTF8 characters? In that case json_encode's output is null.
second: I'd use plain ajax method hinting json as dataType:
jQuery.ajax({
url: 'index.php',
dataType: 'json'
}).done(function(data) {
for (i=1;i<data.length;i++) {
datarow=data[i];
$("ul").append("<li>Name: "+datarow.name+"</li>");
$("ul").append("<li>message: "+datarow.msg+ "</li>");
}
});
third: don't use the same script to generate the json and to display it, it makes no sense to decouple view from app if you do it all in the front. In that case you might as well use plain php to generate it all, as the previous answer told. (#Abdoul Sy)
I have an AJAX call on txt_RollNo's blur event to bring std_name,Class,age from database and fill it in txt_name,txt_class,txt_age.
In a single call can I have name,class,age all as a whole in array or any, how to seperate it.
$("#txt_RollNo").blur(function(){
$.ajax({
url:'getSudent.php',
data:'stdID='+ $(this).val().trim(),
success:function(array_from_php)
{
//but here i m receiving php array, how deal in jquery
//$("#txt_name").val(array_from_php);
//$("#txt_Class").val(array_from_php);
//$("#txt_age").val(array_from_php);
}
})
});
getSudent.php echos array as below
<?php
$qry=mysql_query("select * from students where studentID='".$_GET['std_ID']."'");
$row=mysql_fetch_array($qry);
echo $row;
?>
PHP:
<?php
header('Content-type: application/json');
$qry=mysql_query("select * from v_shop where shop_no='".$_GET['shopno']."'");
$row=mysql_fetch_array($qry);
echo json_encode($row);
?>
JavaScript
...
$.ajax({
dataType: 'json',
...
success:function(array_from_php){
console.log(array_from_php); // WTF is this?
See json_encode : http://php.net/manual/en/function.json-encode.php
First in php send it as json:
echo json_encode($row);
then just treat it as any array:
$("#txt_RollNo").blur(function(){
$.ajax({
url:'getSudent.php',
data:'stdID='+ $(this).val().trim(),
dataType : 'json',
success:function(array_from_php)
{
// i suggest you output the array to console so you can see it
// more crearly
console.log(array_from_php);
$("#txt_name").val(array_from_php[0]);
$("#txt_Class").val(array_from_php[1]);
$("#txt_age").val(array_from_php[2]);
}
})
});