Okay, so I'm a bit of a newb to JSON. I'm trying to cobble together an AJAX call(a PHP mssql query) that returns the values back to the original form through JSON. I'm getting [object Object] instead of the actual value of the variable. Through some searching I think the issue is related to parsing, but I thought json_encode handled this. Or maybe it does and I haven't structured this correctly.
Here's what Im trying to accomplish:
An html form has 3 fields: Account Number, Account Name and Address1. I want the user to be able to enter the Account Number and then have the Name and Address fields populate on blur with the results of the mssql query.
Here's what I have:
HTML
<body>
<label>Account Number:</label><input type="text" id="acctnumber" />
<label>Account Name:</label><input type="text" id="acctname" />
<label>Address 1:</label><input type="text" id="address1" />
</body>
Jquery (I put the acctnumber input value in just for testing)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#acctnumber").blur(function(){
$.ajax({
url: "ajaxtestscript.php?acctnumber=hfi01",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
$("#acctname").val(data.Name);
$("#address1").val(data.Address);
//parse the json data
}
});
});
});
</script>
PHP
<?php
header('Content-Type: application/json');
//mssql connection info//
$acctnumber = $_GET["acctnumber"]; // we received this from the json call
//declare the SQL statement that will query the database
$query = "select[description],[daddr1] from trCustomer where company = '$acctnumber' and archived = 0";
//execute the SQL statement and return records
$rs = $conn->execute($query);
$test = array();
$test['Name'] = $rs[description];
$test['Address'] = $rs[daddr1];
echo json_encode($test);
//echo $name.$address; put this in to test the query was working, which it was
//close the connection and recordset objects freeing up resources
$rs->Close();
$conn->Close();
$rs = null;
$conn = null;
?>
When I actually try this on the html form, I enter in the Account number value (hardcoded at this point) and click out of the element to fire blur, and in the other two input fields I get [object Object]. Although if I just echo my query back I can see the values so I'm thinking I have done something wrong or left something out with my json_encode. Any assistance would be greatly appreciated.
After executing your query, you first need to fetch the resulting rows with whatever function your DB Library is supposed to do so. And should't you prepare your query first?
Otherwise the object that you are trying to json_encode() is an resource object. That is why you get object Object. I would expect code like this
$conn = new PDO(...);
$stmt = $conn->prepare("SELECT ...");
$stmt->execute();
$test = array();
while ($row = $stmt->fetch()) {
$test[] = array(
'Name' => $row[description],
'Address' => $row[daddr1]
);
}
echo json_encode($test);
$stmt = NULL;
$conn = NULL;
First of all, your question is unclear and depending on the situation, I would debug and test the outputs.
1. PHP : The query result : var_dump(json_encode($test)); exit(0);
This will help you to know what data is being sent to front. alert or console print the received data in ajax to view.
2. Javascript : console.log(data);
This will help you to know what data is being received and what exactly you need to write to populate in the required field. Check in browser console.
Thanks for upvoting. Cheers !
Related
I'm creating a small project using php and jax, when I fetch data to database and display to a textbox using specific variable declared in may query it is working but when I try to use declared variable it is not working.
For example:
SELECT remaining FROM sys_stocks WHERE particulars='MONITOR' - Working Fine.
$particularslogs = $_POST['particularslogs'];
SELECT remaining FROM sys_stocks WHERE particulars='$particularslogs' - Not Working
What should be the problem?
Thank you in advance.
Here's what I tried so far.
PHP Code.
<?php
include_once('../connection/pdo_db_connection.php');
$particularslogs = $_POST['particularslogs'];
$database = new Connection();
$db = $database->open();
$query = $db->prepare("SELECT remaining FROM sys_stocks WHERE
particulars='$particularslogs'");
$query->execute();
$query->setFetchMode(PDO::FETCH_ASSOC);
while ($row = $query->fetch()) {
echo $row['remaining'];
}
//close connection
$database->close();
?>
AJAX Code.
<script type="text/javascript">
$('#stocksdatelogs').on('blur', function(){
$.ajax({
type : "get",
url : 'function/remaining_stocks_fetch.php',
success : function(remaining)
{
$('#remaininglogs').val(remaining);
}
});
});
</script>
I expect the output will display the MONITOR remaining count into my database table which is 5 to a remaining textbox field using WHERE particulars='$particularslogs' and not WHERE particulars='MONITOR'.
You are not sending the data.
1 - send the data from ajax method to php file something like this.
url : 'function/remaining_stocks_fetch.php',
data: {particularslogs: your data field name},
2- You are using GET method so you need to change the method POST to GET, something like this.
$particularslogs = $_GET['particularslogs'];
OR
Change the type var in the ajax method, like this.
type : "POST",
I'm very new to php and SQL so i'm really sorry if this is very trivial.
My site has multiple divs with table names inside it. The HTML is of the form:<p class="listname">(table name)</p>
I am trying to write a function so that when a user clicks on a div, the function gets the text using innerHTML and the contents of that particular table are shown.
The jquery function i wrote is:
$(document).ready(function(){
$(".listname").click(function(){
var x=($(this).html()).toLowerCase(); //this assigns the text in the class listname to the variable x
console.log(x);
$.ajax({
url: 'http://localhost/fullcalendar/events.php',
data: {name:x},
type: "GET",
success: function(json) {
}
});
});
});
And my PHP code is:
<?php
include 'ChromePhp.php';
ChromePhp::log('php running');
$json = array();
if($_POST['name']!=null)//check if any value is passed else use default value
{
$table=$_GET['name'];
ChromePhp::log($table);
}
else
{
$table= 'event';
ChromePhp::log($table);
}
$requete = "SELECT * FROM `$table` ORDER BY id";
try {
$bdd = new PDO('mysql:host=localhost;dbname=fullcalendar', 'root', 'root');
} catch(Exception $e) {
exit('Unable to connect to database.');
}
// Execute the query
$resultat = $bdd->query($requete) or die(print_r($bdd->errorInfo()));
// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>
When i first load the website, the default value for $table is used in the query, and data is retrieved. However, when i try clicking on a div, the correct value is passed to php and assigned to $table (i checked in the console) but the data displayed is of the default table i.e 'event' table.
How can i fix this?
PS: all my tables are in the same database.
You're checking the POST data:
if($_POST['name']!=null)
But using GET data:
type: "GET"
So the $_POST array will always be empty and your if condition will always be false. You probably meant to check the GET data:
if($_GET['name']!=null)
Also of note are a couple of other problems in this code:
Your success callback is empty, so this AJAX call isn't going to actually do anything client-side. Whatever you want to do with the returned data needs to be done in that success function.
This code is wide open to SQL injection. It's... very unorthodox to dynamically use table names like that. And this is probably an indication that the design is wrong. But if you must get schema object names from user input then you should at least be taking a white-list approach to validate that the user input is exactly one of the expected values. Never blindly execute user input as code.
I try to learn JS together with jQuery and Ajax, and until now it was more or less painless, but now I faced myself with some obstacles about getting result from called PHP script, initiated by Ajax. What is my problem here? I have a MySQL table and I wanted to pull some data from JS by Ajax call. I tested my query to check is it correct and make result and with same query I built PHP script. Here is my JS file:
...
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
</head>
<body>
<script>
callphp(12,14);
//
function callphp(par1, par2) {
$.ajax({
type: "POST",
url: "_ajax2php2.php",
cache: false,
dataType: "json",
data: { "po1": par1, "po2":par2 },
success: function(data, status, jqXHR){
jss=JSON.stringify(data);
alert(jss);
//
var strBuilder = [];
for(key in data){
if (data.hasOwnProperty(key)) {
strBuilder.push("Key is " + key + ", value is " +data[key] + "\n"); }
}
alert(strBuilder.join(""));
},
error: function(data) {
alert( "params error" );
}
});
// end of JS
and here is my PHP script:
<?php
$eol="<br/>";
$uuu= isset($_POST['po1']) ? $_POST['po1'] : '';
$zzz= isset($_POST['po2']) ? $_POST['po2'] : '';
$con=mysqli_connect("localhost","root","some_password","mydbase");
// Check connection
if (mysqli_connect_errno())
{
echo "Fail to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"mydbase");
$query4 = "SELECT * from mytable WHERE uc_id='$uuu' AND pr_id='$zzz' ";
$result4 = mysqli_query($con, $query4);
$row4= mysqli_fetch_assoc($result4);
if(mysqli_num_rows($result4) > 1) {
while($row4[]=mysqli_fetch_assoc($result4)) {
$data = $row4; }
}
else
{$data=$row4;}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
/* free result set */
mysqli_free_result($result4);
mysqli_close($con);
//end of php
?>
and it seems that it works good when PHP query return just one record, if there are 2 or more then I'm unable to "dismantle" JSON object by this JS code, because for example if my query return 3 records, in alert it appears like
Key is 0, value is [object Object]
Key is 1, value is [object Object]
Key is name_of_field1, value is 1
Key is name_of_field2, value is 12
Key is name_of_field3, value is 2
Key is name_of_field4, value is 1
Key is name_of_field5, value is 14
Key is name_of_field6, value is 2015-09-10
and I need to be able to get each particular record fields of each record in order to fill with it some HTML table. How to write this part of code that resolve JSON response consist of two or more records made by PHP? I tried examples I found here but no one met my needs. Thanks.
In your while loop after the DB query, you are just overwriting the value for $data with every iteration. I would suggest not having different logic for cases with one row in result set vs. more than one row, as this does nothing but add complexity to your code. Just return an array every time and you will be better off. Your code around the query might look like this:
$data = array();
$result4 = mysqli_query($con, $query4);
if($result4) {
while($row = mysqli_fetch_assoc($result4) {
$data[] = $row;
}
}
echo json_encode($data, JSON_UNESCAPED_UNICODE);
This simplifies this section of code and will also simplify the client-side code since now you can write it to simply expect to work with an array of objects in all cases.
This means that in javascript your code might look like (ajax success handler code shown):
success: function(data, status, jqXHR){
// data is an array, with each array entry holding
// an object representing one record from DB result set
var recordCount = data.length;
console.log(recordCount+' records returned in response.');
// you can iterate through each row like this
for(i=0;i<recordCount;i++) {
// do something with each record
var record = data[i];
// in this example, I am just logging each to console
console.log(record);
// accessing individual properties could be done like
console.log(record.name_of_field1);
console.log(record.name_of_field2);
// and so on...
}
}
You should get in the habit of using console.log() rather than alert() or similar for debugging your javascript, as alert() actually interrupts your javascript code execution and could introduce problems in debugging more complex javascript (particularly when there are asynchronous activities going on). Using the javascript console functionalty built into your browser should be fundamental practice for any javascript developer.
I am currently working on a php/javascript project which retrieves information from a database and json encodes the data. It is supposed to show the values from the database inside a combo box on the web page.
In the PHP script that encodes the mysql data I have the following code:
$query = "SELECT pla_platformName as `platform` FROM platforms";
$result = mysql_query($query);
if ($result)
{
while ($myrow = mysql_fetch_array($result))
{
$output[] = $myrow;
}
print json_encode($output);
die();
}
In the javascript code I have the following:
<script>
$(document).ready(function()
{
getPlatforms();
function getPlatforms()
{
$.post("phpHandler/get-platforms.php", function(json)
{
alert(json);
alert(json.platform);
}
);
}
});
</script>
I have alert(json); which shows the entire json data which looks like the following:
[{"0":"hello","platform":"hello"},{"0":"android","platform":"world"}]
The next alert(json.platform) I am expecting it to show either hello or world or both but on this line it keeps on saying undefined. Why isn't this working and how do I get a specific platform, i.e. either hello, or world.
Thanks for any help you can provide.
You need to first convert your JSON string into an object
var data = $.parseJSON(json);
In this case, the object returned is an array. Try
alert(data[0].platform);
You can skip the first step if you set the dataType option to json in your ajax call.
$.post("phpHandler/get-platforms.php", function(data) {
alert(data[0].platform);
},
'json'
);
See jQuery.post() documentation
Your platform member is defined on each item, you'll have to specify which array item you want the platform for. This should do the trick:
alert(json[0].platform);
I'm assuming that your json parameter actually holds a javascript object, and not simply a string. If it is a string, you should define contentType 'application/json' on your php page. (I'm not sure how you do that in php since I do .NET for server side myself.)
To test it quickly however, you can do a $.parseJSON(json) to get the object.
I'm creating a contest sign-up page for our annual math competition at my school. It requires some AJAX like behavior when you click and select an item in a dropdown list.
I've gotten an event to fire when I select something in the dropdown (I'm currently showing an alert box):
<script type="text/javascript">
$(function() {
$("#student").change(onStudentChange);
});
function onStudentChange()
{
alert("Dropdown changed");
}
</script>
What this needs to do, is do an asynchronous call to the server to get a list of contests that student is currently registered for.
I know I need to do a jquery ajax call. So I think my onStudentChange() function would look like this:
$.ajax({
type : 'POST',
url : 'get_registered_events.php',
dataType : 'json',
data: {
studentid : $('#student').val()
},
success : function(data){
// Do something once we get the data
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
// Display error
}
});
return false;
});
So I went ahead and created the get_registered_events.php, which I want to return the events the student is registered for.
My problem is, I'm not experienced with PHP and I'm having difficulty figuring out how I would return the data the database gave me to this ajax call in the JSON format. Another snag I have is our school is using a very old version of PHP so I have to use this PEAR JSON library.
Here is that PHP file I'm having trouble with:
<?php
if (!empty($_POST['studentid')) {
include_once('JSON.php');
$json = new Services_JSON();
$dbconn = pg_connect("host=somehost dbname=somedb user=someuser password=somepassword") or die('Could not connect: ' . pg_last_error());
$query = 'SELECT contest.id, contest.title, FROM contest, student_contest WHERE student_id = '.$_POST['studentid'].' AND contest.id = contest_id';
$contests = pg_query($query) or die('Query failed: ' . pg_last_error());
// Here I need to convert the rows of $contests (contest.id, contest.title), into JSON and return it to that ajax call.
}
?>
So my question is, how do I convert $contests (its rows), into JSON (contest.id, contest.title), and return that back to the ajax call that will make it above.
If anyone could point me in the right direction I would really appreciate it.
$myarray = array();
while ($row = pg_fetch_row($contests)) {
$myarray[] = $row;
}
echo json_encode($myarray);
I think this has to work.
You can also do
$resultArray = pg_fetch_all($result);
echo json_encode($resultArray);
This will encode each row as a JSON Object with the column name as the key and put all the rows in a JSON Array
Only do this if you know for sure that your query will return a small set of data. If you are worried about the size of data, use #atif089's but use pg_fetch_assoc() instead of pg_fetch_row()
From postgresql 9.3 you can get result directly as a json array with json_agg:
With p as (
SELECT contest.id, contest.title, FROM contest, student_contest WHERE student_id = '.$_POST['studentid'].' AND contest.id = contest_id
)
select json_agg(p) as json from p;
http://www.postgresql.org/docs/9.3/static/functions-aggregate.html