passing a value from one file to another javascript - javascript

I have a file called functions.js where I have the functiom sum which computes the score that a student takes at a test. I want that sum to be printed into a table in the file admin.php so that the administrator sees all the scores that each student has.
So how can I pass the sum variable to another file? I tried calling the function using the onlick action but that didn't work

I guess you probably want something like this
document.getElementById('saveScoreButton').onclick = {
var r = new XMLHttpRequest,
message = document.getElementById('message'),
score = sum();
message.innerHTML = 'Saving your score; please wait a second';
r.open('get', 'savescore.php?score=' + score, true);
r.send(null);
r.onreadystatechange = function () {
if (r.readyState == 4 && r.status == 200) {
message.innerHTML = 'Saved your score';
}
}
}
This passes the score to a PHP programme savescore.php when you click a button with id saveScoreButton. The PHP programme then has to retrieve it using $_GET["score"].
Note that this would be easy for the user to trick if they understand javascript and see what is happening. They could just type 'savescore.php?score=100' in the browser's address bar. If you want a secure solution the javascript should only pass the user's answers to the PHP programme, which would then mark the test and sum the results.
It is also possible to use the POST method instead of GET to pass a value:
...
r.open('post', 'savescore.php?score=' + score, true);
r.send('score=' + score);
...
Then pick it up in the PHP programme using $_POST["score"].
As mentioned in comments, if you want to compare/tabulate scores, then savescore.php will need to store the values in a database or file so that they can be retrieved by admin.php.

Javascript is ran client-sided, PHP is ran server-sided. Therefor, you have to code something in your javascript which alters the HTML page returned by the PHP script, displaying the result.

Once all of your files are loaded on the client, there isn't a concept of separate js files. The client (browser + javascript) and server (php) are 2 separate entities. When your data is one place the other has no clue it exists. Either research ajax as a method of communicating between the 2 locations or use a form and submit the page to the server.
Good overview of how the server and browser communicate: How does the communication between a browser and a web server take place?
Basics of Form submission: http://www.htmlgoodies.com/tutorials/forms/article.php/3479121/So-You-Want-A-Form-Huh.htm
Basics of Ajax: http://webdesign.about.com/od/ajax/a/aa101705.htm
Ajax with PHP: http://www.switchonthecode.com/tutorials/simple-ajax-php-and-javascript

Related

Add Variable to PHP Session Array From Dynamically created HTML element within PHP Echo [duplicate]

Is it possible to set PHP session variables using Javascript?
In JavaScript:
jQuery('#div_session_write').load('session_write.php?session_name=new_value');
In session_write.php file:
<?
session_start();
if (isset($_GET['session_name'])) {$_SESSION['session_name'] = $_GET['session_name'];}
?>
In HTML:
<div id='div_session_write'> </div>
The session is stored server-side so you cannot add values to it from JavaScript. All that you get client-side is the session cookie which contains an id. One possibility would be to send an AJAX request to a server-side script which would set the session variable. Example with jQuery's .post() method:
$.post('/setsessionvariable.php', { name: 'value' });
You should, of course, be cautious about exposing such script.
If you want to allow client-side manipulation of persistent data, then it's best to just use cookies. That's what cookies were designed for.
or by pure js, see also on StackOverflow :
JavaScript post request like a form submit
BUT WHY try to set $_session with js? any JS variable can be modified by a player with
some 3rd party tools (firebug), thus any player can mod the $_session[]! And PHP cant give js any secret codes (or even [rolling] encrypted) to return, it is all visible. Jquery or AJAX can't help, it's all js in the end.
This happens in online game design a lot. (Maybe a bit of Game Theory? forgive me, I have a masters and love to put theory to use :) ) Like in crimegameonline.com, I
initialize a minigame puzzle with PHP, saving the initial board in $_SESSION['foo'].
Then, I use php to [make html that] shows the initial puzzle start. Then, js takes over, watching buttons and modding element xy's as players make moves. I DONT want to play client-server (like WOW) and ask the server 'hey, my player want's to move to xy, what should I do?'. It's a lot of bandwidth, I don't want the server that involved.
And I can just send POSTs each time the player makes an error (or dies). The player can block outgoing POSTs (and alter local JS vars to make it forget the out count) or simply modify outgoing POST data. YES, people will do this, especially if real money is involved.
If the game is small, you could send post updates EACH move (button click), 1-way, with post vars of the last TWO moves. Then, the server sanity checks last and cats new in a $_SESSION['allMoves']. If the game is massive, you could just send a 'halfway' update of all preceeding moves, and see if it matches in the final update's list.
Then, after a js thinks we have a win, add or mod a button to change pages:
document.getElementById('but1').onclick=Function("leave()");
...
function leave() {
var line='crimegameonline-p9b.php';
top.location.href=line;
}
Then the new page's PHP looks at $_SESSION['init'] and plays thru each of the
$_SESSION['allMoves'] to see if it is really a winner. The server (PHP) must decide if it is really a winner, not the client (js).
You can't directly manipulate a session value from Javascript - they only exist on the server.
You could let your Javascript get and set values in the session by using AJAX calls though.
See also
Javascript and session variables
jQuery click event to change php session variable
One simple way to set session variable is by sending request to another PHP file. Here no need to use Jquery or any other library.
Consider I have index.php file where I am creating SESSION variable (say $_SESSION['v']=0) if SESSION is not created otherwise I will load other file.
Code is like this:
session_start();
if(!isset($_SESSION['v']))
{
$_SESSION['v']=0;
}
else
{
header("Location:connect.php");
}
Now in count.html I want to set this session variable to 1.
Content in count.html
function doneHandler(result) {
window.location="setSession.php";
}
In count.html javascript part, send a request to another PHP file (say setSession.php) where i can have access to session variable.
So in setSession.php will write
session_start();
$_SESSION['v']=1;
header('Location:index.php');
Not possible. Because JavaScript is client-side and session is server-side. To do anything related to a PHP session, you have to go to the server.
be careful when doing this, as it is a security risk. attackers could just repeatedly inject data into session variables, which is data stored on the server. this opens you to someone overloading your server with junk session data.
here's an example of code that you wouldn't want to do..
<input type="hidden" value="..." name="putIntoSession">
..
<?php
$_SESSION["somekey"] = $_POST["putIntoSession"]
?>
Now an attacker can just change the value of putIntoSession and submit the form a billion times. Boom!
If you take the approach of creating an AJAX service to do this, you'll want to make sure you enforce security to make sure repeated requests can't be made, that you're truncating the received value, and doing some basic data validation.
I solved this question using Ajax. What I do is make an ajax call to a PHP page where the value that passes will be saved in session.
The example that I am going to show you, what I do is that when you change the value of the number of items to show in a datatable, that value is saved in session.
$('#table-campus').on( 'length.dt', function ( e, settings, len ) {
$.ajax ({
data: {"numElems": len},
url: '../../Utiles/GuardarNumElems.php',
type: 'post'
});
});
And the GuardarNumElems.php is as following:
<?php
session_start();
if(isset ($_POST['numElems'] )){
$numElems = $_POST['numElems'];
$_SESSION['elems_table'] = $numElems;
}else{
$_SESSION['elems_table'] = 25;
}
?>

Sending data from javascript to php to generate a pdf but doesn't work

I am using JavaScript to take the info from a form completed by the user, then sending this data to PHP and generate a PDF with FPDF. The problem is I want the browser to ask the user to save the PDF or view it online but
I cannot figure out how. The PDF generates correctly but only when I save it directly to a certain path specified by me.
The question is how do you guys send data from JavaScript to PHP to generate a PDF file then the browser asks the user to open or download, Or how can I make a function where the user can retrieve this PDF.
The JavaScript:
function senddata() {//this activates when i push a button not a submit
var peticion = new XMLHttpRequest();
peticion.open('POST', 'generatepdf.php');
var nueva2 = {};
var key;
for (i = 0; i < 6; i++) {
key = document.forms[0].elements[i].id;
nueva2[key] = document.forms[0].elements[i].value;
}//here i take my data from the form and make an object
var json = JSON.stringify(nueva2);//here i tranform my object to json string so i can send it to my php
var parametros = "json_string=" + json;//here I do this so later I can easily transform the $_POST to an array in the form json_decode($_POST["json_string"],true);
peticion.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
peticion.send(parametros);//it sends ok
}
The PHP with the FPDF class and things
<?php
require('fpdf/fpdf.php');
require('functions.php');
if($_SERVER['REQUEST_METHOD']=='POST'){
$datos=json_decode($_POST["json_string"],true); //here i have my data in an array format so i can use the parameters to fill my pdf fields
//...lots of pdf things here...//
$pdf->Output('F',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this works but never ask the user
//$pdf->Output('D',"pdfs/Cotizacion ".$datos["nombres"]." ".$datos["apellidos"].".pdf");//this should force a dowload or send to the browser but doesnt work
//$pdf->Output();//this should send to the browser but doesnt work
}
To view your PDF inline to the browser, you should use the I variable instead. View full documentation here.
Also I don't think outputting the file in two methods at the same time works. It might conflict each other. The best way to do that is to test each method and if it does conflict each other just simply add a condition for the user to decide whether he/she wants to download or view it in the browser. Hope this helps.

Two Different Javascript Alerts before redirecting in ASP.NET

I want to show different alert messages using JavaScript. Here is my code, but my alert box will not show before the redirect. I tried the other examples provided but those are all using just one type of alert message. I use this ShowAlertMessage method to show other types of warnings as well, in which I don't want to redirect to any other page. Just give the user a warning.
If (user creates a new work order)
{
ShowAlertMessage("Property work order " + txtWorkOrderNumber.Text + " created successfully");
}
else
ShowAlertMessage("Property work order updated successfully");
Response.Redirect("~/DashBoard.aspx");
public static void ShowAlertMessage(string msg)
{
Page page = HttpContext.Current.Handler as Page;
if (page != null)
{
string script = "alert(\"'" + msg + "'\");";
ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", script, true);
}
}
You're sending a Response.Redirect, which means your response does not have any content, but rather just the URL to redirect to.
In order to do what you're trying to do, you'd have to write out the javascript to the current page, then once the alerts fire, use javascript to move to a new URL.
Maybe something like the following:
string script = string.Format("alert('{0}'); window.location.href='{1}';",
msg, ResolveUrl("~/Dashboard.aspx"));
This is a common example of a problem with WebForms - it's very difficult to properly mix client and server code together to provide a good user experience, which is why I much prefer doing my user experience stuff completely in javascript, with AJAX to do most of the posts.

AJAX to send a JS variable to a PHP file (and then to DB)

What I am trying to do:
I have a ready made HTML5 game incorporated onto my website - Link to game
Using this game, I want to now implement a high score board and display it on the same page.
Example, if I am logged in as Conor, Conor goes to snake_game.php where the game is located. He gets a score of three, I need the value of three, which currently is assigned to a JavaScript variable, to become a PHP variable so that I can store it into a table called high_scores in my database.
Then, once the data is in my database, I can start showing the results on the high score variable and update the data when needed.
Problem(s):
I understand that I have to use AJAX to achieve this, but I have never used AJAX before.
Resources:
snake_game.php is where the container is located where the game is displayed, as well as the high scores div:
<div id="wrapper">
<div class="game_canvas">
<canvas id="canvas" width="450" height="450"></canvas>
<script src="javascript/snake.js"></script>
</div>
<div class="high_scores" >
High scores:
</div>
</div>
snake.js is where all the JavaScript is found to create the game. All the JavaScript is available to view in the link above.
What I have tried:
From the game's JS, I believe the score is kept in a var called score - var score; - Knowing this, I have tried the below approach in an attempt to get . I have tried to watch a few tutorials online and have come up with this (located in snake_game.php):
<script type="text/javascript">
function updateScore ()
{
var score = $('score').val();
$.post('snake_game.php', {postscore: score},
function ()
{
$('high_scores').html(data);
});
}
</script>
and then PHP code:
<?php
$new_highscore= $_POST['score'];
echo json_encode($new_highscore);
?>
I believe the following get's data from the JS? But I am not sure, nor do I think it is the correct way to approach this.
Any/all help would be appreciated :)
If I were you I would not do this in vanilla php but of course you can.
Things to note:
1) You're not passing your response data into your call back method in your jQuery post
2) you aren't selecting anything with jquery
$.post('snake_game.php', {postscore: score},
function (data) // <-- pass data in here;
{
$('high_scores').html(data); //<!-- you aren't selecting anything here.
//if I were you I would make data a json
//I would have something like
$('.high_scores').append(data.high_score);
//actually I have no idea why you even have this callback here
});
3) I don't really understand you're explanation of snake_game.php. It seems like you are trying to use it as both a template and an endpoint. If you are doing things in vanilla php, which I strongly discourage you from doing, you need another php file to handle your post request. e.g. snake_high_scores.php.
//in snake_high_scores.php
//this is a really bad way to learn ajax requests. You should use a framework
$new_highscore= $_POST['score'];
//store this score in a db maybe you can pickup the user id from a session cookie
echo json_encode({data => {high_score => $some_highscore}});
In addition to above answers I would suggest whenever game loads make the high score available in page (place in a hidden element/input field if you don't want to show to user) then once the game ends then compare the user score with high score if it is greater than current one then make the Ajax call to php to store in DB.
This works for both per user (make user high score available once user logs in) or global single high score.
You can't access 'score' outside the "ready" function. If you want to implement things the way you were thinking above, you'll have to add a global reference to score, though I'll warn you that's generally frowned upon.
// Make a global reference to score
var score;
$(document).ready(function(){
//Canvas stuff
var canvas = $("#canvas")[0];
var ctx = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
//Lets save the cell width in a variable for easy control
var cw = 10;
var d;
var food;
//var score; THIS NOT NEEDED ANYMORE.
You're better off adding your function with the Ajax call within the ready() function just like the code from the tutorial. The way the game works is everytime you run into a wall, the game resets itself by calling the "init" function. To do what you're wanting, before the score gets reset to zero, you want to send it to the server. See below for an idea:
function init()
{
d = "right"; //default direction
create_snake();
create_food(); //Now we can see the food particle
// Before resetting the score below, send the user score
// to the server
sendScoreToServer(score);
//finally lets display the score
score = 0;
........
EDIT:
Freddy, here's the simplest Ajax demo I can give you. You need to study this and fiddle with it until you understand what's going on. After you understand this demo below, you should be able to figure out how to do what you want above. YOU WILL NEED TO EDIT THE <SCRIPT> FILE PATHS AND AJAX URL TO AJAXDEMO.PHP IN MY EXAMPLE FILES TO MATCH YOUR SYSTEM.
In some HTML file:
<!DOCTYPE html>
<html>
<head>
<title>Ajax Demo</title>
</head>
<body>
<input type="text" name="score" id="scoreBox"><button id="sendScore">Send Score to Server Running PHP</button>
<div id="result">The result from the server will be placed here...</div>
<script src="/resources/js/jquery-1.12.3.js"></script>
<script src="/resources/js/ajaxDemo.js"></script>
</body>
</html>
ajaxDemo.js file:
// This function uses AJAX to send the score from the HTML page running javascript to a web server running PHP.
function sendScoreToServer(theScore) {
$.ajax({
type: "POST",
url: "http://localhost/ajaxDemo.php",
data: { score: theScore },
dataType: 'json',
success: function(response){
console.log(response);
$('#result').html('The score returned by the server is: '+response.scoreDoubled);
}
});
}
// Once the HTML page finishes loading, this binds a 'onClick' event to the button that causes it to trigger the sendScoreToServer function.
$( document ).ready(function() {
$('#sendScore').on('click', function() {
var score = $('#scoreBox').val();
sendScoreToServer(score);
});
});
In ajaxDemo.php file on the server:
<?php
$result = [];
$result['scoreDoubled'] = $_POST['score'] * 2;
echo json_encode($result);
Final Encouragement:
It sounds to me like you might be slightly confused regarding front-end code vs. back-end code and what the difference is. Just remember that Front-End code runs on the USER'S computer. So when you visit that game tutorial website and it loads the Snake game... that game is running on YOUR computer. Back-End code (PHP is a back-end language) is code that runs on a web server... meaning generally NOT on your computer. By running a web server on your machine with "localhost", you are essentially having your PC 'pretend' to be a web site so you can quickly test and develop your application. Thus any Ajax calls to 'localhost' never have to leave your machine. HOWEVER, in a normal usage environment, an Ajax call would be sending a request over the internet to some remote server such as www.MySite.com. MySite.com would then process the info sent to it using PHP or some other language, then send a response back, which gets processed by the "success" function attached to the ajax request. The "success" function (commonly called a 'callback' function) then updates the HTML page with some result based on what the server sent back.

Execute javascript inside the target of an Ajax Call Drag and Drop Shopping Cart without Server language

Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.

Categories

Resources