How to fetch data from a PHP page that encodes JSON? - php

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' })

Related

Retrieve ID number from MYSQL using AJAX & PHP then hashchange URL using retrieved ID

I'm trying to retrieve the latest video ID number from my database and then use that ID number to hashchange my URL and display the corresponding video. My PHP is working and returning a result but I'm not sure how to take that result and use it in jQuery so that I can use it for the hashchange. I haven't used jQuery much before so any detailed help would be amazing! Please find my current code below. The main question I have is how do I pass the $vidarray to jQuery so I can use that variable?
videoprocess.php
<?php
// Connect To DB
$hostname="localhost";
$database="MYDB";
$username="root";
$password="";
#$conn = mysqli_connect($hostname, $username, $password)
or die("Could not connect to server " . mysql_error());
mysqli_select_db($conn, $database) or die("Error: Could not connect to the database: " . mysql_error());
/*Check for Connection*/
if(mysqli_connect_errno()){
// Display Error message if fails
echo 'Error, could not connect to the database please try again again.';
exit();
}
$query = "SELECT VIDEOID FROM JubileeTouchVideo ORDER BY ID DESC LIMIT 1";
$result = mysqli_query($conn, $query) or die("Error in Selecting " . mysqli_error($conn));
//create an array
$vidarray = array();
while($row = mysqli_fetch_assoc($result))
{
$vidarray = $row;
}
echo json_encode($vidarray);
//close the db connection
mysqli_close($conn);
?>
videoprocess jquery
$.ajax({
url: "data.json",
//force to handle it as text
dataType: "text",
success: function(data) {
//data downloaded so we call parseJSON function
//and pass downloaded data
var json = $.parseJSON(data);
//Not sure what to do after this
}
});
This is how you can pass data to ajax.
$.ajax({
type: "POST",
url: url,
data: <?php echo $vidarray["id"]; ?>,
dataType: "text",
success: function(result) {
//result downloaded so we call parseJSON function
//and pass downloaded result
var json = $.parseJSON(result);
//Not sure what to do after this
}
});

Angular $http - function/response undefined

I've been unable to retrieve data from a json or php file because angular keeps yelling at me that either the function or response is undefined.
I want to pull up the navigation items from MySQL, when it failed to load php I've put the contents in a regular json file to see what was the problem it seems something in angular itself.
PHP:
<?php
header('Content-type:application/json');
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "dbname";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = 'SELECT * FROM navigation';
$result = $conn->query($sql);
$emparray = array();
while($row = mysqli_fetch_assoc($result)) {
$emparray[] = $row;
}
echo json_encode($emparray);
$conn->close();
?>
Which results in:
[{"nav_id":"0","nav_name":"Home","nav_link":""}, {"nav_id":"1","nav_name":"Contact","nav_link":"contact"}]
So far so good?
Here's my angular code that gets the file:
(function() {
var app = angular.module("headerControl", []);
app.directive("headerNavigation", function() {
return {
retrict:'E',
templateUrl:'views/partials/header-navigation.html'
};
});
app.controller("navController", function($scope, $http) {
$scope.navlist = {};
$http.get('phpservices/nav.php')
.success(function(response) {
alert('success');
})
.error(alert('error'));
});
})();
When I load the page it first gives me the error response and after that the success response... in the console angular tells me this:
Error: [ng:areq] http://errors.angularjs.org/1.4.2/ng/areq?p0=fn&p1=not%20a%20function%2C%20got%20undefined
whats wrong about this? I can't seem to figure it out...
The problem is that you are not passing error callback function properly. It should be:
.error(function() {
alert('error')
});
Otherwise you just invoke alert immediately (note ()) and since it doesn't return anything (so it "returns" undefined) error handler receives undefined in it. However, it expects a function. That's why you get this error.

How to get JSON data from a url in php file.

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

Try to return JSON data generated with SQL statement from PHP script to JS webpage but get null instead

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

How to generate a JSON based on form selections to build SQL statement by using a jQuery AJAX call to a PHP script

I have an HTML form(2 list-boxes and a check-box) which I want to use for filtering results on the page.
How can I make it so when I press the Submit button(.onclick(function(){})) it would execute a jQuery AJAX call to a PHP script on my local server that will, firstly, check if anything was selected in the list-boxes and if the check-box was checked and then based on that build a SQL statement to query my database and retrieve the result as JSON.
How would you do it, theoretically. I already have the PHP script to simply grab everything from my table and save it as JSON:
<?php
// databse connection info
require("dbinfo.inc.php");
// try to open a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// select the active MySQL database to work with
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// grab data about every campus and which instituion they belong to
$query = 'select statement to grab all the data from a table';
$result = mysql_query($query);
// check if $results has anything
if (!$result) {
die('Invalid query: ' . mysql_error());
}
// time to start generating our huge XML
while ($row = #mysql_fetch_assoc($result)){
$finalarray[] = $row;
$main_arr['products'] = $finalarray;
}
// close connection to the database
mysql_close($connection);
// echo, save and write the file
// print json_encode($main_arr);
$fp = fopen('results.json', 'w');
fwrite($fp, json_encode($main_arr));
fclose($fp);
?>
First send the data from the form with ajax:
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url : 'myPHPfile.php',
data: {form : $('form').serialize()}
}).done(function(data) {
var myJSONresult = data;
});
});
In your PHP file you'll get the form with
$form = $_POST['form'];
and there's no need to save to a file, just send it back by echoing
echo json_encode($main_arr);
Here is an example of posting to a php file and grabbing the data with ajax.
The result will get logged into the console.
I assume you know how to process the json with js once it has been retrieved?
//the php
<?php
//bla bla connect to database etc
//if form has been submitted with ajax
if(isset($_POST["ajax_request"])){
//build query
$id = $_POST["id"];
$fruit = $_POST["fruit"];
$query = "SELECT * FROM fruits WHERE id=$id AND fruit='$fruit'";
//fetch from db
$result = mysql_query($query);
//send out json
die(json_encode($result));
}
?>
//the jquery
<script type="text/javascript">
$(document).ready(function(){
//on submit
$("#ajaxForm").submit(function(e){
//stop default page refresh
e.preventDefault();
//define the form
var form = $(this);
//get the form data
var data = form.serialize();
//send it via ajax
$.ajax({
type : "post",
dataType : "json",
url : "url to your php here",
data : data+"&ajax_request=1",
success : function(json){
console.log(json);
},
error : function(a,b,c){
console.log(a,b,c);
}
});
});
});
</script>
//the html
<form id="ajaxForm" method="post" action="">
<input type="text" name="id" required="required" placeholder="enter id"/>
<input type="text" name="fruit" required="required" placeholder="enter fruit"/>
<input type="submit" name="submit"/>
</form>

Categories