i need to unset $_POST['u'] but only inside a javascript function, now $_POST ARRAY unsets itself automatically after the page is ready...
function resetChat(cod_c){
if(confirm('are you sure?')){
if (sendReq.readyState == 4 || sendReq.readyState == 0) {
sendReq.open("POST", 'getChat.php?chat='+cod_c+'&last=' + lastMessage, true);
sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
sendReq.onreadystatechange = handleResetChat;
var param = 'action=reset';
param += '&user=' + document.getElementById('cod_user').value;
sendReq.send(param);
document.getElementById('txt_message').value = '';
}
<?php unset($_POST['u']); ?> // this only 1 time after confirm???
}
}
function handleResetChat() {
}
PHP is server side language and JavaScript is on client side :) You need learn more about webdev ;)
Related
I'm trying to pass a javascript variable to php on the same page. I tried some code but nothing worked.
The current code looks like this:
function init(e){
$('#DeleteDaily').click(function() {
d = document.getElementById("DailyRequestsList");
selected = d.selectedIndex;
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "index.php?i=" + selected, true);
xhttp.send();
});
}
$(document).ready(init);
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}
?>
});
});
If I try to use Index as an argument for a python script it should delete an entry in a textfile and an element from a select object should be deleted on the website which doesn't happen. The python script itself works fine.
But I don't know why the variable isn't passed to php.
You can't just "mix" javascript and PHP like you're doing.
If that is inside a web page, the PHP code will be rendered (in your case, it will return nothing), and the page will just interpret an empty javascript function.
You need that PHP to be on the server, or turn it into javascript...
you can done it by
PHP Code
<?php
if(isset($_POST['DeleteDaily'])) {
$Index = $_GET['i'];
}else{
$Index='';
}
?>
Javascript code
$(document).ready(function() {
$('#myForm').ajaxForm(function() {
var index = '<?php echo $Index;?>';
if(index == ''){
//put your code
}else{
//put your code
}
});
});
So basically, I got a php file where I create a script in the header.
In this script, I take the value of two textbox with document.getElementByID and I concatenate them in a variable. But now, in the same script, I want to send that var to a php section to use it.
I tried the ajax way, but since the php and the javascript is in the same file, it make an error.
Here is what the script section looks like :
IN FILE.PHP
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
<?php
$parameter = command; <----- obviously not working, but that's basically what im looking for
$output = exec("someExecutable.exe $parameter");
(...)
?>
}
</script>
EDIT 1
So here it is, I tried to use ajax this time, but this isn't working, seems like i miss something. Here is the server.php:
<?php
$parameter = $_POST['command'];
$output = exec("someexecutable.exe $parameter");
$output_array = preg_split("/[\n]+/", $output);
print_r($parameter);
?>
And here is my ajax call in my client.php (in a js script):
var command = "find";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
var ajax = new XMLHttpRequest;
ajax.open("POST", "server.php", true);
ajax.send(command);
var output_array = ajax.responseText;
alert(output_array);
For some reason, it doesn't go farther then the ajax.open step. On the debugger console of IE10, i got this error : SCRIPT438: Object doesn't support property or method 'open' .
You are trying to run a serverside script in your ClientSide script,
that's never going to work.
https://softwareengineering.stackexchange.com/questions/171203/what-are-the-differences-between-server-side-and-client-side-programming
If you want to do something with the data from text_1 and text_2, you should create a php file that can handle a post/get request via AJAX or a simple submit, featuring the data from those elements, and make it return or do whatever it is you want it to end up doing.
You can't use javascript variable (client) from php (server). To do that, you must call ajax.
<script type="text/javascript">
rowNum = 0;
function some_function()
{
var command = "somebasiccommand";
if(document.getElementById("text_1").value != "" && document.getElementById("text_2").value != "")
{
command += " " + document.getElementById("text_1").value + " " + document.getElementById("text_2").value;
}
//AJAX call to a php file on server
//below is example
var ajax = window.XMLHttpRequest;
ajax.open("POST", "yourhost.com/execute.php", true);
ajax.send(command);
}
</script>
And this is execute.php on server
<?php
$parameter = $_POST['command'];
$output = exec("someExecutable.exe $parameter");
(...)
?>
Alright... I pretty much changed and tested many things and I found out that the problem was the async property of the .send command. I was checking the value of the respondText too fast. Putting the third property of .open to false made the communication sync, so I receive the infos properly. I got another problem right now, but its not the same thing, so I will do another post.
The send() function is my JavaScript function which uses AJAX $.post. Though the function(data) is successful, everything I intend it to do is working fine. But the data being sent, in my example, recipient && chat_sent && date is not being sent to the global variable $_POST. The second part of the code is my PHP code. Though since the data is not being sent, the if statement IN MY PHP CODE cannot be executed. What could be the problem?
function send(){
var datetemp= new Date();
var tempUser = "<? echo $user ?>";
var tempRecipient = document.getElementById("recipient_chat").value;
var chat_message= document.getElementById("chat_area").value;
$.post("searchPresentation.php", {chat_sent: chat_message, date: datetemp,
recipient:tempRecipient}, function( data ) {
$("#window").text(datetemp + $("#window").text() + tempUser + " - " + chat_message);
});
}
This is searchPresentation.php:
if (isset($_POST['chat_sent']) && isset($_POST['date']) && isset($_POST['recipient']))
{
//DO SOMETHING
}
if (!empty($_POST['chat_sent']) && !empty($_POST['date']) && !empty($_POST['recipient']))
{//DO SOMETHING}
all of param already set! "document.getElementById("chat_area").value" maybe is ' ' but it is set so use empty()
I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});
i'm trying to use PHP to move some files, as it does that I have a script which will compare the source location with the destination location and work out the difference.
It all starts with a button like so:
<input type="button" class="upload_button" onClick="upload_images('drive_<?=$x["letter"]?>');start_upload_progress()" value="<?=$x["name"]?>"/>
This then starts these two scripts:
function upload_images(x) {
var url = "http://localhost:1234/ppa/php/process_upload.php?x="+x
doc("upload_iframe").src = url;
}
First of all it will change a hidden iframe url to the PHP script and send over the drive letter.
function start_upload_progress() {
upload_progress("http://localhost:1234/ppa/php/upload_progress.php",function() {
doc("upload_bar").innerHTML = this;
if(this != 100) {
//doc("upload_bar").innerHTML = x;
setTimeout(start_upload_progress(),1000);
}
});
}
Next the above script will start, the console.log is simply for me to see if it's working, although I do not see "start" in my console. This function uses a callback, the below code simply loads a PHP script and returns the result. If the result is less than 100 then the call is made again every couple of seconds.
function upload_progress(url, callback) {
var http = getHTTPObject();
http.onreadystatechange = function() {
if (http.readyState == 4 && http.status == 200) {
if (http.responseText == "true") {
//window.location.replace("http://localhost:1234/ppa/rotate.php");
}
callback.call(http.responseText);
}
};
http.open("GET", url, true);
http.send();
}
Below is the PHP script, this was working when I set the $_SESSION['tmp'] variable manually.
<?php
session_start();
//If session has been created then ready to start progress bar
if (isset($_SESSION['tmp'])) {
if ($_SESSION['tmp'] != "true") {
$session_date = str_replace("/","",$_SESSION['session_date']);
$tmp = explode("_", $_SESSION['tmp']);
$upload_number = $tmp[1];
$drive = $tmp[0];
//get paths
$destination = $_SESSION['ROOT_PATH']."data/images/".str_replace("/","",$_SESSION['session_date'])."/".$upload_number."/";
$source = $drive.":/DCIM/";
if (is_dir($destination) && is_dir($source)) {
$source_size = foldersize($source);
$destination_size = foldersize($destination);
echo "Percentage: ".floor(($destination_size / $source_size * 100));
}
} else {
echo "done: ".$_SESSION['tmp'];
}
}
function foldersize($path) {
$total_size = 0;
$files = scandir($path);
$cleanPath = rtrim($path, '/'). '/';
foreach($files as $t) {
if ($t<>"." && $t<>"..") {
$currentFile = $cleanPath . $t;
if (is_dir($currentFile)) {
$size = foldersize($currentFile);
$total_size += $size;
}
else {
$size = filesize($currentFile);
$total_size += $size;
}
}
}
return $total_size;
}
?>
The $_SESSION['tmp'] variable is created just before the files begin to move, it seems like I can't access this session variable until the code has finish executing...
It is created here, at the top of the file moving script:
if (isset($drive)) {
$x = explode("_", $drive);
$x = $x[1];
//Check if connected file exists
if(file_exists($x.":/connected.txt")) {
$file = file_get_contents($x.":/connected.txt");
if ($file != false) {
$file_code = split(":", $file);
//Check if the file has the correct pass code
if($file_code[0] == $code) {
$_SESSION['tmp'] = $x."_".$drive;
When the files have finished moving the variable is set to "true", which seems to be the only value I can get...
Any ideas why my "start_upload_progress" function is not working? The console.log isn't running and I don't think the $_SESSION['tmp'] variable is setting until the file moving script has finished.
Edit 2:
I have got the script running, it compares the source and the destination and updated the innerHTML of the div with the difference. Only issue is that it only seems to work when I move the files from one place to the other manually.
The upload_progress script seems to freeze whilst the files are being moved, it should run at the same time to check the progress.
I have watched the files disappear from the source folder as well but all at the same time, shouldn't they move one by one as the scripting is only moving them one by one...