After
$this->view->headScript()->appendFile($this->_request->getBaseUrl() . '/public/scripts/czassesji.js', 'text/javascript');
is called script
jQuery(document).ready(function() {
var licznik = 0;
var aktywny = true;
window.onblur = function(){aktywny = false;};
window.onfocus = function(){aktywny = true; licznik = 0;};
var id = setInterval(function(){wyslijImpuls()},60000);
function wyslijImpuls() {
if(aktywny == false) {
licznik++; //żeby nie tracić czasu spędzonego na stronie (np: 30 sekund), gdy uzytkownik przelączy okno/zakładkę przeglądarki
}
if(licznik < 2) {
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
}
}
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
console.log(baseUrl);
});
and I revieved error
ReferenceError: baseUrl is not defined $.post(baseUrl+'Zapiszczas/',
{'ile': 1});
My question is how to pass baseUrl value to js? I'd like to mentioned that baseUrl is defined in config.ini and accessible in php Zend controller.
You have to save that baseURL in some input hidden or in a global var in javascript, when php send the rended page , javascript can't access to php variables, one is executed in server side and the other is exectued in the client side.
<script>
baseURL = this->view->headScript()->appendFile($this->_request->getBaseUrl() . '/public/scripts/czassesji.js', 'text/javascript');
</scrip>
And then call in your next javascript script.
At the very Top of your ViewScript where you added $this->view->headScript()
//VIEW FILE
<?php
$this->view->headScript()->appendFile($this->_request->getBaseUrl() . '/public/scripts/czassesji.js', 'text/javascript');
//TRY ADDING THIS:
$this->inlineScript()->captureStart();
echo "var baseURL = '" . $baseUrl . "';";
$this->inlineScript()->captureEnd();
//.... MORE CODES...
?>
<?php
// IN YOUR CONTROLLER: SINCE YOU HAVE ACCESS TO THE $baseUrl VARIABLE HERE
// TRY THIS IN THE APPROPRIATE ACTION:
public function showAction(){
//...HANDLE YOUR BUSINESS LOGIC
$arrViewModel = array();
$arrViewModel['baseUrl'] = $pointerToBaseURL;
$viewModel = new ViewModel($arrViewModel);
//IF $viewModel ALREADY EXIST BEFORE THIS POINT:
// YOU MAY JUST ADD THE baseUrl KEY LIKE SO
// $viewModel->setVariable('baseUrl', '$pointerToBaseURL');
return $viewModel;
}
?>
// IN YOUR JQUERY... $baseUrl SHOULD NOW BE AVAILABLE
// SINCE IT IS NOW GLOBALLY SCOPED FROM YOUR VIEW:
jQuery(document).ready(function() {
var licznik = 0;
var aktywny = true;
window.onblur = function(){aktywny = false;};
window.onfocus = function(){aktywny = true; licznik = 0;};
var id = setInterval(function(){wyslijImpuls()},60000);
function wyslijImpuls() {
if(aktywny == false) {
licznik++; //żeby nie tracić czasu spędzonego na stronie (np: 30 sekund), gdy uzytkownik przelączy okno/zakładkę przeglądarki
}
if(licznik < 2) {
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
}
}
$.post(baseUrl+'Zapiszczas/', {'ile': 1});
console.log(baseUrl);
});
I hope this helps a bit...
Related
I see a lot of these questions comming by. But I seem to do something wrong. So forgive me for asking (I am a bit of a n00b). In my php I echo the the folowing echo json_encode(['msg'=>$NewTotal]);.
I use a HTML5 worker to post data to a php on my server and I need the echo to be posted back to the main script so I can repost it to set it as new value for the variable Totalaccounts for the loop.
Worker Script:
onmessage = function(dbs) {
console.log(dbs.data);
var Totalaccounts = dbs.data;
var DBScriptLoop = setInterval(
(function () {
DBStartWorking();
//postMessage(Totalaccounts);
}), 123000);
function DBStartWorking(){
for (var dw = 0; dw < Totalaccounts; dw++) {
setTimeout(function() {
httpRequest = new XMLHttpRequest()
var dataresponse = httpRequest.responseText;
var NewCount = dataresponse.msg;
httpRequest.open('POST', 'DostuffV1.php')
httpRequest.send(Totalaccounts)
postMessage(NewCount);
console.log(NewCount);
}, 1200 * dw);
}
} // End script loop
};
Main script:
var DBScriptWorker;
function startDBScriptWorker() {
if(typeof(Worker) !== "undefined") {
if(typeof(DBScriptWorker) == "undefined") {
DBScriptWorker = new Worker('DBScriptWorker.js');
var php_va = "<?php echo $AccToRank; ?>";
DBScriptWorker.postMessage(php_va);
}
DBScriptWorker.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data;
DBScriptWorker.postMessage(event.data);
};
} else {
document.getElementById("result").innerHTML = "Sorry, your browser does not support Web Workers...";
}
}
function stopDBScriptWorker() {
DBScriptWorker.terminate();
DBScriptWorker = undefined;
}
In my network tab I see the response is this: {"msg":29}
My variable is not set, it commes up as undifined. What am I doing wrong? Searching and trying for hours now..
anyone has any case like me ? i have to connect another service to my system. the problem is that service is unsupported on JS front-end (im using angularJS). to show form for service i need to complete jQuery form like this :
<script type="text/javascript">
$(function() {
var data = new Object();
data.req_merchant_code = '1';
data.req_chain_merchant = 'NA';
data.req_payment_channel = '15'; // ‘15’ = credit card
data.req_transaction_id = '<?php echo $invoice ?>';
data.req_currency = '<?php echo $currency ?>';
data.req_amount = '<?php echo $amount ?>';
data.req_words = '<?php echo $words ?>';
data.req_form_type = 'full';
getForm(data);
});
</script>
like you see that PHP variable on there with echo, can anyone help me to pass scope variable to that jQuery. i set that variable like this
$scope.dokuPayment = function(){
topUpFactory.createwordsDoku().then(function(data){
console.log(data.data);
var req = data.data;
$scope.invoice = req.invoice;
$scope.words = req.words;
$scope.currency = req.currency;
$scope.amount = req.amount;
console.log(invoice);
$("#doku-modal").modal('show');
});
}
i try to put that scope to parametes like this
<script type="text/javascript">
console.log("form doku");
$(function() {
var data = new Object();
data.req_merchant_code = '3279';
data.req_chain_merchant = 'NA';
data.req_payment_channel = '15'; // ‘15’ = credit card
data.req_transaction_id = {{invoice}};
data.req_currency = {{currency}};
data.req_amount = {{amount}};
data.req_words = {{words}};
data.req_form_type = 'full';
getForm(data);
});
</script>
but doesn't work.. i try to set upperstroup ("") still doesn't work. anyone can help. . thanks
When using AngularJS, try avoiding using jQuery in that way.
$("#doku-modal").modal('show'); - not a good idea to do that in this framework.
This article may give some guidance: http://www.dwmkerr.com/the-only-angularjs-modal-service-youll-ever-need/
In $scope.dokuPayment you can potentially do the same thing what getForm(data) does as long as it does not manipulate the DOM directly.
As a result, you do not have to pass any data to the view as the entire JS logic should be in your Angular services or controllers.
There is simple hack, not sure if it is good practice or not! You can make use of $window scope.
All you need to do is, make angular variables to global variables using $window.{variable name} and access them from outside using window.{variable name}.
See here:
$scope.dokuPayment = function(){
topUpFactory.createwordsDoku().then(function(data){
console.log(data.data);
var req = data.data;
$window.invoice = req.invoice;
$window.words = req.words;
$window.currency = req.currency;
$window.amount = req.amount;
console.log(invoice);
$("#doku-modal").modal('show');
});
}
Outside AngularJS:
console.log("form doku");
$(function() {
var data = new Object();
data.req_merchant_code = '3279';
data.req_chain_merchant = 'NA';
data.req_payment_channel = '15'; // ‘15’ = credit card
data.req_transaction_id = window.invoice;
data.req_currency = window.currency;
data.req_amount = window.amount;
data.req_words = window.words;
data.req_form_type = 'full';
getForm(data);
});
This worked for me. Hope this helps :)
Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});
I am getting list of images from a folder for particular ID. Right now I am getting file names but I also want to get upload path.
How to get both data in one function.
Jquery Code:
listFilesOnServer(project_id);
function listFilesOnServer (project_id) {
var items = [];
uploadURI = uploadURI+'/'+project_id;
console.log(project_id+'--KAL--'+uploadURI);
$.getJSON(uploadURI ,function(data,path) {
console.log(data);
$('div #list-group').html("").html(items.join(""));
});
}
Controller Code:
function listFiles() {
$this->load->helper('file');
$project_id = $this->uri->segment(3);
$builders_id = $this->admin_model->getBuilderID($project_id);
$UPLD_PATH = $this->admin_model->builder_UPLD_PATH($builders_id);
$upload_path = "./application/assets/images/" . $UPLD_PATH;
$files = get_filenames($upload_path);
echo json_encode($files);
}
You should modify your controller action so that it returns an json_encode(array('files'=>$yourFiles, 'filePath'=>$yourFilePath) ); like below :
function listFiles() {
$this->load->helper('file');
$project_id = $this->uri->segment(3);
$builders_id = $this->admin_model->getBuilderID($project_id);
$UPLD_PATH = $this->admin_model->builder_UPLD_PATH($builders_id);
$upload_path = "./application/assets/images/" . $UPLD_PATH;
$files = get_filenames($upload_path);
echo json_encode(array('files'=>$files, 'uploadPath'=>$upload_path) );
exit();
}
Then modify your jquery code to handle the json response and extract the response like below :
listFilesOnServer(project_id);
function listFilesOnServer (project_id) {
var items = [];
uploadURI = uploadURI+'/'+project_id;
console.log(project_id+'--KAL--'+uploadURI);
$.getJSON(uploadURI ,function(data,path) {
//Your upload path
console.info("UPLOAD PATH: "+data.uploadPath);
//Your files
console.log(data.files);
//Your processing logic goes here
$('div #list-group').html("").html(items.join(""));
});
}
Working within system constraints, I needed a way to put working code from a local .php or .html into a target div without additional libraries, jfiddle, iframes, etc. (jquery was fine)
Here are my failed attempts.
First part of file
This is some page!
<script>$("#fruit").click(function(){Expand01("fruit.php"); return false;});</script>
A pretty good page...
<script>$("#orange").click(function(){Expand01("orange.php"); return false;});</script>
I like this page
<script>$("#tomato").click(function(){Expand01("tomato.php"); return false;});</script>
Later in file (after Expand01 function declared)
<div id="thisdiv"></div>
Attempt 1
<script> function Expand01(targetUrl){
document.getElementById('thisdiv').style.display = "block";
document.getElementById('thisdiv').innerHTML = targetUrl;
document.getElementById('thisdiv').append = '<div id="thatdiv"></div>';
} </script>
Attempt 2
<script> function Expand01(targetUrl){
var myTargetUrl = new XMLHttpRequest();
document.getElementById('thisdiv').style.display = "block";
myTargetUrl.open("GET", targetUrl, true);
myTargetUrl.setRequestHeader("Content-Type","text/plain");
myTargetUrl.send("");
document.getElementById('thisdiv').innerHTML = myTargetUrl.responseText;
document.getElementById('thisdiv').append = '<div id="thatdiv"></div>';
} </script>
Attempt 3
<script> function Expand01(targetUrl){
document.getElementById('thisdiv').innerHTML = $.get(targetURL);
} </script>
Attempt 4
<script> function Expand01(targetUrl){
var myFile = getHTTPObject();
myFile.onreadystatechange = function() {
if(request.readyState == 4) {
if(myFile.status == 200 || request.status == 304) {
var targetDiv = document.getElementById('thisdiv');
targetDiv.innerHTML = myFile.responseText;
} else {
alert("Failure");
}
}
}
myFile.open("GET", targetUrl, true);
myFile.send(null);
} </script>
This is the method I use when doing this for ajax applications. It also allows for the usage of $_SESSION[] variables as well as any Javascript or jQuery located in the php file you are pulling into your container.
jQuery:
$.post('pageloader.php', {url: 'path/to/file.php'}, function(data){
var o = $.parseJSON(data);
if(o.status == 1){
$('#yourContainer').html(o.markup);
} else {
alert(o.message);
}
});
PHP: (pageloader.php)
$url = $_POST['url'];
$response = array();
ob_start();
include("markup/" . $url); // Replace or remove '"markup/" . ' depending on file locations
$response['markup'] = ob_get_clean();
if($response['markup']){
$response['status'] = 1;
} else {
$response['status'] = 0;
$response['message'] = 'There was an issue loading the page.';
}
echo json_encode($response);
Hope this helps!