PHP/JSON/ANDROID - why my JSONArray getting error - php

i try to displaying value of my table in android, and i put my code into hosting,
but when i try to running my app, my link doesn't work,
and i tried to create new link that displays the same output , and its works fine,
this is my code to encode json
send_data.php
<?php
include 'dbconfig.php';
$con = new mysqli($servername, $username, $password, $dbname);
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "select id,ask from pertanyaan";
$result = mysqli_query($con, $query);
while ($r = mysqli_fetch_array($result)) {
extract($r);
$rows[] = array(
"id"=>$id,
"ask"=>$ask
);
}
header('Content-Type: application/json');
echo json_encode($rows);
mysqli_close($con);
?>
did I'm doing something wrong??
because I want to set the output from the database

This is just a suggestion without seeing your AJAX code:
Add this code to the top of your PHP code:
header("Access-Control-Allow-Origin: *");
header('Content-type: application/json');
And use this code as an example of AJAX:
var poutput = $('.itemsHolder');
$.ajax({
url: 'https://yourdomain.com/php/YOUR-PAGE.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(pi,item){
str = item.id;
var products = '<div id="'+item.id+'">'+
'</div>';
poutput.append(products);
});
},
error: function(){
//alert('There was an error loading the data.');
}
});
Don't forget to add an element with the class name of itemsHolder to your page.

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 post not working with a https url

In my ionic app I have the following code:
$http({ url: "http://someurl/script.php",
method: "POST",
headers: {'Content-Type': 'application/x-www-form-urlencoded'},
data: $.param({param1:$localStorage.test.paramtest})
}).success(function(data) {
//console.log(data);
$scope.data = data;
}).error(function(data) {
//console.log("error:" + data);
alert("error:" + data);
})
.finally(function (data) {
//console.log("ok:" + data);
alert("ok:" + data);
});
The code above is working fine and I'm able to post en retrieve data from my database.
When I change the http:// url to a https:// url all of a sudden it is not working anymore. The error function gives me the error "error: null"
When I manually define the id in the php script and run de script with the https url in my browser it is also working.
This is mij script.php code:
<?php
//variables
$id = $_POST["param1"];
//$id = "12047";
// databse connection variables
$hostname = "...";
$username = "...";
$password = "...";
$database = "...";
// Create connection
$conn = new mysqli($hostname, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
//echo "Connected successfully<br>";
// show all database entries
$sql = "SELECT * FROM table1 WHERE field1_id='$id'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$rows = [];
while($row = $result->fetch_assoc()) {
// Add all rows to an array
$rows[] = $row;
}
// Json encode the full array
echo json_encode($rows);
} else {
//echo "0results";
}
$conn->close();
?>
I have setup my hosting to work with https and installed a SSL certificate on my server.
I found out that my hosting provider doesn't support SSL database connections in there hosting packages. It appears that this is only possible with dedicated servers.

referencing an image from php

I have a function on a website where I have a img reference leading to a php page
<img src="selectimage.php?uid=21312412">
which I need to return an image and update a database file
<?php
$servername = "localhost";
$username = "webz";
$password = "BLAH";
$dbname = "contactlist";
$readid = $_GET["uid"];
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "UPDATE emails SET `read`='1' WHERE `id`='" .$readid. "'";
if ($conn->query($sql) === TRUE) {
echo "<img src='logo11w.png'>";
}
$conn->close();
?>
I figured this would not work as I am referencing a php page in which is referencing the HTML tag
While this is updating my database it is not displaying the image.
how do I make this php file send the image logo11w.png to that img tag
Further note : include or other methods of including this code on the page loading are out of the question because this procedure may be called from a off-server source.
Store user id in one hidden field
You can use ajax for get respone back from php page after updating value in database
<input type="hidden" id="userid" value="user_id_value">
<input type="button" id="getimage" value="GET IMAGE">
<div id="u_img"></div>
$(document).ready(function(){
$('#getimage').click(function() {
var uid = $('#userid').val();
var datastring = "uid="+uid;
$.ajax({
type: "POST",
url: "php_page.php",
data: datastring,
cache: false,
success: function(result) {
$('#u_img').append(result);
}
});
});
});
The most effective method for what I am trying to do turns out to be:
...
if ($conn->query($sql) === TRUE) {
header('Content-Type: image/jpeg');
echo file_get_contents('https://www.google.com/images/srpr/logo11w.png');
} else {
echo "Error updating record: " . $conn->error;
}
...

Loading JSON in Phonegap?

Basically I have a php script located on a sever that generates a JSON file listing places from a mysql database. Using jQuery Mobile I am developing an application to display these places. My code works in Chrome & Safari, however when I port it over to Phonegap it doesn't work. I have searched all over the internet but can't find an answer :(.
The php file for generating JSON (json.php):
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "xxx";
$password = "xxx";
$database = "xxx";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$sql = "SELECT * FROM places ORDER BY name ASC";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
My Javascript file located within my app (Loads JSON and displays it):
$('#places').bind('pageinit', function(event) {
getPlaces();
});
function getPlaces() {
var output = $('#placeList');
$.ajax({
url: 'http://www.mysite.com/json.php',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<li><a href="">'+item.name+'<span class="ui-li-count">'
+ item.checkins+'</span></a></li>';
output.append(place);
});
$('#placeList').listview('refresh');
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
The HTML looks like this:
<div data-role="content">
<h3>Places</h3>
<ul data-role="listview" id="placeList" data-inset="true">
</ul>
</div><!-- /content -->
This code works in Chrome & Safari, however when run in the xCode simulator with Phonegap it doesn't load the JSON.
Any help would be much appreciated :)
This has probably something to do with the whitelisting, Apple has no faith in any type of uncontrollable data (like iframes or feeds). So they reject every external connection.
Take a look at phonegap.plist in your project rootfolder (xcode) and add your website url to the array 'ExternalHosts'. This will probably work fine after.

How can I work on the output of jsonp in phonegap?

I am working on a PhoneGap with Android project. I have designed a login page in which I want to show an alert box for a valid and invalid user. I am using PHP for database validation.
This is my php page:
<?php
header('Content-type: application/json');
$server = "localhost";
$username = "root";
$password = "";
$database = "mymusic";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$id=$_GET["id"];
$pass=$_GET["password"];
//$id='ram';
//$pass='ram';
$sql = "SELECT id, name,password FROM login where userid='$id' and password='$pass'";
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
This is my java script function:
function onDeviceReady(){
var output = $('#output');
var id = document.getElementById('userid').value;
var pass = document.getElementById('password').value;
// webcam.set_api_url( 'test.php?filename=' + escape(filename));
$.ajax({
url: 'http://192.168.1.214/sample/dologin.php?id='+id+'&password='+pass,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
console.log('entered success============');
$.each(data, function(i,item){
var logi=item.id;
if(logi!=null)
alert("valid user");
else
alert("invalid user");
});
},
error: function(){
console.log('entered success====================');
output.text('There was an error loading the data.');
}
});
}
This is not working properly for an invalid user. Whenever I enter a valid user name and password then it displays the valid user message box. When I enter an invalid user name and password then it doesn't display anything.
Thank you in advance...
Try debugging this in a browser and perhaps send the returned jsonp data to the console from within your ajax's success call console.log(data).
It's quite possible that your jsonp is returning some data as opposed to null... even if it is simply undefined or an empty string. Your conditional is most likely the culprit.

Categories