Ajax php jquery - php

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

Related

AJAX SQL JSON Not Working

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()" />

ajax and php: how to select variables from database and insert in database using ajax

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;

how to get the values from php to javascript variable is it possible

this is my php script from which am returning the value to the ajax calling it
<?php
$questionid=$_GET['qid'];
$answer=$_GET['clickedvalue'];
$dbconnect=mysqli_connect('localhost','root','','quiz')or die("Error Connecting to database");
$query="select answer from question_answer where id=$questionid";
$result=mysqli_query($dbconnect,$query);
while($rows=mysqli_fetch_array($result))
{
$dbanswer=$rows['answer'];
}
//array values which will be passed to json
$result=array('correct'=>'Correct Answer',
'incorrect'=>'Incorrect Answer'
);
if($dbanswer==$answer)
{
//json to be passed to next page with key value pair
echo json_encode(array('display_msg'=>$result['correct'],'points'=>'positive'));
}
else{
echo json_encode(array('display_msg'=>$result['incorrect'],'points'=>'negative'));
}
?>
and this is my ajax code
$.ajax({
url:'checkanswer.php',
dataType:'json',
data:{'clickedvalue':clickedvalue,'qid':qid},
success:function(data){
$this.find(".report").html(data.display_msg);
$this.delay(1000).slideUp();
}
});
So my question is how do i store the value of data.points object that is passed from the php as a json in the javascript variable or is it not possible to store in javascript variable directly if yes how and if no what will be the way to get the value and store somewhere
Just add a temp variable before calling ajax
Some thing like this
var myTempVariable; //Temp JS variable to use somewhere else
$.ajax(
{
url: 'checkanswer.php',
dataType: 'json',
data:
{
'clickedvalue': clickedvalue,
'qid': qid
},
success: function(data) {
$this.find(".report").html(data.display_msg);
$this.delay(1000).slideUp();
myTempVariable = data; //assugn value to temp varaible
}
});
in your ajax success function :
var myVariable = data.points;
This might help

Storing values in a database via AJAX not working

I have this function which uses ajax, but this function doesn't work. I tried a lot, but I'm not able to figure out where the problem is. I am trying to create an alert, when the user inserts a duplicate entry into the database using a check-box selection.
<script>
function func(e,eid,emprid) {
if(document.getElementById(e).checked){
var dataString = 'eid=' + eid + '&emprid='+emprid;
$.ajax({
type:"POST",
url: "mylistcheck.php",
data: dataString,
success: function(result){
if(result!='0') {
modal.open({content: "<span style=\"color:red\" ><h2>You have already selected candidate </h2></span>"});
document.getElementById(e).checked=false;
}
}
});
}
}
</script>
mylistcheck.php looks like this:
<?php require_once("includes/session.php"); ?>
<?php require_once("includes/connection.php"); ?>
<?php require_once("includes/functions.php"); ?>
<?php
$eid=$_POST['eid'];
$emprid=$_POST['emprid'];
$sqlchecklist="SELECT * FROM selected_candidate WHERE eid='{$eid}' AND rid='{$emprid}' ";
$checklistres=mysql_query($sqlchecklist);
$list_check=mysql_num_rows($checklistres);
echo "numrows listcheck".$list_check;
if($list_check>0) {
echo "1";
} else {
echo "0";
}
?>
The check-box code is like this:
echo "<td><input id=\"select_candi{$i}\" onclick=\"javascript:func(this.id,{$data_set['eid']},{$emprid})\" type=\"checkbox\" name=\"check_candi[]\" value=\"{$data_set['eid']},{$emprid}\"/></td>";
In your code you have
echo "eid".$eid;
$emprid=$_POST['emprid'];
echo "rid".$emprid;
Since you are already echoing the result your ajax functie will never be just '0'. Its always something like eid{value}rid{value}0 or eid{value}rid{value}1
Also switch to mysqli or pdo for security reasons. Also check the values of $eid and $rid to match what you expect. Your code is vulnerable for SQL injection.
In your script code you have onclick="javascript:func(...)". onclick is already a javascript function, so you dont need the javascript:
You are sending a POST request but the data is sent in GET form - i.e a string. You need to send it as an object instead:
$.ajax({
type:"POST",
url: "mylistcheck.php",
data: {"eid":eid,
"emprid":emprid}, // send an object
success: function(result){
if(result!='0')
{
modal.open({content: "<span style=\"color:red\" ><h2>You have already selected candidate </h2></span>"});
document.getElementById(e).checked=false;
}
}
});

How to send a json string back to jquery

I need to send some data to an external php page and that page has to send the required data back to jQuery. My question is how can I send the data from the external page back to jQuery on the page that send it.
This is the jQuery code that sends the data to the external page:
function LoadImageData(url)
{
$.ajax({
url: 'get_image_data.php',
dataType: 'json',
data: {'url': url },
success: SetTag()
});
}
This is the PHP code htat receives the data and is required to send some data back:
<?php
require_once('FaceRestClient.php');
$apiKey = '**********************';
$apiSecret = '**********************';
$api = new FaceRestClient($apiKey, $apiSecret);
$active_url = $_POST['url'];
$photos = $api->faces_detect($active_url);
return $photos;
?>
So my problem is, how can I send the data backto jQuery. Just a simple return does not seem to work.
Thanks in Advance,
Mark
You need to echo the resulting JSON:
echo $photos;
If $photos is not already JSON, use json_encode:
echo json_encode( $photos);
One would think the REST API would give you JSON, but you need to check if it's valid JSON (JSONP is not valid here) ?
You could just drop the dataType in your Ajax function and let jQuery figure it out, that way atleast you'll get something back if it's not valid JSON.
Try this:
$.ajax({
url: 'get_image_data.php',
type: 'POST',
data: {'url': url }
}).done(function(data) {
console.log(data);
}).fail(function() {
console.log('Your ajax just failed');
});
Open the console, and see what is printed
At the end of a PHP function I tend to do :
exit(json_encode($someData));
To return the data as JSON, but anything that prints the data is ok.
try this
echo json_encode( $photos);
you need to echo
echo $photos;
and as metntoned by #nickb if $photo is not already a json then convert it into json first and then echo.
echo json_encode($photos)
in jQuery if you want to fetch the data
onSuccess: function(data, status) {
//var data contains the returned json.
}

Categories