I am trying to make an Ajax request and get the data from a PHP file; that is, a single row based on a where condition. I don't know how to extract the PHP array in JavaScript.
My Ajax code:
function loadData(Sno)
{
$.ajax({ //create an ajax request to
type: "GET",
url: "php/getgreetings.php?loadsno=" + Sno,
dataType: "json", //expect html to be returned
success: function(data){
response = jQuery.parseJSON(data);
alert (response.Greet_Name);
}
});
}
My PHP code:
require('db.php');
$loadsno = $_GET['loadsno'];
$query = "SELECT * from Greetings where greetsno=".$loadsno ;
$result = sqlsrv_query($conn,$query);
$data = array();
while ($row = sqlsrv_fetch_array($result))
{
$data[] = $row;
}
echo (json_encode($data));
Related
I am using AJAX and trying to return variables that I got after querying the database in the modcomp.php file, I am then trying to input those values back into my main site to put into input boxes. Below is what I have tried but it is not working. Is this because I am getting variables in PHP and then bringing them back to use in JS / jQuery? Doing a few searches it looks like JSON might be the answer but looking at JSON I havent seen an example of how I could run code to query the database and then put that info in JSON format to pull back? My goal is to eventually pull back all 10 variables.
$.ajax({
method: "POST",
url: "modcomp.php",
data: {item: $(this).val()}
success: function(data) {
$('#itemnumber').val($itemnumber);
$('#cost').val($cost);
}
});
The modcomp.php file
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
$id=$row[0];
$itemnumber=$row[1];
$itemname=$row[2];
$cost=$row[3];
$company=$row[4];
$contact=$row[5];
$address1=$row[6];
$address2=$row[7];
$phone=$row[8];
$part=$row[9];
//print_r ($id." ".$itemnumber." ".$itemname." ".$cost." ".$company." ".$contact." ".$address1." ".$address2." ".$phone." ".$part);
} else {
print_r("Issue with query");
}
}
?>
The easiest way to do that is just set your jquery.ajax to expect a json as return:
$.ajax({
method: "POST",
dataType: "JSON",
/** others attributes **/
After, convert your return to a json and print it (just it, nothing more) at php script:
//a better approach is return the column name (fetch_assoc)
echo json_encode($row);
Now, your return can be used as json:
success: function(data) {
data.column_name
}
json_encode is the answer
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
$array = ();
$array['id']=$row[0];
$array['itemnumber']=$row[1];
$array['itemname']=$row[2];
.
.
$array['part']=$row[9];
$array['status'] = true;
echo json_encode($array);
} else {
echo json_encode(array(status => false , msg => "Issue with query");
}
}
Then in your js code use json as
$.ajax({
method: "POST",
url: "modcomp.php",
data: {item: $(this).val()}
success: function(data) {
data = JSON.parse(data); // to parse json string to object
if(data.status){
$('#itemnumber').val(data.itemnumber);
$('#cost').val(data.cost);
}
}
});
you should return your value from your php file as
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
return json_encode($row,true);
} else {
return json_encode("Some error occured");
}
}
don't use print_r() function to return data from your php file
And set the datatype in ajax as JSON to parse the json data to be returned as
$.ajax({
method: "POST",
url: "modcomp.php",
datatype:'json',
data: {item: $(this).val()}
success: function(data) {
$('#itemnumber').val(data.itemnumber);
$('#cost').val(data.cost);
}
});
Now you are able to use your json data using the dot(.) operator like
$('#cost').val(data.cost);
I really don't know what i'm missing here. I have this script:
<script type="text/javascript">
function ServiceOffer(){
var service_name = $('#service_name').val(),
dataString = "service=" + service_name;
$.ajax({
type: "POST",
url: "posted.php",
data:dataString,
success:function(data){
console.log(data);
}
});
}
$(document).ready(function(){
ServiceOffer();
$(document).on('change','#service_name',function(){
ServiceOffer();
});
});
</script>
And here is my code for posted.php
<?php
$connect = mysql_connect('localhost','root','') or die('Unable to connect'.mysql_error());
$select = mysql_select_db('hcs',$connect) or die('Unable to select database'.mysql_error());
$service = $_POST['service'];
$query = mysql_query("SELECT * FROM serviceoffer WHERE servicename = '$service'");
$num = mysql_num_rows($query);
while($rows = mysql_fetch_array($query)){
$data[] = $rows;
}
echo json_encode($data);
So what i'm missing? I don't think there is a string that is being attached in my code and it gives me string in my console and not json encoded data. Please Help! Thanks!
Edit: Here is the data that is being returned in my console.
You have three options:
Add dataType: 'json' to the options in $.ajax.
Add header("Content-type: application/json"); to the PHP code.
Use console.log($.parseJSON(data)) in the success function.
Note that you shouldn't use option 3 if you've also used options 1 or 2. jQuery automatically parses the JSON in the first two cases, and you'll try to parse the result of that, which won't work.
At a minimum, you should send the appropriate header in PHP, eg
header('Content-type: application/json');
echo json_encode($data);
exit;
You can also set the dataType in jQuery's $.ajax method to specify the expected response type. I also find it easier to send request parameters as object literals (saves having to build URL encoded strings), eg
$.ajax({
type: 'POST',
dataType: 'json',
data: { service: service_name },
//etc
Update
As shirejedi mentioned, you should initialise $data as an array
$data = array();
while($rows = mysql_fetch_array($query)){
$data[] = $rows;
}
I tried until this morning to retreive data from Mysql and ajax.
This is my code :
HTML :
$.ajax({
//type:'GET',
url: "/lecture_message_pilote.php",
data: ({location_id:zlid}),
contentType: "application/json; charset=utf-8",
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
var zidpilote = data[0]; //get id
var zmessage = data[1]; //get name
alert(zmessage);
}
});
And PHP :
$result = mysql_query("select * from Test_phoneGAP_message where IDPILOTE = '".$location_id."'");
$array = mysql_fetch_row($result);
echo (json_encode($array));
mysql_close();
I've the error message : UNDEFINED for alert(zmessage);
If I use the PHP request :
$result = mysql_query("select * from Test_phoneGAP_message");
I have a good result. I think my PHP don't take the $location_id.
try to access the parameter via the $_REQUEST["location_id"] element of php.
i.e.
$result = mysql_query("select * from Test_phoneGAP_message where IDPILOTE = '".$_REQUEST["location_id"]."'"); $array = mysql_fetch_row($result);
I've been trying to find an answer for this for hours but really struggling.
I have a simple jquery Ajax function which sends data to a PHP script. The data is then used to conduct a MySQL query and the results are included as an array. I'm sending the array back using json_encode but can't work out how to display the array at the other end. I've posted the code below. The console.log is displaying Object {modules: Array[0]}
. There should be 3 entries in the array.
The PHP
<?php
include_once('../../dbconnect.php');
$name = $_POST['uploadname'];
$query = "SELECT * FROM marking_assignments WHERE name = '$name'";
$details = $conn->query($query);
$modules = array();
while ($row = $details->fetch_assoc()){
$modules[] = $row['unit'];
}
$dataarray = array("modules"=>$modules);
echo json_encode($dataarray);
?>
The jQuery
var uploadname;
$("#uploadname").blur(function(){
uploadname = $(this).val();
$.ajax({
url: "uploadnames.php",
type: "POST",
data: {uploadname: uploadname},
dataType: 'json',
success: function(data){
console.log(data);
}
});
});
you should use:
var parsedData = jQuery.parseJSON(data);
and then:
console.log(parsedData)
I have jQuery Ajax request that sends data to a PHP page that then insert a record into MySQL.
With my current setup, this all works fine.
However, as part of the PHP script, i use mysql_insert_id() to retreive the ID of the last record.
I need the Ajax Success function to return this ID value as a javascript variable.
PHP Code
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$LastID = array('LastID' => mysql_insert_id());
$LastID = json_encode($LastID);
}
Javascript
$.ajax({
type: "GET",
url: "AddFunction.php",
data: {"Ajax":"1", "Data":"Test"},
dataType: "json",
success: function(data) {
var LastID = data;
alert(LastID);
}
});
I've read of using PHP's json_encode to create a JSON object and then pass that back, but i've had no luck.
How can i return this value?
just use
echo $LastId;
to send a response.
If you pass only one value you dont need JSON:
PHP Code
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$LastID = mysql_insert_id();
echo $LastID;
}
Javascript
$.ajax({
type: "GET",
url: "AddFunction.php",
data: {"Ajax":"1", "Data":"Test"},
dataType: "text",
success: function(data) {
var LastID = data;
alert(LastID);
}
});
with JSON:
PHP Code
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$jsonArray= array('LastID' => mysql_insert_id()); //*1 value is named LastID
echo json_encode($jsonArray);
}
Javascript
$.ajax({
type: "GET",
url: "AddFunction.php",
data: {"Ajax":"1", "Data":"Test"},
dataType: "json",
success: function(data) {
var LastID = data["LastID"];//use the same name as above (*1)
alert(LastID);
}
});
Maybe it is because your LastID is in array so the resulting object would be a JS array.
If you just need the ID don't use JSON encode and just pass the ID in Javascript.
So in PHP:
if ($_GET['Ajax'] == 1) {
$insert_statement = "INSERT INTO ...";
$insert = mysql_query(...);
$LastID = mysql_insert_id();
echo $LastID;
}