why is ajax duplicating the whole page in php - php

I am connected to mysql database and I want to generate table with content from mysql with php after clicking on a button by a user.
But after clicking on a button, the whole page with header, body, etc. is generated to div where are table and php script. The button also duplicate visually of course.
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-2">
<meta http-equiv="content-language" content="cs">
<meta name="author" content="Marek Ciz, Tomas Veskrna">
<meta name="keywords" content="galerie, iis, iis projekt 2016, informacni system">
<link rel="icon" type="image/png" href="./icons/gallery.png" />
<title>Employee</title>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#expo-but").click(function(){
$.ajax({
url: "./employee.php",
type: "post",
data: {action: "exposition"},
success: function(result) {
$("#table").html(result);
}});
});
});
</script>
</head>
<body>
<div class="page">
<div class="menu">
<button id="expo-but">Exposition</button>
</div>
<div id="table-wrapper">
<div id="table">
<table class="striped">
<thead>
<tr class="header">
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<?php
include './db_init.php';
//echo $_SESSION["user"];
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row[id_zamestnance]."</td>";
echo "<td>".$row[jmeno]."</td>";
}
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
</body>
</html>

More correct solution will be separate html and php part:-
Your html should be like this:-
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-2">
<meta http-equiv="content-language" content="cs">
<meta name="author" content="Marek Ciz, Tomas Veskrna">
<meta name="keywords" content="galerie, iis, iis projekt 2016, informacni system">
<link rel="icon" type="image/png" href="./icons/gallery.png" />
<title>Employee</title>
<link rel="stylesheet" type="text/css" href="./mystyle.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(#expo-but).trigger("click"); // on document ready trigger click itself so that table will load initially
$("#expo-but").click(function(){
$.ajax({
url: "./employee.php",
type: "post",
data: {action: "exposition"},
success: function(result) {
$("#table").html(result);
}});
});
});
</script>
</head>
<body>
<div class="page">
<div class="menu">
<button id="expo-but">Exposition</button>
</div>
<div id="table-wrapper">
<div id="table">
</div>
</div>
</div>
</body>
</html>
And php(employee.php) will be like this:-
<?php
include './db_init.php';
//echo $_SESSION["user"];
$data = '';
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
$data .= "<tr>";
$data .="<td>".$row[id_zamestnance]."</td>";
$data .="<td>".$row[jmeno]."</td>";
}
}
}
$final_data = '<table class="striped"><thead><tr class="header"><td>Id</td><td>Name</td></tr></thead><tbody>'.$data.'</tbody></table>';
echo $final_data;
?>
Note:-
Why i am saying more correct because in your php page you also have same code what you written in your current html div, so no need to do the repetition.
Just on document load call the click function of button ,that's it.

cut this code and add this code to top of the page
<?php
include './db_init.php';
//echo $_SESSION["user"];
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row[id_zamestnance]."</td>";
echo "<td>".$row[jmeno]."</td>";
}
}
exit();
}
?>

this is a normal mistake most of us do, I suggest you to request to another php page instead requesting the same page.
table.php
<table class="striped">
<thead>
<tr class="header">
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody>
<?php
include './db_init.php';
//echo $_SESSION["user"];
if(isset($_POST['action'])){
if($_POST['action'] == "exposition") {
$sql = "SELECT id_zamestnance, jmeno FROM Zamestnanec";
$result = mysql_query($sql)or die(mysql_error());
while ($row = mysql_fetch_assoc($result)) {
echo "<tr>";
echo "<td>".$row[id_zamestnance]."</td>";
echo "<td>".$row[jmeno]."</td>";
}
}
}
?>
</tbody>
</table>
and change the url in the scrtipt
<script>
$(document).ready(function(){
$("#expo-but").click(function(){
$.ajax({
url: "./table.php",
type: "post",
data: {action: "exposition"},
success: function(result) {
$("#table").html(result);
}});
});
});

Related

How do I run my PHP code on the click of a button?

I'm trying to build a website for school project. I want the schoolResponse() function to happen after clicking the Submit button. If I remove the jQuery function it works but then it shows a default value when I load the page.
Here's my code:
<!DOCTYPE html>
<html>
<head>
<title>NHG</title>
<meta charset="UTF-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link type="text/css" rel="stylesheet" href="css/normalize.css"/>
<link type="text/css" rel="stylesheet" href="css/style.css"/>
<link type="text/css" rel="stylesheet" href="css/resposive.css"/>
</head>
<body>
<header>
<div id="main-head">
<h2 id="main-heading">sKoolBook</h2>
</div>
</header>
<section>
<div id="container">
<div id="wrapper">
<form method="POST">
<select name="school">
<option value="none" name="none">Please Select a School...</option>
<option value="NHG">New Horizon Gurukul</option>
</select>
<input type="submit" class="button"/>
<?php
error_reporting(0);
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
?>
<script>
$('.button').click(
function(
<?php schoolResponse(); ?>
);
);
</script>
</form>
</div>
</div>
</section>
<footer>
</footer>
</body>
</html>
You should use jQuery/AJAX to do this.
<script>
$('.button').click(
$.ajax({
url: 'yoururl.php',
data: $("form").serialize(), //Better to put an ID to the form or something
success: function(data){
//DO something with your data
}
})
);
</script>
There are other functions you should check to properly use ajax requests.
In yoururl.php you should do something like
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
You can't achieve it like this. Here is one solution:
<?php
error_reporting(0);
$school = $_POST['school'];
function schoolResponse() {
if ($_POST['school'] == 'none'){
echo 'nothing';
} else {
echo 'something';
}
}
if($_POST['school']) schoolResponse();
?>
It would be better if you replace error_reporting(0); with error_reporting(E_ALL); for example, because otherwise php errors will be disabled.
And remove this part:
<script>
$('.button').click(
function(
<?php schoolResponse(); ?>
);
);
</script>
But it is very very basic example.

Autocomplete working on localhost, but not on server

I have a search formula with an autocomplete function which works just fine on localhost, but as soon as I put it on a remote server it stops working.
I hope you can help me.
Here is some Code:
index.php:
<!DOCTYPE html>
<html lang="de">
<head>
<?
header("Content-Type: text/html; charset=iso-8859-1");
?>
<link rel="stylesheet" href="css/jquery-ui-1.10.3.custom.min.css" />
<link rel="stylesheet" href="css/bootstrap.min.css" />
<link rel="stylesheet" href="css/style.css" />
<script src="js/jquery-1.10.2.min.js"></script>
<script src="js/jquery-ui-1.10.3.custom.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div id="wrap">
<h1 class="text-center">Suche</h1>
<div class="row">
<div class="col-xs-6 col-sm-4 col-md-4 col-xs-offset-6 col-sm-offset-4 col-md-offset-4">
<form method='POST' action=''>
<input type='text' name='food' id="country_name" class="form-control txt-auto"/>
<input type='submit' value='search'>
</form>
</div>
</div>
</div>
<script src="js/auto.js"></script>
</body>
</html>
ajax.php
<?php
header('Content-Type: text/html; charset=UTF-8');
require_once 'config.php';
if($_GET['type'] == 'country'){
$result = mysql_query("SELECT *
FROM table
WHERE name LIKE '%".strtoupper($_GET['name_startsWith'])."%'
LIMIT 8");
$data = array();
while ($row = mysql_fetch_array($result)) {
array_push($data, $row['name']);
}
echo json_encode($data);
}
?>
auto.js
$('#country_name').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'ajax.php',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'country'
},
success: function( data ) {
response( $.map( data, function( item ) {
return {
label: item,
value: item
}
}));
}
});
},
autoFocus: true,
minLength: 0
});
You are missing the php in the HTML and if your server isn't set up for short open tags- may cause an issue, and as shown in the comments - there should not be any html content before the header declaration.
should be:
<?php
header("Content-Type: text/html; charset=iso-8859-1");
?>

Can not bind data on view using angular.js and PHP

i need to display data on the page using Angular.js. First i fetched all data from DB using PHP .Here no data is displaying on the page.I am getting the below retrieved data in my browser console.
all data [{"0":"1","id":"1","1":"","name":"","2":"","pass":"","3":"","email":""},{"0":"2","id":"2","1":"subhra","name":"subhra","2":"12345","pass":"12345","3":"subh#gmail.com","email":"subh#gmail.com"},{"0":"3","id":"3","1":"rakesh","name":"rakesh","2":"0901209474","pass":"0901209474","3":"maini","email":"maini"},{"0":"4","id":"4","1":"raj","name":"raj","2":"23457","pass":"23457","3":"rai","email":"rai"},{"0":"5","id":"5","1":"Rahul","name":"Rahul","2":"098765","pass":"098765","3":"shinha","email":"shinha"}]
I am explaining my code below.
read.js:
var app=angular.module('Read_data',[]);
app.controller('readController',function($scope){
$.ajax({
type:'GET',
url:"php/read.php",
success: function(data){
$scope.data=data;
console.log('all data',$scope.data);
}
})
});
read.php:
<?php
//database settings
$connect = mysqli_connect("localhost", "root", "*******", "AngularTest");
$result = mysqli_query($connect, "select * from users");
$data = array();
while ($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
print json_encode($data);
?>
index.html:
<!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" ng-app="Read_data">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Demo of Angular.js</title>
<link rel="stylesheet" href="css/style.css" type="text/css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/angularjs.js" type="text/javascript"></script>
<script src="js/read.js" type="text/javascript"></script>
</head>
<body>
<center ng-controller="readController">
<div id="body">
<div id="content">
<table align="center">
<tr>
<th colspan="5">add data here.</th>
</tr>
<th> Name</th>
<th> Email</th>
<th> Password</th>
<th colspan="2">Operations</th>
</tr>
<tr ng-repeat="users in data">
<td>{{users.name}}</td>
<td>{{users.email}}</td>
<td>{{users.pass}}</td>
<td align="center"><img src="images/pencil_small.png" align="EDIT" /></td>
<td align="center"><img src="images/cross-small-icon.png" align="DELETE" /></td>
</tr>
</table>
</div>
</div>
</center>
</body>
</html>
Please help me to resolve this issue and bind all data in table successfully.
Angular is not aware of updated data. Use $scope.$apply if you are not using $http for AJAX.
var app=angular.module('Read_data',[]);
app.controller('readController',function($scope){
$.ajax({
type:'GET',
url:"php/read.php",
success: function(data){
$scope.$apply(function(){
$scope.data = angular.fromJson(data);
});
console.log('all data',$scope.data);
}
})
});
or use $http (recommended)
var app=angular.module('Read_data',[]);
app.controller('readController',function($scope, $http){
$http.get('php/read.php').
then(function(data) {
// this callback will be called asynchronously
// when the response is available
$scope.data = data.data;
}, function(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
});

Changing the content of jquery mobile

I am developing mobile app using jquery mobile framework and I would like to change page content using javascript and ajax but I don't get the expected result.Could you help me please.
Here is the code :
connection.php
<?php
$dbhost="localhost";
$dbuser="root";
$dbpass="";
$db="mobileapp";
$conn=mysql_connect($dbhost,$dbuser,$dbpass) or die("Could not connect");
mysql_select_db($db);
?>
index1.php
<?php
include 'connection.php';
$fetch="SELECT * from users";
/**
$result=mysql_query($query) or die(mysql_error());
//while($person=mysql_fetch_array($result)){
$person=mysql_fetch_array($result)
echo json_encode($person);**/
while ($row = mysql_fetch_array($fetch, MYSQL_ASSOC)) {
$row_array['id'] = $row['id'];
$row_array['username'] = $row['username'];
$row_array['city'] = $row['city'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
//}
?>
index.html
<html>
<head>
<title>My Page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0.1/jquery.mobile-.0.1.min.css" />
<script src="http://code.jquery.com/jquery-1.6.4.min.js"></script>
<script src="http://code.jquery.com/mobile/1.0.1/jquery.mobile-1.0.1.min.js"> </script>
<script type="text/javascript" src="global.js">
</script>
</head>
<body>
<div data-role="page" id="page1">
<div data-role="header">
<h1>Railway Station</h1>
</div><!-- /header -->
<div data-role="content">
<input type="button" value="Refresh" id="submit" data-icon="refresh" /></br>
<ul data-role="listview" id="list"> </ul>
<script id="source" language="javascript" type="text/javascript">
$(document).live('pageinit',function (event) {
$.ajax({
url: 'index1.php',
data:"",
dataType: 'json',
success: function(rows)
{
for(var i=0;i<rows.length;i++)
{
var row = rows[i];
var id = row[0];
var name= row[1];
var city= row[2];
$('#list').append("<li>id:"+id+"Name:"+name+"City:"+city+"</li>");
}
};
});
});
</script>
</div>
</div>
<div data-role="footer">
<h1>©AmeyPat.All Rights Reserved.</h1>
</div><!-- /footer -->
</body>
</html>

Switch between two javascript functions

basically I want php to decide which version of the site pieces to load
something along the lines of:
<?php
$sql="SELECT _1 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_1=mysql_query($sql);
if($result_1 < 10) { ?>
<script type="text/javascript">
function setdescription_1() {
document.getElementById('title_box').innerHTML = 'Alchemist';
}
</script>
<?php
}
else {
?>
<script type="text/javascript">
function setdescription_1() {
document.getElementById('title_box').innerHTML = 'Master Alchemist';
}
</script>
<?php
}?>
issue is that they both run so even if I set the condition to true I still get the second.
The complete source which is identical to what is being viewed-as-source as far as I can tell but none of the php shows up in the site preview (it is actually there though because my other computer can view the site without seeing the php but when it views source it can see it which it shouldn't be able to):
<head>
<title>Blank</title>
<link rel="icon" type="image/png" href="Pictures/favicon.png">
<meta name="description" content="" />
<meta name="keywords" content="" />
<meta name="author" content="" />
<meta name="owner" content="" />
<meta name="copyright" content="" />
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" href="TreeStyle.css" type="text/css" />
</head>
<body>
<div style="width:100%; height:12.5%;">
<p style="font-size: 300%;"><b>Skill Tree: Alchemist</b></p>
</div>
<div style="width:100%; height:75%;">
<?php
$sql="SELECT _1 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_1=mysql_query($sql);
if($result_1 < 10)
{
?>
<script type="text/javascript">
function setdescription_1()
{
document.getElementById('title_box').innerHTML = 'Alchemist';
document.getElementById('desc_box').innerHTML = 'Turn surroundings into base element costs.';
}
</script>
<?php
}
else
{
?>
<script type="text/javascript">
function setdescription_1()
{
document.getElementById('title_box').innerHTML = 'Master Alchemist';
document.getElementById('desc_box').innerHTML = 'Equiped Philosopher's Stone allows bypass of element costs.';
}
</script>
<?php
}
$sql="SELECT _2 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_2=mysql_query($sql);
if($result_2 < 10)
{
?>
<script type="text/javascript">
function setdescription_2()
{
document.getElementById('title_box').innerHTML = 'Learn Runes';
document.getElementById('desc_box').innerHTML = 'Create Runes and Cores up to Lv.<?php echo "$result_2" ?>';
}
</script>
<?php
}
else
{
?>
<script type="text/javascript">
function setdescription_2()
{
document.getElementById('title_box').innerHTML = 'Comprehension';
document.getElementById('desc_box').innerHTML = 'Create Runes and Cores up to Lv.10';
}
</script>
<?php
}
?>
<script type="text/javascript">
function cleardescription()
{
document.getElementById('title_box').innerHTML = 'Skill Name';
document.getElementById('desc_box').innerHTML = 'This is the skill description.';
}
</script>
<table>
<tr>
<td></td>
<td><img src="Alchemist.png" /></td>
<td><img src="Blank_Tile.png"/></td>
<td><a href='AddSkillPoints.php?skill=_2' onmouseover="setdescription_2()" onmouseout="cleardescription()"><img src="Learn_Runes.png"/></td>
etc..............
</table>
</div>
<div style="width:100%; height:12.5%;">
<b><p id="title_box" style="font-size: 150%;">Skill Name</p></b><br />
<p id="desc_box">This is the skill description.</p>
</div>
</div>
</body>
</html>
I do not believe you get both if your PHP is actually parsed.
If it is not parsed, you will see the code you pasted exactly as you pasted it if you look at the source of the web page
Make sure the php is parsed - if not, then that is the issue.
A script tag will generally not interfere with parsing unless you have to post processing that does not allow the tags - for example if you use some kind of framework where you are not supposed to enter php but instead some tokenised code
Here is a better example - note I moved the script to the head but did not optimise really - so the php can be more elegant if you get both values in one call and create an object array
<?PHP
$sql="SELECT _1 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_1=mysql_query($sql);
$sql="SELECT _2 FROM Player_Registry WHERE Player_Name = $_SESSION[user_name]";
$result_2=mysql_query($sql);
%><html>
<head>
<title>Blank</title>
<link rel="icon" type="image/png" href="Pictures/favicon.png">
.
.
<meta http-equiv="content-type" content="text/html;charset=UTF-8" />
<link rel="stylesheet" href="TreeStyle.css" type="text/css" />
<script type="text/javascript">
var result1 = parseInt("<?PHP echo $result_1; ">,10);
var skillLevel = (result1>=10?'Master ':'')+'Alchemist';
var skillDesc = result1>=10?"Equipped with Philosopher´s Stone allows bypass of element costs.":"Turn surroundings into base element costs.";
var runeLevel = result2>=10?'Comprehension':'Learn Runes';
var runeDesc = 'Create Runes and Cores up to Lv.'+result2;
window.onload=function() {
setdescription_1();
}
function setdescription_1() {
document.getElementById('title_box').innerHTML = skillLevel;
document.getElementById('desc_box').innerHTML = skillDesc;
}
function setdescription_2() {
document.getElementById('title_box').innerHTML = runeLevel;
document.getElementById('desc_box').innerHTML = runeDesc;
}
function cleardescription() {
document.getElementById('title_box').innerHTML = 'Skill Name';
document.getElementById('desc_box').innerHTML = 'This is the skill description.';
}
</script>
</head>

Categories