Briefly, i work on to create a Wordpress plugin. In this plugin, i need a progress bar that moving on according to background process. So, I determined a specific php file which contains my custom functions. Let's call this 'func.php' . Also, there is a file that acts as plugins main page file. We can call it 'main.php' .
So; I designed a concept in my head. On the main page, when I click begin button (named 'buttonbegin'), a jquery post being sent to func.php . I can control this POST value with these codes in func.php:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'buttonbegin':
func1();
break;
case 'otherbutton':
func2();
break;
}
}
After it, func1 executes. In this function, i had these codes for testing:
function func1() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var itemnumber=0;
for (var i = 1; i <= 3000; i++) { //it should be execute 3000 times because of nature of process
itemnumber++;
if (itemnumber == 30) {
var value = "mystring";
var ajaxurl = 'fullurl+pluginsdirectory/main.php', //func.php and main.php are in same folder
data = {'action': value};
$.post(ajaxurl, data, function (response) {
});
itemnumber=0;
}
}
});
</script>
<?php
}
At this point in this func1, I wanna do another jquery post to make a trigger mechanism for progress bar on main.php . And finally, there is some javascript code to control this last jquery post and expand 1% progress bar. Here is the script codes in main.php :
<script type="text/javascript"> //below are for the first process i told
var width = 0;
var addition = 1;
jQuery(document).ready(function($) {
$('#buttonbegin').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'fullurl/func.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
});
});
//actual part starts here
var continuous = setInterval(function() {
var code = <?php echo !isset($_POST['action']) ?>; // the source of the problem
if(!code) {
var percent = $("#myBar").width() / $("#myBar").parent().width() * 100;
if (percent == 100) {
clearInterval(continuous);
}
var element = document.getElementById("myBar");
element.style.width = (width+addition) + "%";
element.innerHTML = (width+addition) * 1 + "%";
width = width + addition;
}
}, 1000);
});
</script>
But it doesn't work. When i print the 'code' variable with console.log, I see NaN value. The php code inside script tags doesn't work properly. Is there any mistake? Or is there another simpler way to do whole process?
Note: Necessary jquery cdn links are included in main.php and func.php both. This is how its look like:
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>
Related
As I asked here I would like to know how I could pass the data from a simple JS function to php, and log it there.
I found this answer and tried to follow it. This is my code right now (both in the same file)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getClientScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH)
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
<script type="text/javascript">
getScreenResolution();
</script>
</body>
</html>
<?php
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
if(isset($_POST['screenResolutionW'])) {
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH
."\r\n");
fclose($fh);
}
?>
However, this does not work.
I wouldn't know how to fix this, whenever I try to google this problem people use more advanced methods, that I wouldn't even know how to start with.
Edit: My PHP and HMTL are in the same file (index.php).
Edit 2: Removed old code for clarity.
This results in these error messages:
Notice: Undefined index: screenResolutionW in index.php on line 153
Notice: Undefined index: screenResolutionH in index.php on line 154
What you want to do with $.post is include your data like this:
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
where the first of the pair is the POST identifier (the ['screenResolutionW']) and the second of the pair is the variable value.
You will also want to change your POST identifiers to be quoted:
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
Otherwise, you will get a warning about constants. I have also corrected the spelling in these variables, to reflect what you're trying to write into your file.
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH ."\r\n");
EDIT
Part of the problem is that you never call the function to execute it. Here is your HTML with the additions I have suggested, plus calling the function:
EDIT TWO
Added an onload handler for the document:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
</body>
<script type="text/javascript">
$(function() {
getScreenResolution();
});
</script>
</html>
OTHER NOTES
You really should separate the PHP code and place it in a different file because when you run the page as it is now you should get one line logged that has no variables when the page initially runs, then one logged line when the JavaScript fires after the page loads.
Then once separated you should not run your PHP until you test for the existence of a variable, for example:
if(isset($_POST['screenResolutionW'])) {
// your code to write to the file here
}
EDIT THREE
I placed all of the JavaScript in the same script block in the head of the file and have tested again:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function() {
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("post_test.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
getScreenResolution();
});
</script>
</head>
<body>
</body>
</html>
Here you can see the variables are being posted:
Adapting the others answers.
try it:
function getScreenResolution() {
"http://example.com/index.php", screenResolutionW + screenResolutionH
$.ajax({
url: '/index.php',
method: 'POST',
data: {
screenResolutionW : screen.width,
screenResolutionH : screen.height
},
success: function(data) { console.log(data); }
});
}
And in your PHP
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
echo $screenResolutionW . " - " . $screenResolutionH;
you have to use serialize the array before doing post request.
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
var serializedArr = {
width: screenResolutionW,
height: screenResolutionH
};
$.post('/index.php', serializedArr, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
In the server end, you will get values in $_POST variable.
Apart of all those mistakes you have discovered thanks to other replies, you have these:
$screenResoltuionW = ...
Notice you wrote "ltuion" and in the fopen command you have it correct. screenResolutionW
Same thing with $screenResoltuionH...
That's why you don't get any value in the file, because those variables doesn't exists.
Hello i started javascript and im making a dynamic ajax GET page, (refreshes page when json data changed etc.).
My problem is i need to refresh page or container div when data is changed
this my code
HTML:
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Refresh" content="600">
<link rel="stylesheet" type="text/css" href="main.css">
</head>
<body>
<div id="container">
<div id="event"></div>
<div id="counter">
<span id="countdown"></span>
</div>
</div>
<script type="text/javascript" src="jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="custom.js"></script>
</body>
</html>
JS:
var request = $.ajax({
url: "data.php",
type: "GET",
dataType: "json"
}).done(function (data) {
var write = '<img src="' + data.img + '">';
$("#event").html(write);
$("#event").delay(data.countdown * 1000).fadeOut();
var i = data.countdown;
var fade_out = function () {
$("#counter").fadeOut().empty();
clearInterval(counter);
};
setTimeout(fade_out, data.countdown * 1000);
function count() { $("#countdown").html(i--); }
var counter = setInterval(function () { count(); }, 1000);
});
JSon is like this
{"img":"img\/maltolmeca.jpg","countdown":"60"}
In this day and age, it might be worth you looking into libraries such as Angular, React and Vuejs which handle 'data refreshing' for you.
Anyway, in your done() function you can just call location.reload() which would refresh the page.
...though I imagine that isn't what you are actually trying to achieve. Refreshing the page like that is a bad user experience usually, so let's try a better solution.
One way of 'reloading' a div is to do something like this:
if (data.success){
$("#event").fadeOut(800, function(){
$("#event").html(msg).fadeIn().delay(2000);
});
}
or even
$("#event").load("#event");
I just put this code in to my php folder, its like from stone age but its ok for my project.
<script>
var previous = null;
var current = null;
setInterval(function() {
$.getJSON("data.php", function(json) {
current = JSON.stringify(json);
if (previous && current && previous !== current) {
console.log('refresh');
location.reload();
}
previous = current;
});
}, 2000);
I am very new to javascript (jquery/json) I have written this code to render a chart of CanvasJS with a php/json data fetching script along with it.
However the chart won't show, when I implement my code in to it. When I used Console.log() in web browser to find the ReferenceError it says: Can't find variable: $ ...Chart.html:11
I have tried many things and I have read many [duplicate] question/answers saying that I didn't load the Jquery Library and a bunch of other options. I have tried implementing this line:
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
And I have tried many variables, but I don't think I understand what I can use more in these two codes I have..
Any point into the right direction would be great.
Chart.html
<!DOCTYPE HTML>
<html>
<script type="text/javascript" src="canvasjs.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<head>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
In the above code, it concerns this part:
$(document).ready(function () {
and my php for the JSON data fetching: data.php
<?php
//header('Content-Type: application/json');
$con = mysqli_connect("localhost","root","","WebApplication");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to DataBase: " . mysqli_connect_error();
}
else
{
$data_points = array();
$result = mysqli_query($con, "SELECT * FROM info");
while($row = mysqli_fetch_array($result))
{
$point = array("x" => $row['id'] , "y" => $row['acceleration']);
array_push($data_points, $point);
}
$json = json_encode($data_points, 32); //define('JSON_NUMERIC_CHECK',32); // Since PHP 5.3.3
$json = str_replace("\"", "", $json); //replace all the "" with nothing
echo $json;
}
mysqli_close($con);
?>
I know that the stack overflow community always require more info, but for god sake, I don't know anymore, and I really want to learn this.
EDIT-1:
This is what I have know, yet no result.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"> </script>
<script type="text/javascript" src="canvasjs.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.getJSON("data.php", function (result) {
var dataPoints = [];
for (var i = 0; i <= result.length - 1; i++) {
dataPoints.push({ x: Number(result[i].x), y: Number(result[i].y) });
}
var chart = new CanvasJS.Chart("chartContainer", {
data: [
{
dataPoints: dataPoints
}
]
});
chart.render();
});
});
</script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:100%;">
</div>
</body>
</html>
EDIT-2:DEFAULT CODE, WHICH WORKS:
This is the default code that doesn't use my data.php code and uses randomized data points as data-source. It's from Canvasjs and it works fine.
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
window.onload = function () {
var dps = []; // dataPoints
var chart = new CanvasJS.Chart("chartContainer",{
title :{
text: "Patient #01"
},
data: [{
type: "line",
dataPoints: dps
}]
});
var xVal = 0;
var yVal = 100;
var updateInterval = 20;
var dataLength = 500; // number of dataPoints visible at any point
var updateChart = function (count) {
count = count || 1;
// count is number of times loop runs to generate random dataPoints.
for (var j = 0; j < count; j++) {
yVal = yVal + Math.round(5 + Math.random() *(-5-5));
dps.push({
x: xVal,
y: yVal
});
xVal++;
};
if (dps.length > dataLength)
{
dps.shift();
}
chart.render();
};
// generates first set of dataPoints
updateChart(dataLength);
// update chart after specified time.
setInterval(function(){updateChart()}, updateInterval);
}
</script>
<script type="text/javascript" src="canvasjs.min.js"></script>
</head>
<body>
<div id="chartContainer" style="height: 300px; width:600px;">
</div>
</body>
</html>
It looks like jQuery is being loaded after canvasJS. If Canvasjs needs to use jQuery, it will need to have jQuery loaded first. Try switching those lines so jQuery is loaded on top, and it will probably fix your error.
EDIT: Actually, it seems that the CDN that hosts your jQuery doesn't use $ as the name of your main jQuery object. If you change $ to "jQuery" that error should be resolved. For example:
$(document).ready
would become:
jQuery(document).ready
same with $.getJson
It looks like Jquery isn't being loaded properly, and I'm thinking it's because of your unconventional practice of including the external scripts directly after the element. Try moving them down to just before your own script, inside the head.
Edit: the post was updated and apparently this didn't help.
SOLVED IT
First include this line:
than include this line: BELOW the code, not above it.
Than go to my data.php and comment (or delete) this line: //$json = str_replace("\"", "", $json); //replace all the "" with nothing
why u ask? Well because CanvasJS requires Strings and not separate characters/integrers.
So that the output will be:
[{"x":"1","y":"5"},{"x":"2","y":"5"},{"x":"3","y":"4"},{"x":"4","y":"1"},{"x":"5","y":"8"},{"x":"6","y":"9"},{"x":"7","y":"5"},{"x":"8","y":"6"},{"x":"9","y":"4"},{"x":"10","y":"7"},{"x":"14","y":"7"},{"x":"15","y":"7"}]
Instead of:
[{x:1,y:5},{x:2,y:5},{x:3,y:4},{x:4,y:1},{x:5,y:8},{x:6,y:9}...etc.
so I developed this sharepoint hosted app with an app part which renders a calendar, when they click on a day it must open a modal popup with an url that I already have.
I will paste the error at the end.
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="/_layouts/15/MicrosoftAjax.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.runtime.js"></script>
<script type="text/javascript" src="/_layouts/15/sp.js"></script>
<!-- Core CSS File. The CSS code needed to make eventCalendar works -->
<link rel="stylesheet" href="../Content/eventCalendar.css">
<!-- Theme CSS file: it makes eventCalendar nicer -->
<link rel="stylesheet" href="../Content/eventCalendar_theme_responsive.css">
Here is the JS
var SPHostUrl;
var SPAppWebUrl;
var ListaEventos;
var Categoria;
var ready = false;
var $events = [];
// this function is executed when the page has finished loading. It performs two tasks:
// 1. It extracts the parameters from the url
// 2. It loads the request executor script from the host web
$(document).ready(function () {
var params = document.URL.split("?")[1].split("&");
for (var i = 0; i < params.length; i = i + 1) {
var param = params[i].split("=");
switch (param[0]) {
case "SPAppWebUrl":
SPAppWebUrl = decodeURIComponent(param[1]);
break;
case "SPHostUrl":
SPHostUrl = decodeURIComponent(param[1]);
break;
case "TituloListaEventos":
TituloListaEventos = decodeURIComponent(param[1]);
break;
case "Categoria":
Categoria = decodeURIComponent(param[1]);
break;
case "NombreListaEventos":
NombreListaEventos = decodeURIComponent(param[1]);
break;
}
}
// load the executor script, once completed set the ready variable to true so that
// we can easily identify if the script has been loaded
$.getScript(SPHostUrl + "/_Layouts/15/SP.RequestExecutor.js", function (data) {
ready = true;
getItems();
ShowServerInformation();
});
var sub = SPHostUrl.substring(0, SPHostUrl.lastIndexOf('/'))
$('head').append('<link rel="stylesheet" href="' + sub + '/Style%20Library/SPCCapatech/SPCCapatech.css">');
$('head').append('<link rel="stylesheet" href="' + sub + '/Style%20Library/SPCCapatech/colors.css">');
});
function ShowServerInformation() {
var options = {
url: "/_layouts/Viewlsts.aspx&IsDlg=1",
tite: 'Server Information',
allowMaximize: false,
showClose: true,
width: 430,
height: 230
};
parent.SP.SOD.execute('sp.ui.dialog.js', 'SP.UI.ModalDialog.showModalDialog', options);
return false;
}
whenthe showserverinformation function is executed I get this error:
Permission denied to access property "SP"
This is a standard security restriction. Otherwise any IFRAME JavaScript could execute anything it wants in the parent window.
In order to manipulate the parent window you have to use HTML 5 Messaging API:
Execute window.postMessage() from your IFRAME to send "an order" to the parent window.
Process this message in the parent window and create the modal window as the reaction to this message.
Before, I had this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
var optPrompt = "- Select One -";
var subCats;
var parentCats;
var nextBtn;
var ParentChanged = function() {
ClearDescription();
if (this.selectedIndex == 0) {
$(subCats).html($("<option>").text(optPrompt));
}
$.getJSON('<%=Url.Action("GetChildCategories") %>', { parentId: $(this).val() },
function(data) {
subCats.options.length = 0;
$("<option>").text(optPrompt).appendTo(subCats);
$(data).each(function() {
$("<option>").attr("value", this.ID).text(this.Name).appendTo(subCats);
});
});
}
var DisplayDescription = function(catId) {
$.ajax({
url: '<%=Url.Action("GetDescription") %>',
data: { categoryId: catId },
dataType: 'html',
success: function(data) {
$("p#categoryDescription").html(data);
}
});
}
var ChildChanged = function() {
var catSelected = this.selectedIndex != 0;
if (!catSelected) ClearDescription();
else DisplayDescription($(this).val());
}
var ClearDescription = function() {
$("p#categoryDescription").html('');
}
$(function() {
parentCats = $("select#Category").get(0);
subCats = $("select#Subcategory").get(0);
nextBtn = $("input#nextButton").get(0);
$(parentCats).change(ParentChanged);
$(subCats).change(ChildChanged);
});
</script>
</head>
Then I put all of my inline script into a file (myScript.js) and changed my HTML to this:
<head>
<script src="/Scripts/jquery-1.3.2.min.js" type="text/javascript"></script>
<script src="/Scripts/myScript.js" type="text/javascript"></script>
</head>
And now nothing is working. I opened up my page in IE7 and it had a page error that read:
Line: 54
Error: Unknown name.
Line 54 happens to be the last line of my external javascript file.
What am I doing wrong?
Am I right in saying that this is ASP.Net? If it is, inline scripts like:
<%=Url.Action("GetDescription") %>
cannot go in the external JavaScript file.
Did you put the < script > tag inside your myScript.js? If yes, remove them.
Your myScript.js should start with
var optPrompt = "- Select One -";
Since you are now serving the js as a static file, rather than via your ASP, lines like
<%=Url.Action("GetChildCategories") %>
will no longer work as the server doesn't interpret them and replace them with the correct values. You'll need to hard-code them in the script, or leave those lines as inline scripts in the main page and set them as global variables which you can then reference from the external file.