Ajax from php DataTables warning:table id=example - Invalid JSON response - javascript

<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="GBK">
<title></title>
</head>
<body>
{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":[["086671","NB","MSC-1","09-APR-15"],["086673","DB","MSC-2","09-APR-15"],["086678","DA","MSC-1","10-APR-15"],["086682","DA","MSC-1","10-APR-15"],["086683","NA","MSC-1","10-APR-15"],["086491","NA","MSC-2","25-MAR-15"],["086686","DA","MSC-1","10-APR-15"],["086688","DA","MSC-2","10-APR-15"],["086690","NA","MSC-2","10-APR-15"],["086496","DA","MSC-1","25-MAR-15"],["086685","NB","MSC-1","09-APR-15"],["086848","NA","MSC-2","22-APR-15"],["086516","NA","MSC-1","22-APR-15"],["086523","DA","MSC-1","22-APR-15"],["086839","DA","MSC-2","22-APR-15"],["086849","DA","MSC-1","22-APR-15"],["086528","NB","MSC-1","24-APR-15"],["086526","NB","MSC-1","27-MAR-15"],["086478","DA","MSC-1","25-MAR-15"],["086482","DB","MSC-1","27-MAR-15"],["086832","NB","MSC-1","24-APR-15"],["086840","DB","MSC-2","24-APR-15"],["086842","NB","MSC-2","24-APR-15"],["086828","DB","MSC-1","24-APR-15"],["086987","NB","MSC-1","07-MAY-15"],["086991","DB","MSC-2","07-MAY-15"]]} </body>
</html>
I am a new-comer to php and jQuery, now I have one question; when I use a datatable to query data, error as title, and detail code as follows:
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="GBK">
<title>作业</title>
<link href="http://CEA815099W/test/cim_web/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="http://Cea815099w/test/cim_web/css/dataTables.bootstrap.css" />
<script src="http://CEA815099W/test/cim_web/js/jquery-1.11.3.min.js"></script>
<script src="http://CEA815099W/test/cim_web/js/jquery.dataTables.min.js"></script>
<script src="http://CEA815099W/test/cim_web/js/dataTables.bootstrap.js"></script>
<script src="http://CEA815099W/test/cim_web/js/echarts.js"></script>
<script src="http://CEA815099W/test/cim_web/js/bootstrap.min.js">
</head>
<body>
<!-- table-->
<div class="container">
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>工号</th>
<th>班别</th>
<th>站点</th>
<th>时间</th>
</tr>
</thead>
<tbody>
<!-- js处理数据库内容-->
</tbody>
<tfoot>
<tr>
<th>工号</th>
<th>班别</th>
<th>站点</th>
<th>时间</th>
</tr>
</tfoot>
</table>
</div>
</body>
</html>
Javascript:
$(document).ready(function() {
$('#example').dataTable( {
"bProcessing": true,
"sAjaxSource": "data.php"
} );
} );
</script>
<script type="text/javascript">
// For demo to fit into DataTables site builder...
$('#example')
.removeClass( 'display' );
.addClass('table table-striped table-bordered');
</script>
PHP:
<?php
$db = new PDO("oci:dbname=mfdm10", "f10mfg",'demon');
$db->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_WARNING); // 设置为警告模式
$rs = $db->prepare("select a.empid,a.shift,a.station,a.infab_time from ut_msc_newcoming a where rownum <= :num"); // SQL 需要修改
$rs->bindValue(':num', 26);
$rs->execute();
while($row=$rs->fetch()){
$data[]= array(
$row[0],
$row[1],
$row[2],
$row[3]
);
}
/* $output = array(
"sEcho" => 1,
"iTotalRecords" => count($row),
"iTotalDisplayRecords" => count($row),
"aaData" => $data
); */
$response = array();
$response['success'] = true;
$response['aaData'] = $data;
echo json_encode( $response );
//异常
function fatal($msg)
{
echo json_encode(array(
"error" => $msg
));
exit(0);
}
?>
Add my json returning from network of the console
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<meta charset="GBK">
<title></title>
</head>
<body>
{"success":true,"aaData":[["086671","NB","MSC-1","09-APR-15"],["086673","DB","MSC-2","09-APR-15"],["086678","DA","MSC-1","10-APR-15"],["086682","DA","MSC-1","10-APR-15"],["086683","NA","MSC-1","10-APR-15"],["086491","NA","MSC-2","25-MAR-15"],["086686","DA","MSC-1","10-APR-15"],["086688","DA","MSC-2","10-APR-15"],["086690","NA","MSC-2","10-APR-15"],["086496","DA","MSC-1","25-MAR-15"],["086685","NB","MSC-1","09-APR-15"],["086848","NA","MSC-2","22-APR-15"],["086516","NA","MSC-1","22-APR-15"],["086523","DA","MSC-1","22-APR-15"],["086839","DA","MSC-2","22-APR-15"],["086849","DA","MSC-1","22-APR-15"],["086528","NB","MSC-1","24-APR-15"],["086526","NB","MSC-1","27-MAR-15"],["086478","DA","MSC-1","25-MAR-15"],["086482","DB","MSC-1","27-MAR-15"],["086832","NB","MSC-1","24-APR-15"],["086840","DB","MSC-2","24-APR-15"],["086842","NB","MSC-2","24-APR-15"],["086828","DB","MSC-1","24-APR-15"],["086987","NB","MSC-1","07-MAY-15"],["086991","DB","MSC-2","07-MAY-15"]]} </body>
</html>
My original json returning, any error?

On this page in the documentation it states the following:
Reply from the server
In reply to each request for information that DataTables makes to the server, it expects to get a well formed JSON object with the following parameters....
It does not appear that your are setting these variables and this may the reason for the error message "warning:table id=example - Invalid JSON response" as your JSON, while valid JSON, is not a valid "JSON response" related to what datatables expects.

Related

PHP redirect buttons in DataTables are not working

I'm generating a table using PHP that will retrieve records from a MySQL database. I'm new to DataTables, and my problem is that the "View Products" button that generates along with the table doesn't work. Clicking the button should redirect to a new page with an entirely different table.
here's a screenshot of what it looks like, just in case I'm not making any sense
Here's the entire code for the page.
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="\WEBDEV\css\reset.css">
<link rel="stylesheet" type="text/css" href="\WEBDEV\css\stylesheet.css">
<link rel="stylesheet" type="text/css" href="\WEBDEV\css\og_stylesheet.css">
<style type="text/css">
thead {
background-color: #dc3545;
color: white;
}
</style>
</head>
<body>
<!-- HEADER -->
<?php include "includes/header.php" ?>
<?php session_start();
?>
<!-- END HEADER -->
<table class="table table-striped" id="table_id">
<thead>
<tr>
<th>Supplier ID</th>
<th>Name</th>
<th>Address</th>
<th>Contact Number</th>
<th>Supplier Details</th>
</tr>
</thead>
<tbody>
<?php
$conn = mysqli_connect("localhost", "root", "", "web_db");
$query = "SELECT * FROM Suppliers";
$search = mysqli_query($conn, $query);
if(mysqli_num_rows($search) > 0 ){
while($row = mysqli_fetch_array($search)){
?>
<form action="supplierdetails.php" method="POST">
<tr>
<td>
<?= $row['supplier_id']?>
</td>
<input type="hidden" value=< ?=$row[ 'supplier_id']?> name = "sup_id">
<input type="hidden" value=< ?=$row[ 'name']?> name = "name">
<td>
<?= $row['name']?>
</td>
<td>
<?= $row['address']?>
</td>
<td>
<?= $row['contactnumber']?>
</td>
<td><input type="submit" name="sub" value="View Products" class="btn btn-info" onclick="sample()"></td>
</tr>
</form>
<?php
}
}
?>
</tbody>
</table>
<script>
$(document).ready(function() {
$(".alert").delay(3000).fadeOut();
});
</script>
<script>
function sample() {
window.alert(document.getElementById("name").getAttribute("value"));
}
</script>
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.js"></script>
<script type="text/javascript" charset="utf8" src="/DataTables/datatables.js"></script>-->
<script type="text/javascript">
$(document).ready(function() {
$('#table_id').DataTable();
});
</script>
<script type="text/javascript" src="jquery.dataTables.js"></script>
<script type="text/javascript" src="dataTables.filter.range.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var table = $('#table_id').DataTable();
/* Add event listeners to the two range filtering inputs */
$('#min, #max').keyup(function() {
table.draw();
});
});
</script>
</body>
</html>
The buttons work perfectly before I added DataTables, by the way. I also found out that a table with hard-coded data (as in without PHP) also have buttons that work fine. I'm pretty much at my wits end here. Any help will be appreciated.
Remove the onclick="sample()"
Add this in a document.ready
$(".btn-info").on("click", function() {
window.alert(document.getElementById("name").getAttribute("value"));
});
Maybe use a window.alert('test');
since I dont see the element with the id name anywhere

Bootstrap Table show entries Don't show exact number of Cells

with my small knowledge coding PHP I struggled about 4 days to make DataTable show exact entries what customer chose. Below is my code for getting data from Mysql DataBase
<?php
include("check.php");
include("config.php");
// Create connection
//$conn = new mysqli($servername, $username, $password, $dbname);
$sql = 'SELECT * from transaction';
if (mysqli_query($db, $sql)) {
echo "";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($db);
}
$count=0;
$result = mysqli_query($db, $sql);
?>
And here is my html for displaying Table which one must have pagination and customer could choose how much cells he want to see (ex: 10, 25, 50, 100)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>მთავარი გვერდი</title>
<link href="vendor/bootstrap/css/bootstrap.min.css" rel="stylesheet"><!-- Bootstrap core CSS-->
<link href="vendor/font-awesome/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <!-- Custom fonts for this template-->
<link href="https://cdn.datatables.net/1.10.18/css/dataTables.bootstrap4.min.css" rel="stylesheet"><!-- Page level plugin CSS-->
<link href="css/sb-admin.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.18/js/dataTables.bootstrap4.min.js"></script>
</head>
<body class="fixed-nav sticky-footer bg-dark" id="page-top">
<!-- Navigation-->
<?php include("template/navigbar.php"); ?>
<!-- Breadcrumbs-->
<?php include("template/breadc.php"); ?>
<!-- Icon Cards-->
<!-- Example DataTables Card-->
<div class="card mb-3">
<div class="card-header">
<i class="fa fa-table"></i> Data Table Example</div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-striped table-bordered" id="myTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>ID</th>
<th>თქვენი ID</th>
<th>თარიღი</th>
<th>ობიექტი</th>
<th>ტერმინალი</th>
<th>თანხა</th>
<th>ჯამი</th>
</tr>
</thead>
<?php
while ($row = mysqli_fetch_assoc($result))
{
$count =$count + $row['amount'];
echo '
<tbody>
<tr>
<td>'.$row["trID"].'</td>
<td>'.$row['userID'].'</td>
<td>'.$row['trDate'].'</td>
<td>'.$row['obName'].'</td>
<td>'.$row['terName'].'</td>
<td>'.$row['amount'].'</td>
<td>'.$count.'</td>
</tr>
</tbody>
';
}
?>
</table>
</div>
</body>
</html>
<script>
$(document).ready( function () {
$('#myTable').DataTable();
});
</script>
But the result is always full Table with Showing 1 to 1 of 1 entries but in the table it shows me more then 25 cell.See Screenshot attached
Please let me know what I m doing wrong?
I posted this as an answer because it solves the issue.
<tbody> must be outside of loop
Put your tbody tags outside of while statement.
I Hope this code will help you
'aLengthMenu': [[50, 100, 150, -1], [50, 100, 150, "All"]],
'iDisplayLength': '50'
You have to add the tbody BEFORE start the loop.
In your code, you are creating a new tbody for each row instead just a row.
Dont forget to close the tbody after the php close tag
tbody must be out site of the loop

Pagination problem makes data table not work

Please help,
I have problem with a data table. The data table does not work when I use this but it's working when it's outside of this. Please help:
<div id="content">
<?php
$pages_dir = 'pages/admin';
if(!empty($_GET['p'])){
$pages = scandir($pages_dir, 0);
unset($pages[0], $pages[1]);
$p = $_GET['p'];
if(in_array($p.'.php', $pages)){
include($pages_dir.'/'.$p.'.php');
}
else {
echo 'Page Not Found :(';
}
}
else {include($pages_dir.'/profile.php');}
?>
</div>
Then the other full script page, in this page data table is not working, but when I try this outside code before, it works.
<?php
$connect = mysqli_connect("localhost", "root", "", "keep");
$query ="SELECT * FROM barang ORDER BY ID DESC";
$result = mysqli_query($connect, $query);
?>
<!DOCTYPE html>
<html>
<head>
<title>Webslesson Tutorial | Datatables Jquery Plugin with Php MySql and Bootstrap</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/dataTables.bootstrap.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.12/css/dataTables.bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container">
<h3 align="center">Datatables Jquery Plugin with Php MySql and Bootstrap</h3>
<br />
<div class="table-responsive">
<table id="employee_data" class="table table-striped table-bordered">
<thead>
<tr>
<td>ID</td>
<td>Nama</td>
<td>Kategori</td>
<td>Harga</td>
<td>Jumlah</td>
<td>Supplier</td>
</tr>
</thead>
<?php
while($row = mysqli_fetch_array($result))
{
echo '
<tr>
<td>'.$row["id"].'</td>
<td>'.$row["nama"].'</td>
<td>'.$row["kategori"].'</td>
<td>'.$row["harga"].'</td>
<td>'.$row["jumlah"].'</td>
<td>'.$row["supplier"].'</td>
</tr>
';
}
?>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('#employee_data').DataTable();
});
</script>
Please help, I'm new to PHP programming. Sorry for the bad English.

Error in Display Date using Jquery Datepicker in PHP

I am new in PHP. I have a code which upload a file and store in Mysql database. I create a web form using php. In this form I use jquery datepicker. my problem is that when I run my code its not display date properly. The result of my code is shown below:
But when I use same code without PHP its work properly. I cant understand what is the problem?
Here is my code:
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test123"; // Database name
//$tbl_name="members"; // Table name
$con=mysql_connect("localhost","root","");
if(! $con)
{
die('Connection Failed'.mysql_error());
}
mysql_select_db("test123",$con);
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
//$desired_dir=$options['upload_dir']."user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 755); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>File Upload</title>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$("#mydate").datepicker({
dateFormat: "dd-M-y"
}).datepicker("setDate", new Date());
});
</script>
</head>
<body>
<form action="" method="POST" enctype="multipart/form-data">
<table>
<tr> <td width="327">
<input type="text" id="mydate"> </td> </tr>
<tr> <td>
<input type="file" name="files[]" multiple/></td> </tr>
<tr> <td>
<input type="submit"/></td> </tr>
</table>
</form>
</body>
</html>
I just make two file with name of form.php and second is form1.php
now my code is working well
form1.php
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery UI Datepicker - Default functionality</title>
<link rel="stylesheet" type="text/css" href="newstyles.css">
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" href="/resources/demos/style.css">
<script>
$(function() {
$("#mydate").datepicker({
dateFormat: "dd-M-y"
}).datepicker("setDate", new Date());
});
</script>
</head>
<body>
<form action="form.php" method="POST" enctype="multipart/form-data">
<table width="664" >
<tr>
<td height="34" colspan="6" class="DivSubHeaderCellTop"><p> Morning Breifing</p></td>
</tr>
<tr>
<td colspan="6" class="DivSubHeaderCellTop">Upload File</td>
</tr>
<tr><td> </td> <td> MB | Falcons</td> <td width="154"><input type="text" id="mydate">
<td>
</td>
</tr>
<tr> <td width="157" height="23"> </td> </tr>
<tr>
<td colspan="4" bordercolorlight="#006666"> <input type="file" name="files[]" multiple/> </td>
<td width="215">
<input type="submit"/>
</td>
<tr>
<td height="75">
</td>
<td width="116">
</td> </tr>
</table>
</form>
</body>
</html>
form.php
<?php
$host="localhost"; // Host name
$username="root"; // Mysql username
$password=""; // Mysql password
$db_name="test123"; // Database name
//$tbl_name="members"; // Table name
$con=mysql_connect("localhost","root","");
if(! $con)
{
die('Connection Failed'.mysql_error());
}
mysql_select_db("test123",$con);
if(isset($_FILES['files'])){
$errors= array();
foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
$file_name = $key.$_FILES['files']['name'][$key];
$file_size =$_FILES['files']['size'][$key];
$file_tmp =$_FILES['files']['tmp_name'][$key];
$file_type=$_FILES['files']['type'][$key];
if($file_size > 2097152){
$errors[]='File size must be less than 2 MB';
}
$query="INSERT into upload_data (`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$file_name','$file_size','$file_type'); ";
$desired_dir="user_data";
//$desired_dir=$options['upload_dir']."user_data";
if(empty($errors)==true){
if(is_dir($desired_dir)==false){
mkdir("$desired_dir", 755); // Create directory if it does not exist
}
if(is_dir("$desired_dir/".$file_name)==false){
move_uploaded_file($file_tmp,"$desired_dir/".$file_name);
}else{ // rename the file if another one exist
$new_dir="$desired_dir/".$file_name.time();
rename($file_tmp,$new_dir) ;
}
mysql_query($query);
}else{
print_r($errors);
}
}
if(empty($error)){
echo "Success";
}
}
?>
That type error occurs when missing css file of datepicker.so please verify you load required css file. And file upload only work when submit click so in php code you may check it post request or not
<?php
if(isset($_POST))
{
// do php work
}
?>
// and after your html code
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>datepicker demo</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<div id="datepicker"></div>
<script>
$( "#datepicker" ).datepicker();
</script>
</body>
</html>
View online Demo

Json Data are not show in html file in angularjs using php files

How do I set the php files in angularJS to set the id of any json code?
Hole and sole this is my final code
<!DOCTYPE html>
<html class="no-js" lang="en" ng-app="myBusStopApp">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My bus stop - Real time data</title>
<link href="http://fonts.googleapis.com/css?family=Open+Sans" rel="stylesheet" type="text/css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.1.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.13/angular.min.js"></script>
<script type="text/javascript">
angular.module('myBusStopApp', [])
.controller('myBusStopCtrl', ['$scope', '$http', function ($scope, $http) {
//$scope.realTimeData;
var url ="http://192.168.1.10/android_connect/JsonReturn.php";
// var url = "http://reis.trafikanten.no/reisrest/realtime/getrealtimedata/3010435" + "?callback=JSON_CALLBACK";
alert(url);
$http.jsonp(url)
.success(function(data){
alert(url);
$scope.realTimeData = data;
});
}]);</script>
</head>
<body style="margin-top:2%;font-size:14px;font-family:Open Sans; padding-left:2%;padding-right:2%;">
<div ng-controller="myBusStopCtrl">
<center>
<div class="table-responsive" style="max-width:800px;">
<table class="table table-striped" >
<thead>
<tr class="info">
<th>Bus#</th>
<th>Destination</th>
<th>Wait time</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="item in realTimeData">
<td>{{item.id}}</td>
<td>{{item.email}}</td>
<td>kk</td>
</tr>
</tbody>
</table>
</div>
</center>
</div>
</body>
</html>
When I try any other setting, then it causes a chrome error
Resource interpreted as Script but transferred with MIME type
text/html
And following is my PHP code
<?php header('Access-Control-Allow-Origin: *'); ?>
<?php
// set up the connection variables
$db_name = 'hotel_db';
$hostname = 'localhost';
$username = 'root';
$password = '';
// connect to the database
$dbh = new PDO("mysql:host=$hostname;dbname=$db_name", $username, $password);
// a query get all the records from the users table
$sql = 'SELECT * FROM user';
// use prepared statements, even if not strictly required is good practice
$stmt = $dbh->prepare( $sql );
// execute the query
$stmt->execute();
// fetch the results into an array
$result = $stmt->fetchAll( PDO::FETCH_ASSOC );
// convert to json
$json = json_encode( $result );
// echo the json string
echo $json;
?>
What can i do in this situation
Please help me of this Thanx in advance
in upeer code i have include this
<?php header('Access-Control-Allow-Origin: *'); ?>
but show me error in chrome but i have run this code in android phone
XMLHttpRequest cannot load http://192.168.1.10/android_connect/JsonReturn.php. Request header field X-Requested-With is not allowed by Access-Control-Allow-Headers.
Please please help me out of this situation please
Just add:-
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
at the top of php page inside
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: *");
your code..
?>
It allows you to enable cors(cross origin resource sharing).
if you returning a json data add the relevant header for json,
header('Content-Type: application/json');
echo $json;

Categories

Resources