Send a string from javascript to php (in the same file) - javascript

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.

Related

Passing a JavaScript value to PHP on completion of quiz

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");
});

How do I fetch PHP script output from Javascript?

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/

Why isn't my Javascript Ajax call posting values to my PHP script?

This is a very strange issue. The Javascript IS calling the PHP script, and the PHP script IS returning "something" (it returns array ()). The issue is, when I try to get the value of the posted data via $_POST['ID'] it basically says that there is no posted value, even though sendData does contain a value for ID. The full string of sendData (obtained through alert(sendData)) is as follows:
ID='1'&Invoice=''&FirstName=''&LastName=''&Description=''&Testimonial=''&ScreenRoom='false'&GlassWindow='true'
Javascript File: admin.js
function saveChanges() {
var sendData='ID=\'' + document.getElementById("ID").value + '\'';
sendData+='&Invoice=\'' + document.getElementById("Invoice").value + '\'';
sendData+='&FirstName=\'' + document.getElementById("FirstName").value + '\'';
sendData+='&LastName=\'' + document.getElementById("LastName").value + '\'';
sendData+='&Description=\'' + document.getElementById("Description").value + '\'';
sendData+='&Testimonial=\'' + document.getElementById("Testimonial").value + '\'';
sendData+='&ScreenRoom=\'' + document.getElementById("ScreenRoom").checked + '\'';
sendData+='&GlassWindow=\'' + document.getElementById("GlassWindow").checked + '\'';
var req = new XMLHttpRequest();
req.open("POST","scripts/saveChanges.php",true); //true indicates ASYNCHRONOUS
req.send(sendData);
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
alert(sendData);
alert(req.responseText);
}
}
}
PHP File (that is being posted to): saveChanges.php (located in /scripts/)
<?php
session_start();
if (!isset($_SESSION['group']) || $_SESSION['group'] != 'admin') {
die ('You do not have permission to access this page!');
}
print_r($_POST);
$ID=$_POST['ID'];
$Invoice=$_POST['Invoice'];
$FirstName=$_POST['FirstName'];
$LastName=$_POST['LastName'];
$Description=$_POST['Description'];
$Testimonial=$_POST['Testimonial'];
$Date=$_POST['Date'];
$GlassWindow=$_POST['GlassWindow'];
$ScreenRoom=$_POST['ScreenRoom'];
?>
I normally only come here in a state of desperation, and being I've spent about 3 hours now working on trying to figure this out, I consider myself fairly desperate. Any help would be greatly appreciated and please ask if you need more information.
You have to set the content type for php to read the variables
req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
Remove the quotes from the posted data and properly encode it
var sendData='ID=' + encodeURIComponent(document.getElementById("ID").value);
sendData+='&Invoice=' + encodeURIComponent(document.getElementById("Invoice").value);
sendData+='&FirstName=' + encodeURIComponent(document.getElementById("FirstName").value);
sendData+='&LastName=' + encodeURIComponent(document.getElementById("LastName").value);
sendData+='&Description=' + encodeURIComponent(document.getElementById("Description").value);
sendData+='&Testimonial=' + encodeURIComponent(document.getElementById("Testimonial").value);
sendData+='&ScreenRoom=' + document.getElementById("ScreenRoom").checked;
sendData+='&GlassWindow=' + document.getElementById("GlassWindow").checked;
Set the ready state listener before you send the request
req.onreadystatechange = function() {
//Is request finished? Does the requested page exist?
if(req.readyState==4 && req.status==200) {
//Your HTML arrives here
alert(sendData);
alert(req.responseText);
}
}
req.send(sendData);
Try to set HTTP header:
req.setRequestHeader("Content-type","application/x-www-form-urlencoded");

running a php function inside javascript code [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I hope to run a php code inside a javascript code too and I do like that :
<?php function categoryChecking(){
return false;
}?>
....
function openPlayer(songname, folder)
{
if(<?php echo categoryChecking() ?> == true)
{
if (folder != '')
{
folderURL = "/"+folder;
}else
{
folderURL = '';
}
var url = "/users/player/"+songname+folderURL;
window.open(url,'mywin','left=20,top=20,width=800,height=440');
}else{
alerte('you should click on a subcategory first');
}
}
....
<a href='javascript:void();' onClick="openPlayer('<?php echo $pendingSong['id']; ?>','')">
finally I get this error instead the alert message "you should click on a subcategory first"
ReferenceError: openPlayer is not defined
openPlayer('265','')
You're reduced your test case too far to see for sure what the problem is, but given the error message you are receiving, your immediate problem has nothing to do with PHP.
You haven't defined openPlayer in scope for the onclick attribute where you call it. Presumably, the earlier JS code is either not inside a script element at all or is wrapped inside a function which will scope it and prevent it from being a global.
Update: #h2ooooooo points out, in a comment, that your PHP is generating the JS:
if( == true)
Check your browser's error console. You need to deal with the first error messages first since they can have knock on effects. In this case the parse error in the script will cause the function to not be defined.
Once you resolve that, however, it looks like you will encounter problems with trying to write bi-directional code where some is client side and some is server side.
You cannot run PHP code from JavaScript, because PHP is a server-side language (which runs on the server) and JavaScript is a client-side language (which runs in your browser).
You need to use AJAX to send a HTTP request to the PHP page, and then your PHP page should give a response. The easiest way to send a HTTP request using AJAX, is using the jQuery ajax() method.
Create a PHP file ajax.php, and put this code in it:
<?php
$value = false; // perform category check
echo $value ? 'true' : 'false';
?>
Then, at your JavaScript code, you should first add a reference to jQuery:
<script type="text/javascript" src="jquery.js"></script>
Then, use this AJAX code to get the value of the bool:
<script type="text/javascript">
$.ajax('ajax.php')
.done(function(data) {
var boolValue = data == 'true'; // converts the string to a bool
})
.fail(function() {
// failed
});
</script>
So, your code should look like this:
function openPlayer(songname, folder) {
$.ajax('ajax.php')
.done(function (data) {
var boolValue = data == 'true'; // converts the string to a bool
if (boolValue) {
if (folder != '') {
folderURL = "/" + folder;
} else {
folderURL = '';
}
var url = "/users/player/" + songname + folderURL;
window.open(url, 'mywin', 'left=20,top=20,width=800,height=440');
} else {
alert('you should click on a subcategory first');
}
})
.fail(function () {
// failed
});
}

Sending URL as a parameter using javascript

I have to send a name and a link from client side to the server. I thought of using AJAX called by Javascript to do this.
This is what I mean. I wished to make an ajax request to a file called abc.php with parameters :-
1. http://thumbs2.ebaystatic.com/m/m7dFgOtLUUUSpktHRspjhXw/140.jpg
2. Apple iPod touch, 3rd generation, 32GB
To begin with, I encoded the URL and tried to send it. But the server says status Forbidden
Any solution to this ?
UPDATE ::
It end up calling to
http://abc.com/addToWishlist.php?rand=506075547542422&image=http://thumbs1.ebaystatic.com/m/mO64jQrMqam2jde9aKiXC9A/140.jpg&prod=Flat%20USB%20Data%20Sync%20Charging%20Charger%20Cable%20Apple%20iPhone%204G%204S%20iPod%20Touch%20Nano
Javascript Code ::
function addToWishlist(num) {
var myurl = "addToWishlist.php";
var myurl1 = myurl;
myRand = parseInt(Math.random()*999999999999999);
var rand = "?rand="+myRand ;
var modurl = myurl1+ rand + "&image=" + encodeURI(storeArray[num][1]) + "&prod=" + encodeURI(storeArray[num][0]);
httpq2.open("GET", modurl, true);
httpq2.onreadystatechange = useHttpResponseq2;
httpq2.send(null);
}
function useHttpResponseq2() {
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
}
Server Code
<?php
include('/home/ankit/public_html/connect_db.php');
$image = $_GET['image'];
$prod = $_GET['prod'];
$id = $_GET['id'];
echo $prod;
echo $image;
?>
As I mentioned, its pretty basics
More Updates :
On trying to send a POST request via AJAX to the server, it says :-
Refused to set unsafe header "Content-length"
Refused to set unsafe header "Connection"
2 things.
Use encodeURIComponent() instead of encodeURI().
Here is a detailed discussion on this: When are you supposed to use escape instead of encodeURI / encodeURIComponent?
If you are new to JavaScript, use some lib to help you do the AJAX work. Like mootools, jQuery, etc.
Using a POST request solved my issue :)
function addToWishlist(num) {
var url = "trial.php";
var parameters = "prod=" + encodeURIComponent(storeArray[num][0]) + "&image=" + encodeURIComponent(storeArray[num][1]);
httpq2.open("POST", url, true);
httpq2.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpq2.onreadystatechange = function(){
if (httpq2.readyState == 4) {
if(httpq2.status == 200) {
var mytext = httpq2.responseText;
document.getElementById('wish' + num).innerHTML = "Added to your wishlist.";
}
}
};
httpq2.send(parameters);
}

Categories