I've been trying to create a simple grade calculator app with ajax functionality. The ajax seems to be working quite nicely, however the separate PHP file I've created 'response.php' is not GET-ting the data from the form. So it is just echoing out 'Uh oh'.
I'm not sure what I'm doing wrong here and I've been going over my code for a while. Can anyone help?
<!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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../../favicon.ico">
<title>Grade Calculator</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<link rel="stylesheet" href="style.css">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET","response.php");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
function sendAjax() {
xhr.send();
document.getElementById('gradeForm').style.display = 'none';
}
</script>
</head>
<body>
<!-- <div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Project name</a>
</div>
<div class="collapse navbar-collapse">
<ul class="nav navbar-nav">
<li class="active">Home</li>
<li>About</li>
<li>Contact</li>
</ul>
</div>
</div>
</div> -->
<div class="container">
<div class="starter-template">
<h1>Bootstrap starter template</h1><br>
<form action="index.php" method="get" id="gradeForm">
<div class="form-group">
<label for="currentGrade">What is your current Grade</label>
<input type="text" name="currentGrade"><br>
</div>
<div class="form-group">
<label for="targetGrade">What is your target Grade</label>
<input type="text" name="targetGrade"><br>
</div>
<div class="form-group">
<label for="finalWorth">What is your final worth?</label>
<input type="text" name="finalWorth"><br>
</div>
<button type="button" class="btn btn-default" onclick="sendAjax()">Submit</button>
</form>
<div id="ajax">
</div>
</div>
</div><!-- /.container -->
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Latest compiled and minified JavaScript -->
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
</body>
</html>
response.php
<?php
$currentGrade = $_GET['currentGrade'];
$targetGrade = $_GET['targetGrade'];
$finalWorth = $_GET['finalWorth'];
if (isset($currentGrade, $targetGrade, $finalWorth)) {
echo $currentGrade;
echo $targetGrade;
echo $finalWorth;
} else {
echo 'Uh oh!';
}
// if (empty($currentGrade, $targetGrade, $finalWorth)) {
// echo 'Nothing...';
// } else {
// $neededMark = $currentGrade - $targetGrade;
// $neededMark = $neededMark / $finalWorth;
// $neededMark = $neededMark * 100;
// $neededMark = round($neededMark);
?>
As far as I am aware you can't retrieve the data because, using the verb (GET) for your call, requires a querystring appended to the target url, this way:
xhr.open("GET","response.php?key1=value1&key2=value2...etc...");
However In my opinion would be better to use the POST verb:
xhr.open("POST","response.php", true);
then set a valid request header like:
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
collect the params (your new sendAjax function):
function sendAjax() {
var values = [];
var form = document.getElementById("gradeForm");
for (var i = 0, l = form.length; i < l; i++)
{
if(form[i].type === "text")
{
values.push(form[i].name +"="+ form[i].value);
}
};
var params = values.join("&");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(params);
document.getElementById('gradeForm').style.display = 'none';
}
Now you can retrieve the data in the response.php page, via the superglobal $_POST
The reason response.php is unable to get the data from the form is that your AJAX isn't sending the data from the form. Unlike a form submit, AJAX won't automatically send the form - you need to set the parameters explicitly.
This is how you do ajax request, without jQuery. You can re-purpose this for your own need.
I made this work as single page script:
test.php
<?php
// Handle GET Ajax Request
if (count($_GET))
{
print_r($_GET);
exit();
}
?>
<script type="text/javascript">
// helper function - http://stackoverflow.com/a/8567149/2332336
function loadXMLDoc(targetUrl, resultDiv) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 ) {
if(xmlhttp.status == 200){
document.getElementById(resultDiv).innerHTML = xmlhttp.responseText;
}
else if(xmlhttp.status == 400) {
alert('There was an error 400')
}
else {
alert('something else other than 200 was returned')
}
}
}
xmlhttp.open("GET", targetUrl, true);
xmlhttp.send();
}
// usage
loadXMLDoc('test.php?a=1&b=2', 'result');
</script>
<div id="result"></div>
Related
So, i want to populate div with id "listberita" with html code from ajax response.
Here is the php code where contain div with "listberita" id
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Jabary - Website Budaya Jabar</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
<script src="https://kit.fontawesome.com/f8535c9b97.js" crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="berita.css">
</head>
<body>
<!-- Navbar -->
<?php include 'php/navbar.php'; ?>
<div class="container my-5">
<div class="kategoricaption mb-5">
<div class="row">
<div class="col">
<h1 class="text-center fw-bold judulkategori">Berita</h1>
<hr class="mx-auto" style="width:10%; background-color: #f49f16;">
</div>
</div>
</div>
<div class="card-group vgr-cards" id="listberita">
</div>
</div>
<!-- footer -->
<?php include 'php/footer.php'; ?>
<script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
<script src="js/bootstrap.bundle.min.js "></script>
<script src="berita.js"></script>
</body>
</html>
Here is my ajax js code
$(this).ready(function() {
getNews()
function getNews() {
$.ajax({
type: "GET",
url: "_php/getBerita.php",
dataType: "JSON",
success: function(response) {
var kode;
$.each(response, function(i, obj) {
console.log(kode)
kode += '<div class="card kartu pb-3"><div class="card-img-body"><img class="card-img" src="img/Berita/' + obj.gambar_berita + '" alt="Card imagecap"></div><div class="card-body"><h4 class="card-title">' + obj.nama_berita + '</h4><p class="card-text">' + obj.keterangan_berita.substring(0, 250) + '....</p>Read More</div></div>'
$('#listberita').html(kode);
})
}
});
}
})
Here is my php code where ajax request to (php_/getBerita.php)
<?php
include '../koneksi.php';
$result = $conn->query("SELECT * from tbl_berita");
while($row=$result->fetch_assoc()){
$data[]=$row;
}
echo json_encode($data);
?>
The code above is working, it's return the data i want. But there is a problem.
Here is the problem
How to get rid the "undefined" thing on the beginning of div?
Try changing your var kode; to var kode = "";.
When you define the variable without initializing it, it will be undefined. And then your loop is appending text to an undefined variable. That's probably why.
I have an Ajax script on a PHP page which is to run a php script on clicking a button.
The code is as follows:
<script>
$('#signup-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'insertfromsession.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data){
$('#form-container').fadeOut('slow', function(){
$('#form-container').fadeIn('slow').html(data);
});
document.getElementById('submitBtn').disabled = true;
document.getElementById("submitBtn").value="Thanks!";
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
When I first open the web page the script isn't run, but if i click back and repeat the process the script executes without an issue. Does anyone know what is causing the issue?
Insert.php which runs this code is here:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/submit.js"></script>
<!-- /.website title -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
<!-- CSS Files -->
<link href="css/bootstrap.min.css" rel="stylesheet" media="screen">
<link href="css/font-awesome.min.css" rel="stylesheet">
<link href="fonts/icon-7-stroke/css/pe-icon-7-stroke.css" rel="stylesheet">
<link href="css/animate.css" rel="stylesheet" media="screen">
<link href="css/owl.theme.css" rel="stylesheet">
<link href="css/owl.carousel.css" rel="stylesheet">
<style type="text/css">
body { background: white !important; } /* Adding !important forces the browser to overwrite the default style applied by Bootstrap */
</style>
<!-- Colors -->
<link href="css/css-index.css" rel="stylesheet" media="screen">
<!-- <link href="css/css-index-green.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-purple.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-red.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-orange.css" rel="stylesheet" media="screen"> -->
<!-- <link href="css/css-index-yellow.css" rel="stylesheet" media="screen"> -->
<!-- Google Fonts -->
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Lato:100,300,400,700,900,100italic,300italic,400italic,700italic,900italic" />
</head>
<div id="top"></div>
<div class="fullscreen landing parallax" style="background-image:url('images/fireworks.jpg');" data-img-width="2000" data-img-height="1333" data-diff="100">
<div class="overlay">
<div class="container">
<div class="row">
<div class="col-md-10">
<!-- /.logo -->
<!-- /.main title -->
<h2 class="wow fadeInLeft">Thank you for submitting your details</h2>
<h2 class="wow bounce infinite">While you are here, why not apply for one of other fantastic products?</h2>
<?php
session_start();
include ("dbconnect.php");
// prepare and bind
$stmt = $conn->prepare("INSERT INTO wills (forename,surname,postcode,telno,email,ipaddress,capturedate,url,user) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
$stmt->bind_param("sssssssss", $forename, $surname, $postcode, $telno, $email, $ipaddress, $capturedate, $url, $user);
$forename = $_POST["forename"];
$surname = $_POST["surname"];
$postcode = $_POST["postcode"];
$telno = $_POST["telno"];
$email = $_POST["email"];
$ipaddress = $_SERVER['REMOTE_ADDR'];
$capturedate = date('Y-m-d H:i:s');
$url ="www.test.com";
$user ="testuser";
$_SESSION["forename"] = $forename;
$_SESSION["surname"] = $surname;
$_SESSION["postcode"] = $postcode;
$_SESSION["telno"] = $telno;
$_SESSION["email"] = $email;
$_SESSION["ipaddress"] = $ipaddress;
$_SESSION["capturedate"] = $capturedate;
$_SESSION["url"] = $url;
$_SESSION["user"] = $user;
echo "<br>"."Forename: ".$forename."<br>";
echo "Surname: ".$surname."<br>";
echo "Telno: ".$telno."<br>";
echo "Email: ".$email."<br>";
echo "IP Address: ".$ipaddress."<br>";
echo "Session User: ".$_SESSION["user"]."<br>";
if (!$stmt->execute()) {
echo $stmt->error;
} else {
}
$stmt->close();
$conn->close();
?>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<div class="text-center">Back to Main Page</div>
<div class="col-md-12">
<!-- /.product 1 -->
<div class="col-sm-6 feat-list">
<i class="pe-7s-phone pe-5x pe-va wow fadeInUp"></i>
<div class="inner">
<h4>Grab a Mobile SIM</h4>
<p>With a SIM only contract, you get the all the benefits of an ongoing contract, without the additional high cost of a handset.
Short-term SIM only contracts give you freedom and flexibility. All the networks offer them from as little as 30 days, and you can then keep them rolling month-by-month
</p>
<form method="post" id="signup-form" autocomplete="off">
<div class="form-group">
<input type="submit" class="btn btn-success btn-block btn-lg" id="submitBtn" value="Apply for Mobile Sim?">
</div>
</form>
</div>
</div>
<!-- /.product 2 -->
<div class="col-sm-6 feat-list">
<i class="pe-7s-like2 pe-5x pe-va wow fadeInUp"></i>
<div class="inner">
<h4>Debt Plan</h4>
<p>Do you have more than £5,000 worth of debt?<br>
Do you need help to reduce the monthly payments?<br>
If so, find out if you qualify to write off up to 80% of your debt here</p>
<form method="post" id="signup-formdebt" autocomplete="off">
<div class="form-group">
<input type="submit" class="btn btn-success btn-block btn-lg" id="submitBtndebt" value="Get help now">
</div>
</form>
</div>
</div>
</div>
<!-- /.footer -->
<footer id="footer">
<div class="container">
<div class="col-sm-4 col-sm-offset-4">
<!-- /.social links -->
<div class="social text-center">
<ul>
<li><a class="wow fadeInUp" href="https://twitter.com/"><i class="fa fa-twitter"></i></a></li>
<li><a class="wow fadeInUp" href="https://www.facebook.com/" data-wow-delay="0.2s"><i class="fa fa-facebook"></i></a></li>
</ul>
</div>
<i class="pe-7s-up-arrow pe-va"></i>
</div>
</div>
</footer>
<!-- /.javascript files -->
<script src="js/jquery.js"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/custom.js"></script>
<script src="js/jquery.sticky.js"></script>
<script src="js/wow.min.js"></script>
<script src="js/owl.carousel.min.js"></script>
<script>
new WOW().init();
</script>
</body>
<script>
$( document ).ready(function() {
$('#signup-form').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'insertfromsession.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data){
$('#form-container').fadeOut('slow', function(){
$('#form-container').fadeIn('slow').html(data);
});
document.getElementById('submitBtn').disabled = true;
document.getElementById("submitBtn").value="Thanks!";
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
</script>
<script>
$( document ).ready(function() {
console.log( "ready!" );
$('#signup-formdebt').submit(function(e){
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'insertfromsessiondebt.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data){
$('#form-container').fadeOut('slow', function(){
$('#form-container').fadeIn('slow').html(data);
});
document.getElementById('submitBtndebt').disabled = true;
document.getElementById("submitBtndebt").value="Thanks!";
})
.fail(function(){
alert('Ajax Submit Failed ...');
});
});
});
</script>
</html>
I think I solved the issue and it has nothing at all to do with the AJAX. It actually appears to be an issue with the session variables. I moved the session variables on the insert.php right to the top before anything else and this makes it work as intended.
Thanks for your efforts guys
You should use a document.ready function. Here is a link to the jQuery version documentation : https://learn.jquery.com/using-jquery-core/document-ready/
I was trying to create a custom directive, and inside the template of my directive, I have included a directive of angular-bootrstrap library. In this case a popover directive.
When I run my app, the following error appears:
Error: [$compile:multidir] Multiple directives [bar, bar] asking for template on: navbar-default progress-bar" ng-class="type && 'progress-bar-' + type" role="navigation>progressbar" aria-valuenow="{{value}}" aria-valuemin="0" aria-valuemax="{{max}}" ng-style="{width: >percent + '%'}" aria-valuetext="{{percent | number:0}}%" ng-transclude="" bar="">`
What's wrong in my code?
app.js
(function () {
'use strict';
//var angular = require('angular');
function config($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/init.html',
controller: 'MainCtrl',
controllerAs: 'main',
resolve: {
jobsData: function(ServiceMain) {
return ServiceMain.getData();
},
itemsData: function(ServiceMain,$resource) {
return ServiceMain.getItems();
},
}
});
}
angular.module('testApp', ['ngRoute','app.controller','ui.bootstrap'])
.config(config);
})();
home.php
<!DOCTYPE html>
<html lang="en" ng-app="testApp">
<head>
<meta charset="UTF-8">
<title>Document</title>
<!-- inject:css -->
<link rel="stylesheet" href="css/style.css">
<!-- endinject -->
<!-- bower:css -->
<link rel="stylesheet" href="bower_components/animate.css/animate.css">
<link rel="stylesheet" href="bower_components/ng-sortable/dist/ng-sortable.min.css">
<link rel="stylesheet" href="bower_components/angular-hotkeys/build/hotkeys.min.css">
<link rel="stylesheet" href="bower_components/bootstrap/dist/css/bootstrap.css">
<!-- endinject -->
</head>
<body>
HERE I USED MY CUSTOM DIRECTIVE
<nav bar class="navbar navbar-default" role="navigation"></nav>
<!-- Here we'll to load the templates of the App -->
<div ng-view></div>
<!-- bower:js -->
<script src="bower_components/angular/angular.js"></script>
<script src="bower_components/angular-route/angular-route.js"></script>
<script src="bower_components/jquery/dist/jquery.js"></script>
<script src="bower_components/angular-bootstrap/ui-bootstrap-tpls.js"></script>
<script src="bower_components/bootstrap/dist/js/bootstrap.js"></script>
<!-- endinject -->
<!-- inject:js -->
<script src="components/app.js"></script>
<script src="components/controllerMain.js"></script>
<script src="components/directiveUserBar.js"></script>
<script src="components/serviceMain.js"></script>
<!-- endinject -->
<script type="text/javascript">
var base_url = '<?php echo base_url(); ?>';
</script>
</body>
</html>
directiveUserBar.js
(function () {
'use strict';
function userBarDirective() {
return{
restrict: 'EA',
templateUrl:'views/user-bar.html',
link: function (scope, element, attrs) {
// DOM manipulation/events here!
scope.showMe = function(){
alert('showSomething!');
}
scope.logOut = function(){
alert('log out me!');
}
},
controller: function($scope){
$scope.modules = ['a','b','c','d'];
$scope.user = "Gonzalo"
}
};
}
angular
.module('testApp')
.directive('bar',userBarDirective);
})();
The template of my directive: user-bar.html
<div class="container-fluid">
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#userMenu">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Info Plant</a>
</div>
<div class="collapse navbar-collapse" id="userMenu">
<ul class="nav navbar-nav" ng-repeat="module in modules">
<li><a ng-click="showMe()">{{module}}</a></li>
</ul>
<div class="form-group">
<a popover-placement="bottom" popover="user" popover-title="Gonzalo"> Log Out</a>
</div>
</div>
</div>
My first thought is that you are using two directives on the same element and both specify a template or templateurl property.
That said, looking at your code, we're not getting the full picture because your error is telling you about progressbar but that directive isn't used in any of the code you've pasted.
In the future, a working plunker that shows the error is much more helpful in determining where errors lie.
My implementation is at : http://i.cs.hku.hk/~hsbashir/Project_Work/Listview/list_view.html
The first entry is when the list is hardcoded. Second and third ones are when they are extracted from the server using xmlhttp object. I am unable to understand why in the 2nd & 3rd list the formatting is different.
Original HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script>
lastRecord=0;
function loadNews(){
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
var x = document.getElementById("sample");
x.innerHTML = "hello";
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var news = document.getElementById("news_mesgs");
news.innerHTML += xmlhttp.responseText;
$("news_mesgs").enhanceWithin();
}
}
xmlhttp.open("GET", "queryNews.php?lastRecord="+lastRecord,true);
xmlhttp.send();
}
</script>
</head>
<body onload="loadNews()">
<div data-role="page" id="pageone">
<div data-role="main" class="ui-content">
<ul data-role="listview" data-inset="true" id="news_mesgs">
<li>
<a href="#">
<img src="http://i.cs.hku.hk/~hsbashir/Project_Work/Listview/suicide-panel.jpg">
<h2> HKU identifies a new strategy to protect flowers from freezing stress </h2>
<p> sample description </p>
</a>
</li>
</ul>
</div>
</div>
<div id="sample"></div>
</body>
</html>
Updated HTML:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.css">
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.2/jquery.mobile-1.4.2.min.js"></script>
<script>
lastRecord=0;
function loadNews(){
$('#sample').html( 'hello' );
$.get(
"queryNews.php?lastRecord="+lastRecord,
function( data ) {
$('#news_mesgs').append( data )
.enhanceWithin();
}
);
}
</script>
</head>
<body onload="loadNews()">
<div data-role="page" id="pageone">
<div data-role="main" class="ui-content">
<ul data-role="listview" data-inset="true" id="news_mesgs">
<li>
<a href="#">
<img src="http://i.cs.hku.hk/~hsbashir/Project_Work/Listview/suicide-panel.jpg">
<h2> HKU identifies a new strategy to protect flowers from freezing stress </h2>
<p> sample description </p>
</a>
</li>
</ul>
</div>
</div>
<div id="sample"></div>
</body>
</html>
PHP
<?
...
mysql_connect($host,$username,$password);
mysql_select_db($database) or die( "Unable to select database");
$query = "SELECT * FROM News_Info";
$result = mysql_query($query) or die( "Unable to execute query");
while ($row = mysql_fetch_array($result)){
print "<li>";
print "<h2>".$row['Title']."</h2>";
print "<p>sample description is here</p>";
print "</a>";
print "</li>";
}
?>
The second and third are added after the widget has been initialized. You therefore have to re-enhance (refresh) the widget each time you make an update to it. And you can do that using the $(parent_of_new_content).listview('refresh'). In your case you would have to call the following:
$('#news_mesgs').listview( 'refresh' );
Just out of curiosity, is there any particular reason why you're using plain vanilla JS for your ajax call? If you were to use jQuery (recommended) your function would be:
lastRecord=0;
function loadNews(){
$('#sample').html( 'hello' );
$.get(
"queryNews.php?lastRecord="+lastRecord,
function( data ) {
$('#news_mesgs').append( data )
.listview( 'refresh' );
}
);
}
EDIT
Please note that in the above code .enhanceWithin() has been replaced with .listview('refresh')
JS FIDDLE DEMO
I am trying to use jqmobi with PHP where everything is working but when I try to use PHP session it's not working. First when I use jquery post then it will retrieve data from server but when I reload page then session is destroyed.
I have kept session_start() in every file but still of no use. So if anybody have worked with jqmobi and PHP, share your experience. I am posting my main index.php file:
<?php
session_start();
?>
<!DOCTYPE html>
<!--HTML5 doctype-->
<html>
<head>
<title>UI Starter</title>
<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-capable" content="yes" />
<META HTTP-EQUIV="Pragma" CONTENT="no-cache" >
<link rel="stylesheet" type="text/css" href="http://cdn.app-framework-software.intel.com/2.0/af.ui.base.css"/>
<link rel="stylesheet" type="text/css" href="http://cdn.app-framework-software.intel.com/2.0/icons.css" />
<link rel="stylesheet" type="text/css" href="http://cdn.app-framework-software.intel.com/2.0/af.ui.css" />
<!-- http://code.jquery.com/jquery-1.10.1.min.js -->
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script src="./js/lib/jquery.validate.min.js"></script>
<script src="./js/jq.appframework.js"></script>
<script src="http://cdn.app-framework-software.intel.com/2.0/appframework.ui.min.js"> </script>
<script src="./fcharts/FusionCharts/FusionCharts.js"></script>
<!-- include touch on desktop browsers only -->
<script>
// $.ui.showBackButton = false;
if (!((window.DocumentTouch && document instanceof DocumentTouch) || 'ontouchstart' in window)) {
var script = document.createElement("script");
script.src = "plugins/af.desktopBrowsers.js";
var tag = $("head").append(script);
//$.os.android = true; //let's make it run like an android device
//$.os.desktop = true;
}
</script>
</head>
<body>
<div id="afui"> <!-- this is the main container div. This way, you can have only part of your app use UI -->
<!-- this is the header div at the top -->
<div id="header">
<a onclick="$.ui.toggleSideMenu()" id="mainbuon" class="menuButton" style="float:right"></a>
</div>
<div id="content">
<!-- here is where you can add your panels -->
<div title='Management' id="elogin" class="panel" selected="true"
data-load="notloadedPanel" data-unload="notunloadedPanel">
<h2 >login</h2>
<form id="sample" style="position:absolute;width:250px;height:350px; left:50%; top:50%;margin-left:-130px;margin-top:-50px;">
<input type="email" id="email" name="email" value="" placeholder="username"style="text-align:center;" >
<div id="error"></div>
<input type="password" id="password" name="password" value="" placeholder="password" style="text-align:center;" >
<div id="error1"></div>
<a class="button" onclick="validate()" >Login</a>
</form>
<footer>
</footer>
</div>
<div title='List' data-defer="evelist.php" id="elist" class="panel" data-header="testheader"
data-tab="navbar_list" data-load="loadedPanel" data-unload="unloadedPanel">
</div>
<div id="setting" class="panel" title='Management' data-defer="Setting.php" data-load="settingloadedPanel"
data-unload="settingunloadedPanel" data-tab="navbar_list" >
</div>
<div id="missreport" class="panel" data-defer="MissReports.php" title='Management' data-load="reportloadedPanel"
data-unload="reportunloadedPanel" data-tab="navbar_list" >
</div>
<header id="testheader">
<a onclick="$.ui.toggleSideMenu()" id="mainbuon" class="menuButton" style="float:left"></a>
<!-- <a id="backButton" onclick="$.ui.goBack()" class='button'>Go Back</a> -->
<h1>Events List</h1>
</header>
</div> <!-- content ends here #smessage -->
<!-- bottom navbar. Add additional tabs here -->
<div id="navbar">
<div class="horzRule"></div>
<a href="#Dashboard" id='navbar_dash' class='icon home'>Dashboard</a>
<a href="#elist" id='navbar_list' class='icon home'>list</a>
<a href="#aevent" id='navbar_add' class='icon home'>Add ent</a>
<a href="#smessage" id='navbar_sent' class='icon home'>Sent Msg</a>
<a href="#sendmessage" id='navbar_send' class='icon home'>Send Msg</a>
</div>
<!-- this is the default left side nav menu. If you do not want any, do not include these -->
</div>
</body>
<script type="text/javascript">
var webRoot = "./";
$.ui.autoLaunch = false; //By default, it is set to true and you're app will run right away. We set it to false to show a splashscreen
$(document).ready(function(){
//
$.ui.launch();
});
$.ui.backButtonText="Back"
$(document).bind("swipeLeft",function(){
$.ui.toggleSideMenu(false);
});
$(document).bind("swipeRight",function(){
$.ui.toggleSideMenu(true);
});
//$.ui.useAjaxCacheBuster=true;
function logout(){
var rt= "<?php echo session_destroy(); ?>";
$.ui.loadContent("#elogin",false,false,"slide");
} /***login form panel start here****/
function notloadedPanel(){
$.ui.disableSideMenu();
$('#mainbuon').hide();
$.ui.clearHistory();
}
function notunloadedPanel(){
$.ui.enableSideMenu();
$('#mainbuon').show();
}
function validate(){
var validator = $("#sample").validate({
rules: {
email: {
required: true,
}
, password: {
required: true,
}
},
errorPlacement: function(error, element) {
if (element.attr("name") == "email" ) {
// error.insertAfter("#error");
error.appendTo('#error');
} else {
//error.insertAfter(element);
error.appendTo('#error1');
} },submitHandler: function() {
$.post(webRoot + 'parameter.php', {
email:$('#email').val(),password:$('#password').val(),Login:'Login'
}, function (data) {
if($.trim(data)=='success'){
$.ui.loadContent("#elist",false,false,"slide");
}else{
alert("wrong username and password");
}
});
}
});
if(validator.form()){
$('form#sample').submit();
}
}
/***login form panel ends here****/
document.addEventListener("DOMContentLoaded", init, false);
$.ui.ready(function () {
//This function will get executed when $.ui.launch has completed
// $.ui.showBackButton = false;
});
/* This code is used for native apps */
var onDeviceReady = function () {
AppMobi.device.setRotateOrientation("portrait");
AppMobi.device.setAutoRotate(false);
webRoot = AppMobi.webRoot + "/";
//hide splash screen
AppMobi.device.hideSplashScreen();
$.ui.blockPageScroll();
};
document.addEventListener("appMobi.device.ready", onDeviceReady, false);
</script>
The code should be sufficient, however you need to find out if session_destroy or unset($_SESSION) was called else where
<?php
session_start();
$_SESSION['key'] = "value";
?>