Hello friends please help me for following question
How to pass data in JSON and how to get JSON data in php using
following code
eg:
$.getJSON("url",function(data)
{
alert(data);
});
php file:::::
<?php how to get JSON data here? ?>
The below is a sample server side code i.e. php code (you asked for php)
This includes fetching data from sql and encoding it into JSON format and returning it to client.
File content of testAJAX_getJson.php
$con =
mysql_connect("localhost","peter","abc123");
if (!$con) { die('Could not
connect: ' . mysql_error()); }
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM
Persons");
while($row =
mysql_fetch_array($result)) {
$data[] = $row; }
echo json_encode($data);
Related
I have made an "api", I have converted data from my sql table into JSON and that is echoed onto my file "api.php", I have "get.php" and I would like to get specific bits of data from the JSON on get.php. It's not working and just throwing an error however
This is for a contract, I have already tried cURL but it doesn't work
api.php (not included login variables)
$dblink = new mysqli($servername, $username, $password, $dbname);
if ($dblink->connect_errno) {
printf("Failed to connect to database");
exit();
}
$result = $dblink->query("SELECT * FROM updates LIMIT 3");
$dbdata = array();
while ( $row = $result->fetch_assoc()) {
$dbdata[]=$row;
}
echo json_encode($dbdata);
and this is what I see on api.php, the JSON is corrected echod i just can't access it.
[{"id":"1564343527","title":"title","type":"Server","overview":"overview","added":"a:2:{i:0;s:6:\"added1\";i:1;s:6:\"added2\";}","removed":"a:2:{i:0;s:8:\"removed1\";i:1;s:8:\"removed2\";}","changed":"a:1:{i:0;s:0:\"\";}","date":"2019\/07\/28","time":"09:52:07pm"}]
get.php
<?php
$strJsonFileContents = file_get_contents('api.php');
var_dump($strJsonFileContents); // show contents
?>
error (on get.php)
string(610) "connect_errno) { printf("Failed to connect to database"); exit(); } $result = $dblink->query("SELECT * FROM updates LIMIT 3"); $dbdata = array(); while ( $row = $result->fetch_assoc()) { $dbdata[]=$row; } echo json_encode($dbdata); ?> "
Expected result is for it to echo the page (api.php) so i can pick apart the JSON, actual result is an error.
Not sure about the extent of your code, but I think this can be done simply by including api.php in get.php. There is no need to read the contents of api.php to parse the data.
get.php:
<?php
require 'api.php';
// api.php is included so $dbdata is in scope here
var_dump(json_encode($dbdata));
I am trying to receive data back from a mysql db but in my results I receive escape characters. How can I get rid of these and just return raw data (I'm a noob in this realm of coding so please keep that in mind)?
Here is a sample of my result (it's a json signature):
{"signature":"\n\t\t\t[{\"lx\":16,\"ly\":16,\"mx\":16,\"my\":15},{\"lx\":16,\"ly\":17,\"mx\":16,\"my\":16},{\"lx\":16,\"ly\":18,\"mx\":16,\"my\":17},{\"lx\":16,\"ly\":20,\"mx\":16,\"my\":18},{\"lx\":16,\"ly\":21,\"mx\":16,\"my\":20},{\"lx\":16,\"ly\":22,\"mx\":16,\"my\":21},{\"lx\":16,\"ly\":25,\"mx\":16,\"my\":22},{\"lx\":16,\"ly\":26,\"mx\":16,\"my\":25},.....]\n\t\t\t"}
I would like to remove the: {"signature":"\n\t\t\t on the beginning and \n\t\t\t"} on the end automatically.
Any help is greatly appreciated!
<?php
{
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', 'rootpassword', 'crs' );
//Check our connection_aborted
if ($mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_error );
}
//Read the signature
$sql = "SELECT signature FROM rescue_forms WHERE id=53";
$idresult = $mysqli->query($sql);
while($row = mysqli_fetch_assoc($idresults))
$id = $row;
//Just printing this so I can see the results.
print json_encode($id);
//sending this to a statement below.
$json = json_encode($id);
//Close connection
$mysqli->close();
}
?>
You are storing json in a database, which you shouldn't,
and for some reason you are encoding your json again, which is pointless.
In a round about way of down voting my question and basically telling me I'm an idiot, it helped! (which is the point of the forum) In hopes that this might help someone else that might just be starting out coding this kind of thing. I was able to change my array around to get the raw data as I was expecting, here's my example:
<?php
{
// Connect to MySQL
$mysqli = new mysqli( 'localhost', 'root', 'rootpassword', 'crs' );
//Check our connection_aborted
if ($mysqli->connect_error ) {
die( 'Connect Error: ' . $mysqli->connect_error );
}
//Read the signature
$sql = "SELECT signature FROM rescue_forms WHERE id=53";
$idresult = $mysqli->query($sql);
while($sig=mysqli_fetch_assoc($idresult)){
echo "<tr>";
echo "<td>".$sig['signature']."</td>";
echo "</tr>";
}
//Close connection
$mysqli->close();
}
?>
Thank you to all that responded it was greatly appreciated! Also thank you #YourCommonSense for showing me the proper way to format my code in this window with your edit.
Please help me guys. I've been figuring how to solve this problem for several hours already but I still don't know how. ><
This is my php page that displays value in JSON Format.
jsonfile.php :
<?php
header("Access-Control-Allow-Origin: *");
header('Content-Type: application/json');
//open connection to mysql db
$connection = mysqli_connect("localhost","root","","online_evaluation_revised") or die("Error " . mysqli_error($connection));
//fetch table rows from mysql db
$sql = "select * from tblaccount";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
//create an array
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
echo json_encode($emparray);
//close the db connection
mysqli_close($connection);
?>
it display something like this:
[{"account_id":"89","username":"2012100014","password":"25d55ad283aa400af464c76d713c07ad"},{"account_id":"90","username":"2012102400","password":"25d55ad283aa400af464c76d713c07ad"},{"account_id":"91","username":"2012101087","password":"25d55ad283aa400af464c76d713c07ad"},{"account_id":"92","username":"2011102090","password":"25d55ad283aa400af464c76d713c07ad"}]
however, I don't how to fetch/transfer these data to my services.js and controller.js.
Here is my services.js:
app.service("myService", function($http,$q)
{
var deferred = $q.defer();
$http.get('resources/json/jsonfile.php').then(function(data)
{
deferred.resolve(data);
});
this.getAccounts = function()
{
return deferred.promise;
}
})
here is my controller.js:
.controller("myCtrl",function($scope,myService)
{
var promise = myService.getAccounts();
promise.then(function (data)
{
$scope.allAccounts = data;
var accounts = data;
console.log($scope.allAccounts);
});
})
Whenever I use the data using the format above, it gives me something like this in the console log:
Object {data: "<?php
↵ //open connection to mysql db
↵ $con…db connection
↵ mysqli_close($connection);
↵?>", status: 200, config: Object, statusText: "OK"}
Weird because if I use the format above when fetching a file in JSON format (not in PHP), it gives me array objects.
For This To Access Data in Js File YOu Have to use ajax.
call ajax when ever you want data.
for More Details you refer below link.
http://www.w3schools.com/php/php_ajax_database.asp
Try :
$http.get('resources/json/jsonfile.php',{ responseType : 'json' })
I am trying to convert data from my DB to JSON with a PHP script.
Everything works great on my local environment (MAMP).
As soon as I am trying to put things together on my server, my JSON File is empty :(
What I have so far
my php script
<?php
$connection = mysqli_connect("localhost","root","root","angulardb") or die("Error " . mysqli_error($connection));
$sql = "select * from postings";
$result = mysqli_query($connection, $sql) or die("Error in Selecting " . mysqli_error($connection));
$emparray = array();
while($row =mysqli_fetch_assoc($result))
{
$emparray[] = $row;
}
$fp = fopen('menue.json', 'w');
fwrite($fp, json_encode($emparray));
fclose($fp);
echo json_encode($emparray);
?>
By uploading this script to my server (& update the data), I receive an empty JSON file with no response.
Any Idea what can be wrong???
Is there additional configuration necessary on the server side?
Thanks in advance
Ok,
got it .
the missing chsrset=utf8 caused my problem!
$pdo=new PDO("mysql:dbname=db239256x2330361;host=mysql.webhosting38.1blu.de;charset=utf8","s239256_2330361","20dj93lpav+dd");
I want to return JSON data from a resulted SQL statement in a PHP script upon pressing Submit button, but I receive null instead.
I'll be using the returned JSON to filter-show markers on my Google Map, but for now I just want to get the data back across to my jQuery page from PHP script so I can manipulate/use it.
Submit button:
HTML
<input type="submit" id="filter" value="Filter" />
JS
$('#myform').on('submit', function(e) {
e.preventDefault();
var myData = $('#myform').serializeArray();
$.getJSON('myscript.php', myData, function(json){
alert(json);// actually filter for later
});
});
PHP script:
// action is a hidden form control I use to check if form was submitted
if(isset($_POST["action"])){
if(isset($_POST["color"]) && isset($_POST["zipcode"])){
// try to open a connection to a MySQL server
$connection = mysql_connect($host, $username, $password) or die("Could not connect" . mysql_error());
// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection) or die("Can\'t use db:" . mysql_error());
$query = 'sql statement to return resutls based on what color and zipcode was provided';
$result = mysql_query($query) or die("Can\'t do that: " . mysql_error());
}
// close connection to the database
echo json_encode($result);
mysql_close($connection);
}
You can't return the result object of a mysql_query call directly. You first have to parse it with functions like mysql_fetch_array or alike (PHP docu).
...
$result = mysql_query($query);
if ( $result === false ) {
die("Can\'t do that: " . mysql_error());
}
$retVal = array();
while( $row = mysql_fetch_array( $result ) ) {
$retVal[] = $row;
}
...
echo json_encode( $retVal );
EDIT
According to the jQuery spec for getJSON (link), the data is sent using GET parameters and not using POST. So you would have to change all the $_POST appearances in your PHP code to either $_GET or $_REQUEST.
Besides this, you should return some error messages if your variables are not set. Right now (according to your code) just an empty document is returned.
Before the echo you should declare the returned content type:
header('Content-Type: application/json');
If you want to check for the receival of the data you can use:
$.ajax({
url: url,
data: myData,
success: function(json) {},
error: function(json) {} // this should allow you to check if data is received (but since the content type is set to text/html and $.getJSON expectr application/json it won't be a success)
});