How to pass a PHP var to an external js file - javascript

I know there are numerous resource that covers this topic but I couldn't find one that matched my problem completely. I am trying to pass $filemanagerToken to post_editor.js. Here is what I have;
In index.php i have the following script:
$filemanagerToken = '123456';
$this->data['scripts_admin'] = '
<!-- Scripts Admin -->
<script src="//cdn.ckeditor.com/4.16.0/full/ckeditor.js"></script>
<script src="'.base_url().'/assets/admin/post/js/post_editor.js">
var fmKey = '.json_encode($filemanagerToken).';
</script>';
And in post_editor.js, I have the following;
CKEDITOR.replace( 'post_body' ,{
filebrowserBrowseUrl : '../../filemanager/dialog.php?type=2&editor=ckeditor&fldr=',
filebrowserImageBrowseUrl : '../../filemanager/dialog.php?type=1&editor=ckeditor&fldr=&akey=fmKey' ,
});
I just cannot understand how to echo out fmKey above. Any guidance appreciated. I tried but get a parse error.

Related

results from php library not working with AJAX

I'm calling the uberGallery (www.uberGallery.net) from the index.php like so:
<?php
include_once 'resources/UberGallery.php';
include_once 'resources/uberCall.php';
?>
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
...
<link rel="stylesheet" type="text/css" href="resources/themes/uber-naked/style.css" />
<link rel="stylesheet" type="text/css" href="resources/colorbox/5/colorbox.css" />
<script src="//code.jquery.com/jquery.js"></script>
<script type="text/javascript" src="resources/colorbox/jquery.colorbox.js"></script>
</head>
<body>
<div class = "row">
<div class = "col col-lg-12">
<h2 id = "locName"></h2>
</div>
</div>
<div id="gallery">
<?php
$path = "london";
getGallery($path);
$path = "paris";
getGallery($path);
$path = "rome";
getGallery($path);
?>
</div>
<script type="text/javascript" src='js/UX.js'></script>
</body>
</html>
The uberCall.php is like that:
<?php
include_once ('UberGallery.php');
function getGallery($pathToImage){
UberGallery::init() -> createGallery('locations/'.$pathToImage.'/gallery');
}
if(isset( $_POST['image-path'] )) {
$path = $_POST['image-path'];
UberGallery::init() -> createGallery('locations/'.$path.'/gallery');
}
?>
So far this is working like expected.
Now I would like to load the galleries from a dropdown menue and just show the selected gallery. The dropdown selection is done in a jQuery script:
$(document).ready(function() {
$("a[rel='colorbox']").colorbox({
maxWidth : "90%",
maxHeight : "90%",
opacity : ".5"
});
$(".dropdown-toggle").dropdown();
$('#demolist li a').click(function(e) {
$('#locationSelector').val($(this).text());
var $this = $(this);
var selLocID = $this.attr("value");
e.preventDefault();
var dataString = {
'location_id' : selLocID
};
$.ajax({
type : 'POST',
dataType : 'json',
url : 'includes/locationAPI.php',
data : dataString,
success : function(data) {
$('#locData').html('');
// erase content if any
$('#locName').html(data['name']);
// from MySQL
// set location headline
$.ajax({
type : "POST",
data : {
'image-path' : data['pfad'] // from MySQL
},
url : 'resources/uberCall.php',
dataType : "html",
async : false,
success : function(data) {
result = data;
alert(result);
$('#gallery').html(result);
}
});
}
});
});
});
When going this route the ubergallery doesn't find any folders, though I'm adressing the exact same uber.php as I would from the index.php.
I have looked into the ubergallery.php with xdebug and it would be called with exactly the same parameters.
Also I tried to call createGallery() without init:: and also explicitly create a new instance of the UberGallery class before calling createGallery.
All with no luck.
What am I doing wrong here?
In your resources/userCall.php script you are not actually calling the gallery function in order to render it. This appears to be the target of the second AJAX request. The script is merely defining the function.
EDIT: You've since updated the code in your question to include the call.
Assuming image-path is the parameter you want to supply as $pathToImage you will need to have a script that calls the function getGallery passing the value from $_POST['image-path'].
For example:
<?php
require_once('resources/uberCall.php');
getGallery($_POST['image-path']);
NOTE: Without any filtering sanitisation, bear in mind this could be potentially dangerous as I could pass an image-path parameter that picks a naughty directory.
Then use that script as the target of your second AJAX call.
P.S. Remove the async: false in the second AJAX call, it stops any other interactivity on your page whilst the request is in flight.
Bear in mind that with your parameter checking in the resources/userCall.php the original request is down a directory from the second request. This means the working directory for the second request will be different, the path will resolve to "resources/locations/$path/gallery" and not "locations/$path/gallery".
You are best off creating a second script for the AJAX action in the same directory as the original and requiring in the resource/userCall.php as per the first script. Or using a configurable absolute directory path to resolve the gallery location:
<?php
require_once('UberGallery.php');
require_once('config.php');
function getGallery($path) {
UberGallery::init() -> createGallery("{$config['gallery_base_path']}/$path/gallery");
}
With $config['gallery_base_path'] being something like /absolute/path/to/my/application/locations.
Additional confusion can be caused by not knowing whether file operations will use the include path, some file options can be told to use the include path which may include the current file path and current script directory, but if not it will only try to find the file from the current working directory. Whereas include and require all use the include path and current script directory as potential points to find a script.
P.S.P.S Use getcwd to find out what the current working directory is at any point in your scripts.

Backbone: passing data to server (save() method, php file)

Hope you can help me with that problem.
I want to use Backbone's save() method and pass to php file data.
But on a very begining I have problem.
In browser's console I execute:
var test = new MyModel(); // - it's ok
test.toJSON(); // - it's ok
test.save(); // and here I have error "TypeError: d.collection is undefined"
When I use localStorage everythink is OK (it's commented in my code below). I can create models, collections, views etc. and operate on them.
I tried to use these tutorials net.tutsplus.com/tutorials/javascript-ajax/understanding-backbone-js-and-the-server/ and http://coenraets.org/blog/2011/12/restful-services-with-jquery-php-and-the-slim-framework/ but I can't get how REST works and where I made mistake. Hope you can explain.
index.html
<!DOCTYPE html>
<html>
<head>
<title>S.O.S</title>
</head>
<body>
<h1>Test</h1>
<script src="jquery.min.js"></script>
<script src="underscore-min.js"></script>
<script src="backbone-min.js"></script>
<script src="backbone.localStorage-min.js" type="text/javascript"></script>
<script >
window.MyModel = Backbone.Model.extend({
defaults: {
title: 'Test'
},
//localStorage: new Store('TEST')
urlRoot: 'api/items'
});
</script>
</body>
</html>
index.php
<?php
require 'Slim/Slim.php';
$app = new Slim();
$app->post('/items', 'addItem');
$app->run();
function addItem() {
$request = Slim::getInstance()->request();
try {
echo json_encode('OK message');
} catch(PDOException $e) {
echo 'Error message';
}
}
?>
folders structure
|->main_folder
|-index.html
|->api
|->index.html
|->Slim
|-> (folder with Slim php library)
Here is a working example http://jsfiddle.net/acDb3/
Even without working REST I didn't got the error you have.
I noticed there is no Content-type for JSON output. You may add this line to the index.php to make it work.
$app->contentType("application/json");
You can also get success and error callacks to see if they are have been called.
test.save(null, {
success: function() {
alert("success");
},
error: function() {
alert("error");
}
});

Next and previous button using jquery

I am using a PHP Simple HTML DOM Parser to save a website as a htm file. I then use jQuery to extract a div from the file and put it into a div. I want to create a
Previous and Next button but the problem I have is that to do this I have to change the URL so the parser can get the page. I would really appreciate if you can help. Below is the code I am using.
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=1');
$html->save('site/rtnews.htm')
?>
<script type="text/javascript" src="site/jquery.js"></script>
<script type="text/javascript">
$('document').ready(function() {
$('#wrap').click(function (event){
event.preventDefault();
});
$("#wrap").load('site/rtnews.htm #postsArea');
});
</script>
</head>
<body>
<div id="wrap">
</div>
</body>
You will have to create a new php file for this and make an AJAX request to that file. I assume you have already realised that you cannot make a cross-domain request due to CORS.
Here is your new php file, let's call it proxy.php. It will proxy the request, responding with the page that is passed to it via GET :
<?php
include( 'site/simple_html_dom.php');
$html=file_get_html( 'http://roosterteeth.com/home.php?page=' . $_GET["page"]);
echo $html;
?>
Your new JavaScript;
$('document').ready(function() {
var $wrap = $('#wrap'),
page = 1;
$('#next').on('click', function () {
getPage(++page);
});
$('#prev').on('click', function () {
getPage(--page);
});
var getPage = function (page) {
$wrap.load('proxy.php?page=' + page + ' #postsArea');
};
getPage(page);
});

NowJS error! I can't get the example to work!

I was following along the tutorial at http://nowjs.com/doc when I encountered some errors.
<html>
<head>
<title>index.html</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"/>
<script src="http://localhost:8080/NowJS/now.js"></script>
<script>
$(document).ready(function(){
var name = prompt("what is your name?","");
now.receiveMessage = function(name,message){
alert(name+" "+message);
};
$('.butt').click(function(){
alert($('#put').val());
now.distributeMessage(name,$('#put').val());
$('#put').val('');
});
});
</script>
and for the server:
var fs = require('fs');
var sys = require('sys');
var server = require('http').createServer(function(req,response){
fs.readFile('index.html',function(err,data){
response.writeHead(200);
response.write(data);
response.end();
});
});
server.listen(8080);
sys.print('woot');
var everyone = require('now').initialize(server);
everyone.now.distributeMessage = function(name, message){
sys.print(name+" "+message);
everyone.now.receiveMessage(name,message);
};
I highly suspect it has something to do with my tag since there isnt anything at /NowJS/now.js.
Can someone enlighten me on this part:
On pages that you would like to use NowJS on, simply include this script tag in your HTML head: NowJS only works on pages that are served through the same http server instance that was passed into the initialize function above.
Thanks for your time.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"/>
script tags can't be self-closed.
In the docs the path in the script tag is lower-case, /nowjs/now.js, whereas in your snippet it is /NowJS/now.js, and so I guess this is the reason it doesn't work.

How do you automatically refresh part of a page automatically using AJAX?

$messages = $db->query("SELECT * FROM chatmessages ORDER BY datetime DESC, displayorderid DESC LIMIT 0,10");
while($message = $db->fetch_array($messages)) {
$oldmessages[] = $message['message'];
}
$oldmessages = array_reverse($oldmessages);
?>
<div id="chat">
<?php
for ($count = 0; $count < 9; $count++) {
echo $oldmessages[$count];
}
?>
<script language="javascript" type="text/javascript">
<!--
setInterval( "document.getElementById('chat').innerHTML='<NEW CONTENT OF #CHAT>'", 1000 );
-->
</script>
</div>
I'm trying to create a PHP chatroom script but I'm having a lot of trouble getting it to AutoRefresh
The content should automatically update to , how do you make it do that? I've been searching for almost an hour
I would take that PHP functionality you have and putting it in a sperate page that returns JSON. From there you can call that method using jQuery and the AJAX tools built in. Really simple. Start here for jQuery: http://api.jquery.com/category/ajax/
you'll need to set up a server side script that renders only the contents of the chat div and use ajax to grab that. it can be done with jquery quite easily:
In your html document:
<head>
...
<script src="/path/to/jquery.js" type="text/javascript"></script>
<script>
var chatUpdateInterval = null;
function initChat() {
chatUpdateInterval = window.setInterval(updateChat, 5000); /* every 5 seconds */
}
function updateChat() {
$.ajax({
url: '/url/path/to/your/script.php'
,dataType: 'HTML'
,success: function(data, status, xhr){
$('#chat').append($(data).html());
}
});
}
$(document).ready(function(){
initChat();
});
</script>
...
</head>
<body>
<div id="chat">
please stand by while we're firing up the coal!
</div>
</body>
Note that this won't be really good, it's just a sample to get you started. you should look into jquery's $.ajax

Categories

Resources