results from php library not working with AJAX - javascript

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.

Related

How to pass a PHP var to an external js file

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.

Open PHP Dynamic Page response in Cordova Inappbrowser

I want to open the response that I get from my PHP server in the In App Browser in a new window.
I am creating an app using Ionic and using PHP as a back end. I have full control of the php server.
I am making the ajax call like so:
$(document).ready( function() {
$("#paybutton").click(function() {
var params = "projectpaymentoption=1197&id=",
usernamepay = window.localStorage.getItem("username"),
paymenturl = params + usernamepay;
$.ajax({
type: 'POST',
url: 'http://www.blabla.com/encode.php',
data: $.param({"paymenturl": paymenturl}),
success: function(output) {
window.open('output','_blank','location=no','closebuttoncaption=Zurück');
console.log(result);
}
});
});
});
Now I want to open the output in a new inappbrowser windows.
The output i am throwing out is as follows
<?php
ob_start();
include_once('includes/headers.php');
require_once('includes/connection.php');
require_once('includes/functions.php');
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
</head>
<?php
include($filePath);
?>
It is a dynamically generated php page. An not an url.
How can I show this page in the inappbrowser

got error when using javascript ajax json to retrieve php array

My html page is suppose to retrieve the array from the php page and alert the first element in the array. But when I run the html, got the following error, "Uncaught TypeError: Object function (E,F){return new o.fn.init(E,F)} has no method 'parseJSON' " in the console window. I tried to use jQuery.parseJSON(json_data) instead of $.parseJSON(json_data) but still got the same error. How can I fix this?
script.js:
function getArr(){
alert('return sent');
$.ajax({
url: "n1.php",
type: "GET",
success: function(json_data){
var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];
alert(rec);
alert("GOOD");
},
error: function() {
alert("BAD");
} });
}
newcal.html:
<!DOCTYPE html>
<html >
<head>
<meta charset="utf-8">
<link rel="stylesheet" media="screen" href="demo.css">
<body onload="getArr();">
<div id="rounded"><div id="main" class="container">
<div id="pageContent">
Hello, this is the default content
</div>
</div>
</div>
</body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="script.js"></script>
</head>
</html>
n1.php:
<?php
$output = array("cat","dog");
echo json_encode($output);
?>
parseJSON was added in jQuery 1.4.1 (in 2010)
You are using jQuery 1.3.2 (from 2009), which is too old.
The current version of jQuery 1.x is 1.11 (released this year).
Use a more recent version of jQuery.
You should also tell the browser that you are sending it JSON instead of claiming that your JSON is HTML. (PHP defaults to claiming that anything it outputs through a web server is HTML)
<?php
header("Content-type: application/json");
$output = array("cat","dog");
echo json_encode($output);
?>
Then let jQuery parse it automatically:
success: function(data_array){
// Remove the following line. It will be parsed automatically.
// var data_array =jQuery.parseJSON(json_data);
var rec = data_array[0];

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");
}
});

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