How can I assign results from Ajax call into a variable?
I have a drop down list. when user make a choice. I want ajax to call a PHP page to find related data from server and auto fill that into an input field.
See below code
$(document).on('change','#dropdownchoiceid', function(){
$id = 1; // passing in some variable for php to use
$.ajax({
url: "../folder/getdata.php",
type: "POST",
data: {
'id' : $id
},
success:function(data){
$result = data;
console.log($result);
$('#inputid').val($result.column1);
$('#inputid2').val($result.column2);
}
});
The php is working. I get the result in a object that look like this
array(1) {
[0]=>
object(stdClass)#5 (4) {
["id"]=>
string(1) "2"
["column1"]=>
string(7) "20.0000"
["column2"]=>
string(14) "someinfo"
["column3"]=>
string(1) "1"
}
So I am trying to change the input field value with the datas I got from the server. but I get blanks in the console.log. I dont quite understand the code below. I tried it because I see this answer on stackoverflow for similar questions
success:function(data){
$result = data;
}
the PHP is
<?php
//Create class Object
$mProduct = new mProduct;
$id = $_POST['id'];
$result= $mProduct->getData($id);
the model PHP page is
public function getData($id){
$this->db->query("
SELECT
*
FROM rebate
WHERE id= :id
");
//bind
$this->db->bind(':id', $id);
//Assign Result Set
$result = $this->db->resultset();
return $result;
}
I hard-coded an array to match what your db methods returned, according to your var_dump,
in your PHP page:
$arr=(object) [ "id"=> "2", "column1"=>"20.0000", "column2"=>"someinfo", column3"=>"1" ];
$arr=array($arr);
//var_dump($arr);
echo json_encode($arr, JSON_FORCE_OBJECT);
Also, I suggest that use echo instead of print_r because
print_r will also show protected and private properties of objects with PHP 5.
See PHP Manual print_r
Initialize your $result variable and since it is an array with a single element
you must reference it that way:
$.ajax({
url: "getData.php",
type: "POST",
data: {
'id' : $id
},
dataType: "json",
success:function(data){
var $result = data; // var initialize
console.log($result);
$('#inputid').val($result[0].column1); //$result is an array
$('#inputid2').val($result[0].column2);
},
error:function(data){
window.alert("Something went wrong"+data.error);
}
});
You ask:
(Quote)...is the word data supposed to match the $result from my PHP page?
..data is the variable on the client side that the server response gets stored in
To receive data on front end, the PHP page has to print something, preferably in JSON format. Try this:
<?php
//Create class Object
$mProduct = new mProduct;
$id = $_POST['id'];
$result= $mProduct->getData($id);
print_r(json_encode($result));
I am OP answering my own question.
Get data from php array - AJAX - jQuery
after checking above post. here is the answer
so the final working code look like this
$(document).on('change','#dropdownchoiceid', function(){
$id = 1; // passing in some variable for php to use
$.ajax({
url: "../folder/getdata.php",
type: "POST",
data: {
'id' : $id
},
datatype: "json",
success:function(data){
$result = data;
console.log($result);
$('#inputid').val($result.column1);
$('#inputid2').val($result.column2);
}
});
in PHP
add one more line
echo json_encode($result);
Related
I have an AJAX request here:
var model = $("#variation").val();
var problem_id = $('input[name="problem"]:checked').val();
$.ajax({
type: "POST",
url: "../common/prices.php",
data: {model: model, problem_id: problem_id},
datatype: "json",
success: function (data) {
alert(data['bronze_price']);
},
error: function() {
alert("Error: Contact administrator");
}
});
and the end result is some sort of array.
console.log(data)
returns {"bronze_price":null,"silver_price":null,"gold_price":"249.00"}, by the way
This is the PHP code:
$query = "SELECT * FROM ext_product_price WHERE product_id='".$_POST['model']."' AND problem_id='".$_POST['problem_id']."'";
$result = mysqli_query($link, $query);
$row = mysqli_fetch_array($result);
die(json_encode(array("bronze_price"=> $row['bronze_price'], "silver_price"=>$row['silver_price'], "gold_price"=>$row['gold_price'])));
So, data['bronze_price'] returns "undefined" but when I remove all parameters it displays the array {"bronze_price":null,"silver_price":null,"gold_price":"249.00"}. I want to access each individual piece of data (bronze_price, silver_price, gold_price). All answers and comments would be greatly appreciated.
Set the following json header to return json with a valid content type
header('Content-Type: application/json');
die(json_encode(array("bronze_price"=> $row['bronze_price'], "silver_price"=>$row['silver_price'], "gold_price"=>$row['gold_price'])));
you can use the dot notation to get the values
alert(data.bronze_price);
make sure you are returning the correct json structure
It will be data.bronze_price. Others looking OK.
I'm creating my project using OOP. I need to pass all the values inserted in the database in the form of array. And it's a multidimensional array. SO when I pass now via ajax as a 'text' datatype it displays array in console.log(). But I'm unsure if this is the correct way and how to display the value in a table form in jquery.
Below are the functions where the values returned to the object in another page.
public function selectType()
{
$sql="SELECT * FROM car_type";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carType=array();
while($row = $stmt->fetch())
{
array_push($carType,$row['car_type']);
}
return $carType;
}
public function selectMaker()
{
$sql="SELECT * FROM car_maker";
$stmt =connection::$pdo->prepare($sql);
$stmt->execute();
$carMaker=array();
while($row = $stmt->fetch())
{
array_push($carMaker,$row['car_maker']);
}
return $carMaker;
}
ANd this is how I'm fetching the values to be passed to another page to be displayed to the user.
$setting = new setting($car_type,$car_maker,$rental_type,$rental);
//$setting->connection;
$setting->addCarType();
$setting->addCarMaker();
$setting->addRentalBy();
$carType=$setting->selectType();
$carMaker=$setting->selectMaker();
$json=array();
array_push($json,array("type"=>$carType,"maker"=>$carMaker));
echo $json;
Finally ajax to fetch and display data
$("#submit").on("click",function()
{
$("#set_setting").submit(function(){
data = $(this).serialize()
$.ajax({
type: "POST",
dataType: "html",
url: "submit_setting.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
//hide the form
$("#set_setting").slideUp("slow");
//show the result
for (i = 0; i < data.length; i++) {
console.log(data);//outputs array
$(".the-return").html(data);
}
}
});
return false;
});
});
You need to pass array as JSON and post it using name value pairs.
var data = {a:{'foo':'bar'},b:{'this':'that'}};
$.ajax({ url : '/',
type : 'POST',
data : {'data':JSON.stringify(data)},
success : function(){ }
});
And in backend (PHP):
$data = json_decode($_POST['data']);
print_r($data);
// Result:
// Array( "a" => Array("foo"=> "bar"), "b" => Array("that" => "this"))
I execute a simple AJAX Request, where i select some data from a mysql database. When i pass my Array back to Javascript, it always converts all Values in my Array into String, doesn't matter if its datatype was integer or boolean in my database.
EDIT:
I just found out, that MySQLi always converts datatypes to string, so I guess thats the problem. json_encode works fine.. https://stackoverflow.com/a/5323169/4720149
SQL Statement
function getAll()
{
// Get all buildings
$db = new db();
$sql = "SELECT * FROM building";
$result = $db->runQuery($sql);
$rows = array();
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
return $rows;
}
PHP Controller File
function getBuildings(){
$bu_db = new Building_Model();
$buildings = $bu_db->getAll();
echo json_encode($buildings);
}
Javascript file
var data = {
action: "getBuildings"
};
$.ajax({
type: "POST",
dataType: "json",
url: "controller/Building.php",
data: data,
success: function(data) {
console.log(data);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
console.log("Error in AJAX Request: " + textStatus + ", " + errorThrown);
}
});
Instead of keeping the original datatypes from the database, it turns all values into Strings:
Output
[Object, Object, Object, Object, Obje...]
>0: Object
>1: Object
>2: Object
>3: Object
ActiveCost: "20"
BuildEfc: "0"
BuildSfx: "0"
BuildingEfc: "0"
BuildingID: "1"
Name: "Vogtei I"
ResidentLvLNeeded: "0"
...
Does anybody know this problem?
Thanks in Advance.
What PHP version do you use?
Try:
echo json_encode($buildings, JSON_NUMERIC_CHECK );
Javascript has dynamic data types. So there is no specific data type for int string etc. same var object can hold all the data types. It will dynamically identify the type based on the operations you do on those variables.
I'm using php to return an array of data, with the command json_encode(). I want to also send some other data after I send this array. I'm using the jquery library. My php code is as follows:
<?php
//// Query
$sql = "SELECT gtn FROM $table WHERE gid < 10";
//// Open connection
$con = pg_connect("host=12.12.2.2 port=5434 dbname=spatial_data user=postgres password=****");
if (!$con){echo 'error connecting'; die; }
//// Run query
$query = pg_query($con, $sql);
$arrayData = array(); // Store results from query in arrays
//// Parse results
while($r = pg_fetch_row($query)) {
$arrayData[] = $r[0];
}
echo json_encode($arrayData);
//// Return metadata about calculation
//echo "$('#messages').html('Result returned for New York')";
//// close connection
pg_close($con);
?>
This php is responding to a jquery post command:
$.ajax({
type: "POST",
url: "/php/array_test_v3.php",
data:{vertices: pointlist},
success: function(arrayData){
//console.log(arrayData[0])
for(i=0;i<arrayData.length; i++){
setGeoJson(arrayData[i]);
}
},
dataType:'json'
});
This is a spatial database, and when I query the information, I also want to return some other values. For example, if the area is New York, I want to return an array of data and also the string New York. At the moment the line echo "$('#messages').html('Result returned for New York')"; just appends to the array of information. Is there a way that I can escape from the array, or do I need to have a separate post function to get this information.
Instead of echo json_encode($arrayData);, just fetch the meta data and then do:
echo json_encode(array(
'data' => $arrayData,
'meta' => $metaData
));
And then in JQuery:
success: function(result){
for(i=0;i<result.data.length; i++){
setGeoJson(result.data[i]);
}
// do something with result.meta
},
assuming you are using php.
make the array like this below
while($r = pg_fetch_row($query)) {
$arrayData[] = array('gtn'=>$r[0],'someotherkey'=>'someothervalue','anotherkey'=>'anothevalue');
}
echo json_encode($arrayData);
now in jquery you can do this
$.ajax({
type: "POST",
url: "/php/array_test_v3.php",
data:{vertices: pointlist},
success: function(arrayData){
$.each(arrayData,function(index,value){
setGeoJson(value.gtn);
$('#messages').html(value.someotherkey);
})
},
dataType:'json'
});
like this you can append or do any thing you like..
I am trying to figure out how to retrieve data from a MySQL database using an AJAX call to a PHP page. I have been following this tutorial
http://www.ryancoughlin.com/2008/11/04/use-jquery-to-submit-form/
But i cant figure out how to get it to send back json data so that i can read it.
Right now I have something like this:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "ajax.php",
data: "code="+ code,
datatype: "xml",
success: function() {
$(xml).find('site').each(function(){
//do something
});
});
});
My PHP i guess will be something like this
<?php
include ("../../inc/config.inc.php");
// CLIENT INFORMATION
$code = htmlspecialchars(trim($_POST['lname']));
$addClient = "select * from news where code=$code";
mysql_query($addClient) or die(mysql_error());
?>
This tutorial only shows how to insert data into a table but i need to read data. Can anyone point me in a good direction?
Thanks,
Craig
First of all I would highly recommend to use a JS object for the data variable in ajax requests. This will make your life a lot simpler when you will have a lot of data. For example:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "ajax.php",
data: { "code": code },
datatype: "xml",
success: function() {
$(xml).find('site').each(function(){
//do something
});
});
});
As for getting information from the server, first you will have to make a PHP script to pull out the data from the db. If you are suppose to get a lot of information from the server, then in addition you might want to serialize your data in either XML or JSON (I would recomment JSON).
In your example, I will assume your db table is very small and simple. The available columns are id, code, and description. If you want to pull all the news descriptions for a specific code your PHP might look like this. (I haven't done any PHP in a while so syntax might be wrong)
// create data-structure to handle the db info
// this will also make your code more maintainable
// since OOP is, well just a good practice
class NewsDB {
private $id = null;
var $code = null;
var $description = null;
function setID($id) {
$this->id = $id;
}
function setCode($code) {
$this->code = $code;
}
function setDescription($desc) {
$this->description = $desc;
}
}
// now you want to get all the info from the db
$data_array = array(); // will store the array of the results
$data = null; // temporary var to store info to
// make sure to make this line MUCH more secure since this can allow SQL attacks
$code = htmlspecialchars(trim($_POST['lname']));
// query
$sql = "select * from news where code=$code";
$query = mysql_query(mysql_real_escape_string($sql)) or reportSQLerror($sql);
// get the data
while ($result = mysql_fetch_assoc($query)) {
$data = new NewsDB();
$data.setID($result['id']);
$data.setCode($result['code']);
$data.setDescription($result['description']);
// append data to the array
array_push($data_array, $data);
}
// at this point you got all the data into an array
// so you can return this to the client (in ajax request)
header('Content-type: application/json');
echo json_encode($data_array);
The sample output:
[
{ "code": 5, "description": "desc of 5" },
{ "code": 6, "description": "desc of 6" },
...
]
So at this stage you will have a PHP script which returns data in JSON. Also lets assume the url to this PHP script is foo.php.
Then you can simply get a response from the server by:
$('h1').click(function() {
$.ajax({
type:"POST",
url: "foo.php",
datatype: "json",
success: function(data, textStatus, xhr) {
data = JSON.parse(xhr.responseText);
// do something with data
for (var i = 0, len = data.length; i < len; i++) {
var code = data[i].code;
var desc = data[i].description;
// do something
}
});
});
That's all.
It's nothing different. Just do your stuff for fetching data in ajax.php as usually we do. and send response in your container on page.
like explained here :
http://openenergymonitor.org/emon/node/107
http://www.electrictoolbox.com/json-data-jquery-php-mysql/