I'm working with this code snippet plugin : http://www.steamdev.com/snippet/ for my blog
but the plugin doesn't work on page load.
It only works at first page refresh.
I load my content in a specific div with jquery.ajax request and i'm trying this :
$(window).on("load", function(){
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
I also tried to trigger the load event but i don't know if it is correct..
Another question : i build my html with php string like this example:
$string = '<pre class="cplus">
#include <iostream>
int main()
{
//c++ code
}
</pre>
<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
echo $string; // ajax -> success
but the PHP snippet shows empty (the c++ is ok). Any other way (or plugin) to show php code snippet on my page?
Thank you.
SOLVED:
The problem isn't the plugin or Iserni suggestions.. i had a problem in page load (ajax)..
This is how i load the pages:
function pageload(hash) {
if(hash == '' || hash == '#php')
{
getHomePage();
}
if(hash)
{
getPage();
}
}
function getHomePage() {
var hdata = 'page=' + encodeURIComponent("#php");
//alert(hdata);
$.ajax({
url: "homeloader.php",
type: "GET",
data: hdata,
cache: false,
success: function (hhtml) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
});
}
function getPage() {
var data = 'page=' + encodeURIComponent(document.location.hash);
//alert(data);
$.ajax({
url: "loader.php",
type: "GET",
data: data,
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(html);
$('#body').fadeIn('slow');
}
});
}
$(document).ready(function() {
// content
$.history.init(pageload);
$('a[href=' + window.location.hash + ']').addClass('selected');
$('a[rel=ajax]').click(function () {
var hash = this.href;
hash = hash.replace(/^.*#/, '');
$.history.load(hash);
$('a[rel=ajax]').removeClass('selected');
$(this).addClass('selected');
$('#body').hide();
$('.loading').show();
getPage();
return false;
});
// ..... other code for menus, tooltips,etc.
I know this is experimental , i have made a mix of various tutorials but now it works..
comments are much appreciated..
Thanks to all.
The PHP snippet seems empty because the browser believes it's a sort of HTML tag.
Instead of
$string = '<pre class="php">
<?php
function foo()
{
// PHP code
}
?>
</pre>';
you need to do:
// CODE ONLY
$string = '<?php
function foo()
{
// PHP code
}
?>';
// HTMLIZE CODE
$string = '<pre class="php">'.HTMLEntities($string).'</pre>';
As for the jQuery, it is probably due to where you put the jQuery code: try putting it at the bottom of the page, like this:
....
<!-- The page ended here -->
<!-- You need jQuery included before, of course -->
<script type="text/javascript">
(function($){ // This wraps jQuery in a safe private scope
$(document).ready(function(){ // This delays until DOM is ready
// Here, the snippets must be already loaded. If they are not,
// $("pre.cplus") will return an empty wrapper and nothing will happen.
// So, here we should invoke whatever function it is that loads the snippets,
// e.g. $("#reloadbutton").click();
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
});
})(jQuery); // This way, the code works anywhere. But it's faster at BODY end
</script>
</body>
Update
I think you could save and simplify some code by merging the two page loading functions (it's called the DRY principle - Don't Repeat Yourself):
function getAnyPage(url, what) {
$('.loading').show(); // I think it makes more sense here
$.ajax({
url: url,
type: "GET",
data: 'page=' + encodeURIComponent(what),
cache: false,
success: function (html) {
$('.loading').hide();
$('#content').html(hhtml);
$('#body').fadeIn('slow');
}
// Here you ought to allow for the case of an error (hiding .loading, etc.)
});
}
You can then change the calls to getPage, or reimplement them as wrappers:
function getHomePage(){ return getAnyPage('homeloader.php', "#php"); }
function getPage() { return getAnyPage('loader.php', document.location.hash); }
ok for the first issue I would suggest to
see what your JS error console saying
ensure correspondent js plugin file is loaded
and use the following code when you are using ajax (the key thing is "success" event function):
$.ajax({
url: 'your_url',
success: function(data) {
$("pre.cplus").snippet("cpp",{style:"acid"});
$("pre.php").snippet("php",{style:"acid"});
}
});
for the second issue lserni answered clearly
you need to use to jquery on load function like so:
$(function(){
RunMeOnLoad();
});
Related
I'm new into php and I am trying to call code from another file.
I try to use ajax to so, because later I would like to add parameters. But unfortunattely for me nothing appen when I click on my button.
I have a button in my file admin.php that is written like this:
<button onclick="clickMe()"> Click </button>
And in the same file I have my ajax code in script balise:
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: test() {
alert('ok');
}
error : test(){
alert("error");
}
});
}
</script>
And here is the code that I'm trying to call in my ajax, the function test in the file delete.php:
<?php
function test() {
echo "Hello the World! ";
}
?>
I wondering if I maybe need to put the code in delete.php in a function ?
Do you think I need to post the entirety of my admin.php file, even thought a lot of the code is not related to the question ?
EDIT: I forgot to mention; i have require delete file in my admin one:
require 'delete.php';
I don't know jQuery, but I think your code should look something like this:
<?php
// delete.php
// make somthing
return 'Helo Word';
<script>
function clickMe() {
$.ajax( {
url: 'delete.php',
type: "POST",
success: response => {
alert(reponse);
},
error: error => {
alert(error);
}
});
}
</script>
let's assume that your js code is working(i'm bad with JQuery). The JS code and the PHP code are living in different worlds but can connect by HTTP requests(XML-AJAX) and some others.
You can do a request to a PHP page like my-domain.com/the-page.php?get_param_1=value(GET method), and you can pass the same params(and a little more) by POST method. GET and POST params are looking like :
param_name=param_value¶m_name=param_value¶m_name=param_value
You can't call directly PHP function(like var_dump('123);), but you can do this request with JS my-domain.com/the-page.php?call_func=myFunc123&printIt=HelloMate
to php page
<?php
function myFunc123($printText) { echo $printText; }
if (array_key_exists('call_func', $_GET)) {
$param_callFunc = $_GET['call_func'];
if ($param_callFunc == 'myFunc123') { myFunc123($_GET['printIt']); }
}
?>
Yes, you can pass any existing function name and call it, but it's not safe in future usage. Above, i use "page" word because you should do a request, not php file read or access.
Here is how I finally did it :
I gived an id to my button:
<button id="<?php echo $rows['id']; ?>" onclick ="deletedata(this.id)">Delete</button>
I give in deletedata the parameter this.id, it's a way to give the id of the button as parameter, then I use Ajax to call delete:
<script type="text/javascript">
// Function
function deletedata(id){
$.ajax({
// Action
url: 'admin',
// Method
type: 'POST',
data: {
// Get value
id: id,
action: "delete"
},
success:function(response){
}
});
};
</script>
Here is the tricky thing, I didn't use a fonction as I thought I needed. Instead I did this :
if (isset($_POST["action"])) {
echo "Hello the World! ";
// Choose a function depends on value of $_POST["action"]
if($_POST["action"] == "delete"){
mysqli_query($conn, "DELETE FROM bdd_sites WHERE id = " . $_POST['id'].";");
}
header('Location: '.$_SERVER['REQUEST_URI']);
}
?>
What i want to do is, to show a message based on certain condition.
So, i will read the database after a given time continuously, and accordingly, show the message to the user.
But i want the message, to be updated only on a part of the page(lets say a DIV).
Any help would be appreciated !
Thanks !
This is possible using setInterval() and jQuery.load()
The below example will refresh a div with ID result with the content of another file every 5 seconds:
setInterval(function(){
$('#result').load('test.html');
}, 5000);
You need a ajax solution if you want to load data from your database and show it on your currently loaded page without page loading.
<script type="text/javascript" language="javascript" src=" JQUERY LIBRARY FILE PATH"></script>
<script type="text/javascript" language="javascript">
var init;
$(document).ready(function(){
init = window.setInterval('call()',5000);// 5000 is milisecond
});
function call(){
$.ajax({
url:'your server file name',
type:'post',
dataType:'html',
success:function(msg){
$('div#xyz').html(msg);// #xyz id of your div in which you want place result
},
error:function(){
alert('Error in loading...');
}
});
}
</script>
You can use setInterval if you want to make the request for content periodically and update the contents of your DIV with the AJAX response e.g.
setInterval(makeRequestAndPopulateDiv, "5000"); // 5 seconds
The setInterval() method will continue calling the function until clearInterval() is called.
If you are using a JS library you can update the DIV very easily e.g. in Prototype you can use replace on your div e.g.
$('yourDiv').replace('your new content');
I'm not suggesting that my method is the best, but what I generally do to deal with dynamic stuff that needs access to the database is the following method :
1- A server-side script that gets a message according to a given context, let's call it "contextmsg.php".
<?php
$ctx = intval($_POST["ctx"]);
$msg = getMessageFromDatabase($ctx); // get the message according to $ctx number
echo $msg;
?>
2- in your client-side page, with jquery :
var DIV_ID = "div-message";
var INTERVAL_IN_SECONDS = 5;
setInterval(function() {
updateMessage(currentContext)
}, INTERVAL_IN_SECONDS*1000);
function updateMessage(ctx) {
_e(DIV_ID).innerHTML = getMessage(ctx);
}
function getMessage(ctx) {
var msg = null;
$.ajax({
type: "post",
url: "contextmsg.php",
data: {
"ctx": ctx
},
success: function(data) {
msg = data.responseText;
},
dataType: "json"
});
return msg;
}
function _e(id) {
return document.getElementById(id);
}
Hope this helps :)
I'm working with AJAX on a website and I'm currently making some pages to load on a certain div: "pageContent". Now I have another content I want to be opened on another div: "reproductor". I want to open 'page' in 'pageContent' div and 'play' in 'reproductor' div. I don't know how to modify my script.js and load_page.php files in order to make it work. Here's what I got:
HTML:
<script type="text/javascript" src="js/script.js"></script>
PAGE
PLAY
<div id ="pageContent"></div>
<div id="reproductor"></div>
script.js:
var default_content="";
$(document).ready(function(){
checkURL();
$('ul li a').click(function (e){
checkURL(this.hash);
});
default_content = $('#pageContent').html();
setInterval("checkURL()",250);
});
var lasturl="";
function checkURL(hash)
{
if(!hash) hash=window.location.hash;
if(hash != lasturl)
{
lasturl=hash;
if(hash=="")
$('#pageContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url)
{
url=url.replace('#page','');
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+url,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg);
$('#loading').css('visibility','hidden');
}
}
});
}
load_page.php:
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.html'))
echo file_get_contents('pages/page_'.$page.'.html');
else
echo 'There is no such page!';
?>
I forgot to mention: I have my 'pages' content in a folder named 'pages' and my 'play' content in another named 'plays'.
Thanks for your help!
The easiest way to load content from a resource that serves HTML into an element is to use load:
$('#reproductor').load('public_html/plays/play_1.html', function(){
//stuff to do after load goes here
});
You could also apply this technique to the other div you are trying to load content into.
If I understand, your have two groups of links (for pages and a play list) each one to be loaded in a different container. Here is something you can try: mainly I eliminated the global variables and put the current hash inside each containter's data, and separated the management of the two groups of links.
In this code I supposed you have a separate load_play.php file. If not, then you can use the same page for both kind of links, but you'll have to merge loadPlay with loadPage, change loadPage(newHash) to loadPage(newHash, linkType) and change the ajax parameter from 'page='+newHash to 'number='+newHash+'&type='+linkType, and do the corresponding changes server side in your PHP page. I would recommend you to create two separate PHP files in order to manage the two types of content.
I remember you where doing something with the hash of the current page's url, you can still set it in the ajax's success, inside the loadPage function.
Here is a working sfiddle example with some console calls (open browser's console) but without the ajax call.
UPDATE:
I updated the code, so your can manage the dynamically added links (new content loaded via AJAX) and fixed the management of urls with hashes, which was broken because of the new code.
<div id="#page">
PAGE 1
PAGE 2
PLAY 1
PLAY 2
PLAY 3
<div id ="pageContent"></div>
<div id="reproductor"></div>
</div>
And this is the javascript:
$(document).ready(function(){
$('#pageContent').data('currentPage', '');
$('#reproductor').data('currentPlay', '');
//This will allow it to work even on dynamically created links
$('#page').on('click', '.pageLink', function (e){
loadPage(this.hash);
});
$('#page').on('click', '.playLink', function (e){
loadPlay(this.hash);
});
//And this is for managing the urls with hashes (for markers)
var urlLocation = location.hash;
if(urlLocation.indexOf("#page") > -1){
$('.pageLink[href='+ urlLocation +']').trigger('click')
}
});
function loadPage(newHash)
{
//This is the current Page
var curHash = $('#pageContent').data('currentPage');
//and this is the new one
newHash = newHash.replace('#page', '');
if(curHash===newHash){
//If already loaded: do nothing
return
}
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page='+newHash,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#pageContent').html(msg).data('currentPage',newHash);
$('#loading').css('visibility','hidden');
}
}
});
}
function loadPlay(newHash)
{//Similar to loadPage...
var curHash = $('#reproductor').data('currentPlay');
newHash = newHash.replace('#play', '');
if(curHash===newHash){return}
$('#loading').css('visibility','visible');
$.ajax({
type: "POST",
url: "load_play.php",
data: 'play='+newHash,
dataType: "html",
success: function(msg){
if(parseInt(msg)!=0)
{
$('#reproductor').html(msg).data('currentPlay',newHash);
$('#loading').css('visibility','hidden');
}
}
});
}
Check this and comment if this is what you need, or I got something wrong :)
There are a number of reasons why the following is not an ideal solution. The most glaring would be security - by modifying the href attribute of the link before clicking it, the user can certainly get your server to serve up any html on your server.
EDIT I've removed my original answer, because I can't recommend it's usage.
As Asad suggested, you can also use jQuery load and pass it the relevant url using some of the code above
function loadPage(url)
{
// remove the hash in url
url=url.replace('#','');
// extract page or play - only works for four letter words
var contentType=url.substr(0,4);
// extract the number
var contentId=url.substr(4);
if ( $contentType == "page") {
$("#pageContent #loading").css('visibility','visible');
$("#pageContent").load($contentType+'s/'+$contentType+'_'+$contentId+'.html');
$("#pageContent #loading").css('visibility','hidden');
} else if ( $contentType == "play") {
$("#reporductor #loading").css('visibility','visible');
$("#reproductor").load($contentType+'s/'+$contentType+'_'+$contentId+'.html');
$("#reporductor #loading").css('visibility','hidden');
}
}
I have problem with the site I'm developing. The dynamically loaded div (ajax) is empty in IE9 and works poorly on firefox (php doesn't compile) and I can read the source of my php file in the div.
I've tried a lot of solutions like changing from GET to POST or adding a unique id to the url or making an async request but the content is absolutely empty. Any ideas? thanks
function pageload(hash) {
if(hash == '' || hash == null)
{
document.location.hash = "#php"; // home page
}
if(hash)
{
getPage();
}
}
function getUniqueTime() {
var time = new Date().getTime();
while (time == new Date().getTime());
return new Date().getTime();
}
function getPage() {
var str = getUniqueTime();
console.log(str);
var data = 'page=' + encodeURIComponent(document.location.hash);
$('#content').fadeOut(200);
$.ajax({
url: "loader.php?_=" + str,
type: "POST",
data: data,
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
}
});
}
EDIT:
//loader.php
<?
require_once('session.class.php');
require_once('user.class.php');
$se = new session();
$lo = new user();
$se->regenerate();
if(isset($_POST))
{
$alpha = (string) $_POST['page'];
if($alpha == '#php')
{
include 'homeloader.php';
}
else if($alpha == '#cplus')
{
include 'cplusloader.php';
}
else if($alpha == '#web')
{
include 'underloader.php';
}
else if($alpha == '#about')
{
include 'underloader.php';
}
else if($alpha == '#social')
{
include 'socialloader.php';
}
}
else
$page = 'error';
echo $page;
?>
try this:
//on click of a button:
$("#button").live("click", function(){
//get you string data
var str = "test";
//do new version of ajax
$.post("loader.php", {str:str}, function(html){
$('#content').html(html);
});
});
and you dont need to do AJAX method anymore $.post works amazing
php doesn't compile? async request? actually not specifying ascync: true the request is executed asyncroniously and in version jQuery 1.8 there is no sync AJAX requests at all. Attach an error handler and you will see that your request probably results an error:
...
cache: false,
success: function (html) {
$('#content').fadeIn(200);
$('#content').html(html);
},
error: function (a,b) {
alert('Error!');
}
...
Normally AJAX consists of 2 parts - client side and server side. I don't see serverside posted in your question. You have to check both of them. Make a simple loader.php returning the string success and get rid of all extra get params. First test your php file in browser to be sure that it works. Check FireBug for javascript errors ...
Why doesn't the following pick up the form? All it does is just to do a normal PHP post without throwing any errors...
I'm using blockUi on this as well, hence block/unblock.
$(document).ready(function(){
$("input.update").click(function(){
var str = $(this).parent().serialize();
$(this).parent().parent().block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
$.ajax({
type: "POST",
url: "forms/update.php",
data: str,
success: function(){
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
}
});
return false;
});
});
This is my first attempt at using jQuery's Ajax functionality so please bear with me.
("input.update").click(function(){
should be
$("input.update").click(function(){
Since it seems you're only using the 'success' callback of post you could use the .post method, which is a bit easier on the eyes. Also you can put those block calls inside ajaxStart and ajaxStop. To me it's neater.
The $(this).parent().parent().block seemed wrong to me, I changed it to reference the same element that is used for unblocking. I'd also be checking the output of the PHP script, to make sure that whatever you are 'updating' actually is updated (just echo XML from PHP and you'll see it on your console log).
$(function() {
// Apply click handlers to anchors
$("input.update").click(function(e){
// Stop normal link click
e.preventDefault();
var str = $(this).parent().serialize();
// Send request
var action = "forms/update.php";
$.post(action, {data:str}, function(xml) {
console.log(xml);
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
})
});
// Adds a wait indicator to any Ajax requests
$(document.body).ajaxStart(function() {
$("div.edit_box").block({ message: "<span class=\"loading\"><img src=\"<?php echo $siteUrl ?>/admin/template/images/loading.gif\" alt=\"loading...\" /><p>Updating...</p></span>" });
}).ajaxStop(function() {
$("div.edit_box").unblock();
$("div.edit_box").append("<span class=\"success\">This has been updated!</span>");
});
});