I have a star rating system on my application - the following code works correctly if it is in the PHP doc. But when I remove it and place it in a js file, it doesn't work.
Could someone please let me know why it's not working when i call the js file. Thanks.
<script>
$(document).ready(function(){
$('.rate-btn').hover(function(){
$('.rate-btn').removeClass('rate-btn-hover');
var rating = $(this).attr('id');
for (var i = rating; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-hover');
};
});
$('.rate-btn').click(function(){
var rating = $(this).attr('id');
var dataRate = 'act=rate&app_id=<?php echo $app_id; ?>&id=<?php echo $id; ?>&rate='+rating;
$('.rate-btn').removeClass('rate-btn-active');
for (var i = rating; i >= 0; i--) {
$('.rate-btn-'+i).addClass('rate-btn-active');
};
$.ajax({
type : "POST",
url : "submitRating.php", // I have tried changing this to reflect the directory
data: dataRate,
success:function(){}
});
});
});
</script>
What "TamilSelvan" said is right you can't inject php code in js file. Try keeping the app_id and id in webstorage (or cookies) if you are redirection from some other page to this page and then make use of them in js file else first make AJAX call to retrieve app_id and id then use them.
Related
im using winwheel.js + custom.js , i have also test.php where file is called by Custom.js to get random StopPosition, all works fine, my question is how can i restrict accessing file test.php?action=try directly, because if i access that file it calls php functions (payWheel(),getReward())
test.php generate an item that will be won if someone will spin the wheel
Custom.js:
function startSpin() {
if (wheelSpinning == false)
{
var jsonData = null;
$.getJSON("wheel-responder.php?action=rotate", function (data)
{
console.log(data);
WheelOfFortune.rotationAngle = 0;
WheelOfFortune.animation.spins = 10;
WheelOfFortune.animation.stopAngle = data["lastPosition"];
WheelOfFortune.startAnimation();
wheelSpinning = true;
});
} }
test.php
if(isset($_GET['action']))
{
if($mycredit>= 100){
if($_GET['action'] == 'try')
_Spin(rand(1, 10), 100);
}
}
If you want to restrict the casual user make it a POST request. That would prevent random access thru address bar.
JS FILE
$.post("wheel-responder.php?action=rotate", function (data) {}
PHP FILE
if(isset($_POST['action'])) {}
Not tested but should be trivial.
I'm currently developing a web application and I am using PHP 8.0.3.
For some reason, the Ajax request is not capable of getting the updated value of the SESSION variable unless I forcefully refresh the page. I am calling the ajax function first when the page finishes loading, and then every minute.
I am using AJAX to update the values on a CanvasJS graph.
Can someone help me identify what am I doing wrong?
First, I start the session on a global file that I require on the scripts.
session_name("mfm");
session_start();
Snippet of my current ajax request on index.php page:
$.ajax({
method: "POST",
url: "php_func/somefile.php",
success: function(data){
console.log(data);
var dbdata = JSON.parse(data);
var qtyNuts = [];
var time = [];
dbdata = dbdata.reverse();
for (i = 0; i < dbdata.length; i++) {
time[i] = dbdata[i][1];
qtyNuts[i] = dbdata[i][0];
}
...
And this is part of the php_func/some_file.php:
if(isset($_SESSION['bar']))
{
$processed = $_SESSION['bar'];
$max = count($processed);
if($max > 5)
{
$max = 5;
}
$recent_data = array_slice($processed, -$max);
foreach($recent_data as $data)
{
$kgs = $data[0] / 120.0;
array_push($kgdata, array($kgs, $data[1]));
}
echo json_encode(array_reverse($kgdata));
}
I typed /php_func/some_file.php on my localhost URL and it works, kgdata array is getting updated as the SESSION variable updates.
And this is a snipped of where the session variable is created (this script runs as soon as the page is loaded and then every minute). Update.php:
$bar = array()
if(isset($_SESSION['bar'])
{
$bar = $_SESSION['bar'];
}
$b = array(count($buffer), date("H:i:s"));
array_push($bar, $b);
$_SESSION['bar'] = $bar;
For some reason, the ajax request does not update the values in the index.php graph, unless I forcefully refresh the page. What am I doing wrong?
I tried
Checking session id. They are the same in all files.
Use $.post instead. I have the same issue.
Change the setInterval for the ajax function to be more than a minute in case there is clashing between update.php and somefile.php
My current code is:
Play.save = function() {
//Hide the buttons
this.printButton.visible = false;
this.saveButton.visible = false;
this.backButton.visible = false;
//Force the game to re-render.
this.game.cameras.render(); //generally not recommended if you can help it
//Get the canvas information
var img = this.game.stage.canvas.toDataURL("image/octet-stream");
this.saveajax(img);
//Show UI again.
this.printButton.visible = false;
this.saveButton.visible = true;
this.backButton.visible = true;
}
Play.saveajax = function(img){
$.ajax
({
url: "http://localhost/ourthing/character/save.php",
type: "POST",
cache: false,
data: {
img: img
}
});
}
The file 'save.php' works (when i simply open the file). It will execute a query which it has to do. Problem here is: with this script i want to update a user with the given post data (img). But it doesnt execute on this request.
(i create data for var img and send this data to the saveajax function, which will open save.php to execute the query).
Im very new to JS/ajax. Does anyone can help me?
Best regards
apparently I cant comment, so my question is what are you getting on save.php
with command like
error_log(print_r($_REQUEST,true));
I suspect JSON issue here. can we see save.php?
Ok didn't see your previous comment, scrap that - your Jquery is not included.
Answer:
I had to include jQuery:
<script src="assets/js/jquery.js" ></script >
Thanks #Don'tVoteMeDown and #Lixus
Save.php file:
$db = framework::getDBO();
$data = array(
'canvas_character' => $_POST['img'],
);
$db->where('id', 1);
$db->update('ot_users', $data);
(i use my own framework)
I have a string array in javascript. But when I use href='mypage.php?id=var', I lost this array. I need keep it out for use it in the $_GET. This is the code:
<script>
var element_selected=[];
var i = 0;
function hrefPage()
{
var pagina = "index.php?id=renew";
location.href = pagina;
}
function loadArray(value)
{
element_selected[i] = value;
i++;
}
</script>
<?php
if(isset($_GET['id']))
{
if ($_GET['id'] == "renew")
{
$selected_elements = array();
$j = 0;
for($j = 0; $j < "<script> document.write(i) </script>"; $j++)
{
$selected_elements[j] = "<script> document.write(elements_selected[j]) </script>";
echo $selected_elements[j];
}
}
}
?>
You need to use local storage to use retain javascript variables value across page reloads
var varName = "sachin";
localStorage.setItem("varName", VarName);
alert(localStorage.getItem("varName"));
Another example how to store array in localstorage
var arrayName= [];
arrayName[0] = prompt("Enter your value");
localStorage.setItem("arrayName", JSON.stringify(arrayName));
//...
var storedValues = JSON.parse(localStorage.getItem("arrayName"));
I have added a simple example here how to set javascript value in localstorage and how to access it
I have provided it as an information for you to retain value across page reloads
but first thing about http is that it is a stateless protocol .Each request fetches data from server and renders it in browser the value here is set in local storage of browser .So if you want to reload some value to script after page reload you need to set some flags and on page load check that flag if flag condition for the required situation arises get data from localstorage else proceed as normal
Check out this tutorial for more information
This is an example of the PHP script I want to get the output from within my javascript file:
data.php
<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>
script.js
$(document).ready(function(){
var data;
// get output from data.php
console.log( data );
});
I just want a way to test to see if the data from within the data.txt file that is being stored in a php variable can be passed into the javascript file and then printed within the javascript console on the html page.
I want to do this so that I can store a variable in the text file and then reference it as it dynamically is updated from multiple users at the same time.
I've seen ways to do this, but it involves the javascript being in the same file as the html, which is not the case here. I'm also using jquery so I don't know if that makes a difference. I've never used php before and am new to javascript, so any help would be appreciated.
You can put you php code in the javascript file if you change the extension to "php". As "php" extensions will get delivered as Html per default, you have to state that it is Javascript in the code.
script.js.php
<?php header('Content-Type: application/javascript');
?>console.log("<?php
$input = file_get_contents('data.txt');
echo $input."\n";
?>");
$(document).ready(function(){
$("#imgTag, #img2").on("click", process);
var size = 0;
function getTarget(evt)
{
evt = evt || window.event;
return evt.target || evt.scrElement;
}
var temp;
console.log("before get");
console.log("post get");
console.log(size);
function changeSize(myName, myOther)
{
var name = myName;
var other = myOther;
if($("#" + name).height() < 400)
{
$("#" + name).height($("#" + name).height() + 5);
$("#" + name).width($("#" + name).width() + 5);
$("#" + other).height($("#" + other).height() - 5);
$("#" + other).width($("#" + other).width() - 5);
}
}
function process(event)
{
var name = getTarget(event).id;
var other;
if(name == "imgTag")
{
other = "img2";
}
else
other = "imgTag";
console.log($("#" + name));
console.log("Changing size!!!");
console.log( $("#" + name).height());
changeSize(name, other);
}
});
You can read that text file directly with jquery like this:
$.ajax({
url : "data.txt",
dataType: "text",
success : function (data) {
// Display the data in console
console.log(data);
// Or append it to body
$('body').append(data);
}
});
The same way you can read output from your php file, in which case you should change the url to point to your php file. Another thing you should read about is different options of communicating server-client side like json data structure etc.
Documentation: https://api.jquery.com/jQuery.ajax/