My jQuery Mobile page does not load content via $.get which is bind into pageinit event, but does so when I hit refresh (F5), why is that so?
My HTML page igra.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<!-- stili za custom temo, jquery, jquery mobile, phonegap-->
<link rel="stylesheet" href="themes/what.min.css" />
<link rel="stylesheet" href="jquerymobile.css" />
<script src="jquery191.js"></script>
<script src="jquerymobile.js"></script>
<script src="phonegap.js"></script>
<script src="main.js"></script>
<link rel="stylesheet" href="stil.css" />
</head>
<body>
<div data-role="page" id="igra">
<div data-theme="a" data-role="header">
347 coins
<h3>WHAT?</h3>
Home
</div>
<div data-role="content" class="igracontent"> </div>
</div>
</body>
</html>
My main.js with jQuery Mobile code:
$( document ).delegate("#igra", "pageinit", function() {
var par = qs["battlefield"];
$.get('igra.php?battlefield='+par, function(data2) {
$('div.igracontent').append(data2).trigger('create');
});
});
//parse url parameter
var qs = (function(a) {
if (a == "") return {};
var b = {};
for (var i = 0; i < a.length; ++i)
{
var p=a[i].split('=');
if (p.length != 2) continue;
b[p[0]] = decodeURIComponent(p[1].replace(/\+/g, " "));
}
return b;
})(window.location.search.substr(1).split('&'));
In igra.php I make SQL query and retrieve some data which I format in jQuery Mobile style and echo it back.
I know jQuery Mobile does not load head into DOM in subsequent pages, so main.js is also included in index.html head which is landing page of my app. All transitions to new pages are by normal ajax querying (I do not prevent default behaviour).
So what happens? When I navigate to igra.html?battlefield=3 the pageinit event does happen but content which I load via $.get from php page does not get inserted! If I hit F5(refresh) the content does get loaded into page. Can anybody explain and help? :) Thank you!
Related
I have a div tag with many anchor tags in it. On clicking a lick it should open a php page in another div tag of the same page.
<!DOCTYPE html>
<html lang="en">
<head>
<title>Test</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<header>
<h2>Test</h2>
</header>
<div class="topnav" id="myTopnav">
page1
page2
page3
page4
</div>
<div id="content" >
</div>
<script>
$(function(){
$("#myTopnav a").click(function(e){
e.preventDefault(); //To prevent the default anchor tag behaviour
var url = this.href;
$("#content").load(url);
});
});
</script>
</body>
</html>
I have a nav bar and on clicking the links it should load a php page in content div. I tried the above code but it does not work.
The Reason is that its a local file at your system, you need to set up a webserver.
If the problem exist further then you can add "Cross Origin" headers to the called php files.
If it's not working for you, try the full context and see what the error message might be:
$( "#content" ).load( url, function( response, status, xhr ) {
if ( status == "error" ) {
window.alert(xhr.status + " " + xhr.statusText);
}
});
I'm have a problem. I want connect PHP and PostgreSQL, but don't know how.
HTML:
<?php
?>
<!DOCTYPE html>
<html lang = "pt-br">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Título -->
<title>test</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Font-Awesome CSS -->
<link href="css/font-awesome.min.css" rel="stylesheet">
<!-- Ubicua-cloud CSS -->
</head>
<body>
<form action = "" name = "f1" method = "post" style = "">
<input type = "text" id = "telefone">
<button type = "button" id = "init">iniciar sessão</button>
</form>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="js/bootstrap.min.js"></script>
<!-- Ubicua-cloud-js -->
<script src="login.js"></script>
</body>
</html>
DB connect:
<?php
$connect=pg_connect ("host=localhost dbname=test port=5432 user=postgres password=28974220")or
die("Error");
?>
JS to catch user informations:
$(document).ready(function(){
$('#init').click(function(){
var telefone=$('#telefone').val();
alert(telefone);
$.ajax({
type:"POST",
dataType:'json',
url:'login.Ajax.php',
data:{telefone:telefone},
success: function(response){
if(response.resposta==true){
$('#msg').html(response.msg);
window.location='test.php';
}
else{
$('#msg').html(response.msg);
}
},error:function(){
alert('error');
}
});
});
});
The PHP code to validate informations:
<?php
include_once('includes/connect.php');
$msg_ok=false;
$msg_error='O sistema está indisponível.';
if(isset($_POST['telefone']))
if($_POST['telefone']!="")
$telefone=$_POST['telefone'];
$consulta=pg_query($connect, ("Select * from test where telefone='$telefone"));
if(pg_num_rows($consulta)>0)
$msg_ok=true;
$usua=pg_fetch_array($consulta);
session_start();
$_SESSION['id']=$usua[0];
$_SESSION['telefone']=$usua[1];
$msg_error='Logado';
else
$msg_error='Telefone não existe.';
endif;
else
$msg_error='Telefone incorreto.';
endif
else
$msg_error='Erro.';
endif;
$saidaJson=array('resposta' => $msg_ok, 'msg' => msg_error);
echo json_encode($saidaJson);
?>
I received error messages to catch user informations, help, please.
I'm assuming you are using PDO. If so, you need make changes to the database connection file(substitute the variables with your database values):
<?php
$db = new PDO("pgsql:dbname=$dbname;host=$host";port=$port, $dbuser, $dbpass);
?>
I solved the problem, but now I'm needing exchange informations between the php and js...I have a script that simulates a person typing and need it to talk to users calling them by their proper names, but I don't know how, I need concatenate one variable in JS, but before that I need store one PHP variable in one JS variable.
var init = document.getElementById('init_text');
var init_text = 'Hi <nome>, I'm your friend!';
function digit(str, el) {
var char = str.split('').reverse();
var typer = setInterval(function () {
if (!char.length) return clearInterval(typer);
var next = char.pop();
el.innerHTML += next;
}, 60);
}
digit(init_text, init);
I have this code on my index.php page:
require_once 'includes/settings.php';
require_once 'includes/data_functions.php';
if($_GET["section"] == '1') {
require_once 'includes/includes.php';
require_once 'pages/'.$_GET["id"].'.php';
exit();
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Integra | <?php echo $PageTitle; ?></title>
<meta content='width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no' name='viewport'>
<?php require_once 'includes/includes.php'; ?>
<!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.3.0/respond.min.js"></script>
<![endif]-->
</head>
<body class="skin-black-light sidebar-mini sidebar-collapse">
and i use JQuery .load to load pages into a popup div, when loading the page it has the $_GET variable section = 1 so it runs the above code
here is the function that i use to .load pages:
function LoadModal(page, title) {
title = title || '';
$( "#modal_page" ).fadeIn("slow");
$( "#modal_title" ).html(title);
$("#modal_page_body").html('<h2 align="center">Loading...</h3><p align="center"><i class="fa fa-refresh fa-spin fa-5x"></i></p>'); //$('#LoadingDiv').show();
$("#modal_page_body").load(page, function(){
});
$("html, body").animate({ scrollTop: 0 }, "slow");
}
and then to call this function:
<i class="fa fa-plus"></i>
so the includes.php file is included in all pages.
this includes some jquery files which have some functions in.
when opening a page in the popup using jquery .load these specific jquery funtcions are not working at all however if i remove the $_GET var (section = 1) to open the page not in the jquery popup (.load) the functions are working fine
what could be causing these to stop working only in the jquery .load
Your URL (/section/page?seq=add) doesn't include section=1 in the query string, so $_GET['section'] is not set.
i want to delete a record that are showing in while loop from the database but before deleting i want to display a confirmation box.The code i have written is below.it is working fine but to delete record i need to pass an id that i haave described in the code
------index.php starts
<!DOCTYPE html><html><head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A jQuery Confirm Dialog Replacement with CSS3 | Tutorialzine Demo</title>
<link href='http://fonts.googleapis.com/css?family=Cuprum&subset=latin' rel='stylesheet' type='text/css'>
<link rel="stylesheet" type="text/css" href="css/styles.css" />
<link rel="stylesheet" type="text/css" href="jquery.confirm/jquery.confirm.css" />
</head>
<body>
<div id="page">
<?php
$sql = "SELECT * FROM tablename";
$result = db_query($sql);
while(db_fetch($result))
{
?>
<div class="item">
<div class="delete"></div>
</div>
<?php
}
?>
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="jquery.confirm/jquery.confirm.js"></script>
<script src="js/script.js"></script>
</body>
</html>
----index.php ends
----jquery.confirm.js file starts
(function($){
$.confirm = function(params){
if($('#confirmOverlay').length){
// A confirm is already shown on the page:
return false;
}
var buttonHTML = '';
$.each(params.buttons,function(name,obj){
// Generating the markup for the buttons:
buttonHTML += ''+name+'<span></span>';
if(!obj.action){
obj.action = function(){};
}
});
var markup = [
'<div id="confirmOverlay">',
'<div id="confirmBox">',
'<h1>',params.title,'</h1>',
'<p>',params.message,'</p>',
'<div id="confirmButtons">',
buttonHTML,
'</div></div></div>'
].join('');
$(markup).hide().appendTo('body').fadeIn();
var buttons = $('#confirmBox .button'),
i = 0;
$.each(params.buttons,function(name,obj){
buttons.eq(i++).click(function(){
// Calling the action attribute when a
// click occurs, and hiding the confirm.
obj.action();
$.confirm.hide();
return false;
});
});
}
$.confirm.hide = function(){
$('#confirmOverlay').fadeOut(function(){
$(this).remove();
});
}
})(jQuery);
----jquery.confirm.js file ends
-----script.js file starts
$(document).ready(function(){
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
$.confirm({
'title' : 'Delete Confirmation',
'message' : 'You are about to delete this item. <br />It cannot be restored at a later time! Continue?',
'buttons' : {
'Yes' : {
'class' : 'blue',
'action': function(){
elem.slideUp();
//sql delete query will be written here... in where condition i need to pass the fetched record id from index.php file in where condtion
}
},
'No' : {
'class' : 'gray',
'action': function(){} // Nothing to do in this case. You can as well omit the action property.
}
}
});
});
});
-----script.js ends
You can use the html data attribute and retrieve it with .data jQuery method
In your HTML:
<div class="delete" data-id="{$id}"></div>
In your Javascript
$('.item .delete').click(function(){
var elem = $(this).closest('.item');
var id = elem.data('id'); /* this is your db id */
});
Are you sure you want to send a query from Javascript? The usual way to do this is to send a request (via jQuery) with that specific id, to a script which runs the query (server side), and returns a response.
Now, since you add the item divs, using a while, why not add an id property to the divs, which contain the id from the database, something like
<div id="item<?php echo $row['id'];?>" class="item">
<div class="delete">
</div>
This way, the $('.item .delete').click handler has access to the item's id, by parsing the target's id property, and you don't need to pass it explicitly to jQuery.
Here you can use hidden field to save value for id and then use jquery to retrieve it from hidden field..
while(db_fetch($result))
{
?>
//here we need to pass the fetched record id to script.js file,but i dont know how
<input type="hidden" id="hid_id" value="<?php echo 'fetched id';?>" />
<div class="item">
<div class="delete"></div> //here i have applied css i.e it displays wrong icon, when we click on that icon ,it is showing confirmation box. Everything is perfect in this.. but i wnat to pass and id.. im new to jquery
</div>
<?php
}
?>
And then in jquery when using confirm box you can get value by id hid_id .
I have a SlickGrid set up, it is reading data from my database with PHP, my problem is arising when i try to save the data back to my database, I am trying to use JSON to give me an array that I can then use to write back to the database, i have see this thread explaining this:
Saving changes in SlickGrid
So I have the hidden form element in my code, and am using JSON to encode the data variable, the assign it to the data hidden input on the form, this form posts to a page called save_price.php, the trouble is when I print_r, or var_dump the data variable, I get null as an output, I think it might be something to do with how I am using PHP to add the content into the data variable, either that or I am doing something really obviously wrong, hopefully you can see what the problem is, there isn't a great deal of documentation online about retrieving/saving to a db with PHP, so I'm kinda stuck banging my head against the wall on this one, here's my code:
Ok so I found the problem, just incase anyone is struggling to get this all to work, here is the working code, it gets data from a database, then sends the changed data to another page for processing, it nees a little bit of refinements, that will happen once I've got it all implemented:
<?php
include("includes/check_session.php");
require_once('includes/functions.php');
require_once('includes/config.php');
$data = '';
$i = 0;
$query = "
SELECT * FROM `prices`";
$result = mysql_query($query);
while($row = mysql_fetch_array($result, MYSQL_ASSOC)){
$data .= '
data['.$i.'] = {
id: "'.$row['id'].'",
title: "'.$row['title'].'",
duration: "'.$row['duration'].'",
percentComplete: "'.$row['percentComplete'].'",
start: "'.$row['start'].'",
finish: "'.$row['finish'].'",
effortDriven: "'.$row['effortDriven'].'"
};
';
$i++;
echo $data;
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset=utf-8>
<?php // include("includes/cms_head_scripts.php"); ?>
<link rel="stylesheet" href="css/slick.grid.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/smoothness/jquery-ui-1.8.5.custom.css" type="text/css" media="screen" charset="utf-8" />
<link rel="stylesheet" href="css/examples.css" type="text/css" media="screen" charset="utf-8" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" src="js/jquery.json.js"></script>
</head>
<body>
<div id="content_cont">
<div id="main">
<div style="position:relative">
<div style="width:600px;">
<div id="myGrid" style="width:100%;height:500px;"></div>
</div>
</div>
pricing
</div><!-- #main -->
</div><!-- #content_cont -->
<script src="lib/firebugx.js"></script>
<script src="lib/jquery-ui-1.8.5.custom.min.js"></script>
<script src="lib/jquery.event.drag-2.0.min.js"></script>
<script src="slick.core.js"></script>
<script src="plugins/slick.cellrangeselector.js"></script>
<script src="plugins/slick.cellselectionmodel.js"></script>
<script src="slick.editors.js"></script>
<script src="slick.grid.js"></script>
<script type="text/javascript">
var grid;
var data = [];
var columns = [
{id:"title", name:"Title", field:"title", editor:TextCellEditor},
{id:"duration", name:"Duration", field:"duration", editor:TextCellEditor},
{id:"%", name:"% Complete", field:"percentComplete", editor:TextCellEditor},
{id:"start", name:"Start", field:"start", editor:TextCellEditor},
{id:"finish", name:"Finish", field:"finish", editor:TextCellEditor},
{id:"effort-driven", name:"Effort Driven", field:"effortDriven", editor:TextCellEditor}
];
var options = {
editable: true,
enableCellNavigation: true,
asyncEditorLoading: false,
autoEdit: true
};
$(function() {
<?php echo $data ?>
grid = new Slick.Grid($("#myGrid"), data, columns, options);
})
</script>
<form method="POST" action="save_price.php">
<input type="submit" value="Save">
<input type="hidden" name="data" value="">
</form>
<script type="text/javascript">
$(function() {
$("form").submit(
function() {
$("input[name='data']").val($.JSON.encode(data));
}
);
});
</script>
</body>
</html>