I do have a code which shows number of data in database. I want to send this data to browser in real time or in between couple of seconds using ajax or any other method...
My code:
$db = mysql_connect($db_host, $db_username, $db_password) or die("Could not connect.");
mysql_select_db($databse_name,$db)or die(mysql_error());
$result = mysql_query("SELECT * FROM table")or die(mysql_error());
$num_rows = mysql_num_rows($result);
echo "$num_rows\n";
If you're using jQuery and that php code is in a file called your_code.php, you could do something like this:
$('#my_button').click(function() {
$.ajax({
url: "your_code.php",
success: function(data) {
$('#my_div').html(data);
}
});
}
Related
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
}
});
I'm trying to make a test page for sending google map cordinates to populate a mysql database. I'm using ajax to send data to php. Firebug shows that the data is sending. But this php error comes out. And the mysql database is populating without the map cordinates.
Here's the Ajax function:
function sendData(geodata){
var hr = new XMLHttpRequest();
hr.open("POST","getdata.php",true);
hr.setRequestHeader("Content-type","application/json");
if(hr.readyState==4 && hr.status==200){
var data = JSON.parse(hr.responseText);
alert("Data received about "+data);
}//end if
hr.send("geodata="+geodata);
}//close sendData
This is the PHP page.
<?php
header("Content-Type : application/json");
$loc = $_POST["geodata"];
$username="root";
$password="";
$database="location";
$connection = mysql_connect('localhost',$username,$password);
if(!$connection){
die('Unable to connect to the server '.mysql_error());
}
$selectdb = mysql_select_db($database);
if(!$selectdb){
die('Unable to connect to database'.mysql_error());
}
$query = "INSERT INTO `location_data`(`ltlng`) VALUES ('".$loc."')";
$result = mysql_query($query);
if(!$result){
die('Invalid query : '.mysql_error());
}
?>
Then the following errors comes out.
( ! ) Notice: Undefined index: geodata in C:\wamp\www\IndustryProject\SampleDataGen\getdata.php on line 4
Any help would be appreciated.Thanks.
When you're POSTing the data as a query-string, try using the application/x-www-form-urlencoded Content-type, not the application/json one that you currently are:
hr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
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)
});
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.
I am trying to pull latitude and longitude values from another server on a different domain using a singe id string. I am not very familiar with JQuery, but it seems to be the easiest way to go about getting around the same origin problem. I am unable to use iframes and I cannot install PHP on the server running this javascript, which is forcing my hand on this.
My queries appear to be going through properly, but I am not getting any results back. I was hoping someone here might have an idea that could help, seeing as I probably wouldn't recognize most obvious errors here.
My javascript function is:
var surl = "http://...omitted.../pull.php";
var idnum = 5a; //in practice this is defined above
alert("BEFORE");
$.ajax({
url: surl,
data: {id: idnum},
dataType: "jsonp",
jsonp : "callback",
jsonp: "jsonpcallback",
success: function (rdata) {
alert(rdata.lat + ", " + rdata.lon);
}
});
alert("BETWEEN");
function jsonpcallback(rtndata) {
alert("CALLED");
alert(rtndata.lat + ", " + rtndata.lon);
}
alert("AFTER");
When my javascript is run, the BEFORE, BETWEEN and AFTER alerts are displayed. The CALLED and other jsonpcallback alerts are not shown.
Is there another way to tell if the jsoncallback function has been called?
Below is the PHP code I have running on the second server. I added the count table to my database just so that I can tell when this script is run. Every time I call the javascript, count has had an extra item inserted and the id number is correct.
<?php
header("content-type: application/json");
if (isset($_GET['id']) || isset($_POST['id'])){
$db_handle = mysql_connect($server, $username, $password);
if (!$db_handle)
{
die('Could not connect: ' . mysql_error());
}
$db_found = mysql_select_db($database, $db_handle);
if ($db_found)
{
if (isset($_POST['id'])){
$SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_POST['id']));
}
if (isset($_GET['id'])){
$SQL = sprintf("SELECT * FROM %s WHERE loc_id='%s'", $loctable, mysql_real_escape_string($_GET['id']));
}
$result = mysql_query($SQL, $db_handle);
$db_field = mysql_fetch_assoc($result);
$rtnjsonobj -> lat = $db_field["lat"];
$rtnjsonobj -> lon = $db_field["lon"];
if (isset($_POST['id'])){
echo $_POST['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
}
if (isset($_GET['id'])){
echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
}
$SQL = sprintf("INSERT INTO count (bullshit) VALUES ('%s')", $_GET['id']);
$result = mysql_query($SQL, $db_handle);
$db_field = mysql_fetch_assoc($result);
}
mysql_close($db_handle);
} else {
$rtnjsonobj -> lat = 404;
$rtnjsonobj -> lon = 404;
echo $_GET['jsonpcallback']. '('. json_encode($rtnjsonobj) . ')';
}?>
I am not entirely sure if the jsonp returned by this PHP is correct. When I go directly to the PHP script without including any parameters, I do get the following.
({"lat":404,"lon":404})
The callback function is not included, but that much can be expected when it isn't included in the original call.
Does anyone have any idea what might be going wrong here?
Thanks in advance!
Change this part of the code
jsonp: "jsonpcallback",
with:
jsonpCallback : "jsonpcallback",