I know this sound weird but I need to be able to use a variable in javascript and use it inside a php mysqli query
I use the jQuery File Upload from blueImp. It's variable are store like this
{%=file.name%}
and I need to do something like this
$iq = $mysqli->query("SELECT * FROM image WHERE mId='".$_GET['mId']."' AND file_name = '".{%=file.name%}."'");
of course this is not working because of the {}.
Anyone have a clue how to work with those kind of programming ?
In javascript:
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState == 4) {
//POST request sent
}
};
xmlhttp.open("POST", "url_to_phpfile.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("yourvariable="+yourvariable);
Then you can use that variable in your php file like so:
$iq = $mysqli->query("SELECT * FROM image WHERE mId='".$_GET['mId']."' AND file_name = '".$_POST["yourvariable"]."'");
No, you cannot directly do this**.
Javascript is something that will execute at client side(browser).
PHP is a server side scripting language.
If you want to pass a Javascript variable in PHP , then you can do so through AJAX
Related
I'm having a weird problem here and I can't seem to figure out why I can't pass one array to the PHP script using ajax, but I can pass another array without any problems.
Here's my ajax function:
function update(){
var hr = new XMLHttpRequest();
var url = "update.php";
var vars = "array="+arr;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(vars);
}
The variable "arr" is a 2d array loaded with coordinates, like so: [[2,3],[4,5],[5,2]...] and it's user-generated, every time user inserts new set of coordinates, I use PUSH to add them to the array.
It is declared just above this function, inside the javascript.
This seems to be working fine, because when I do alert(JSON.stringify(arr)); inside the ajax function, I can see clearly the coordinate pairs pop up in my browser.
However, when I catch the array on the other side (php script) and write it into a notepad file using:
<?php
$fp=fopen("ajax.txt","w");
$data = $_POST['array'];
fwrite($fp,$data);
fclose($fp);
?>
The file ajax.txt is created but remains empty.
However, when I initialize another array (arr1) inside the ajax function, like this:
function update(){
var arr1=[[2,3],[4,5],[5,7]];
var hr = new XMLHttpRequest();
var url = "update.php";
var vars = "array="+arr1;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send(vars);
}
The PHP script seems to write the array to the notepad file without any problems! Why does this happen? Clearly the "arr" variable is not empty, because we can see the contents of it using alert.
Any ideas?
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
pass php variable to javascript
I want to compare the click count(s) clicked by the users with the data saved in database.
I am not sure how to proceed to pass the value of the HTML "clicks" to compare with "counts" in PHP.
<html>
<script type="text/javascript">
var count = 0;
function countClicks()
{
count = count + 1;
document.getElementById("clicks").innerHTML = count;
}
</script>
<?php
if(empty($counts)){
?>
<script type="text/javascript">
alert("Count is empty!!");
</script>
<?php
} else {
$data = mysql_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'");
$info = mysql_fetch_array($data);
//compare $data with the clicks
echo 'same!';
}
?>
<body>
Count Clicks
<input type="button" onclick=countClicks() value="Click"/>
<p id="clicks">0</p>
</body>
</html>
You are using PHP and Javascript in the wrong way. PHP is a serverside language. which means it runs before the page even loaded on the browser.
You will have to create a javascript click counter and put its values into a hidden formfield. Then use a submit button to send the information to the server (PHP). Then let PHP do the checks and selections from the database and return an answer.
Another solution is to use javascript AJAX, but I do recommend first trying the above.
The best way to proceed would be to make an Asynchronous JavaScript and XML call (AJAX). PHP is a server-side language, which is executed before the HTML (thus, before Javascript) is built and shown to the browser.
Therefor, the only way for Javascript to exchange variables and data with PHP is to make an AJAX call (you could always reload the page with a form submit or with session variables and cookies, but this isn't the best way to go if action is repeated too often.
IN AJAX, you can make another PHP page that will check both values and return whatever you want. The response can be stored in a Javascript variable, or even in JSON.
I suggest you to read more about AJAX and also get to know what is PHP how to use it.
Edit: After reading your comment, I decided to put a simple example down here.
Javascript (in your HTML page)
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
/*Here you should do what you want.
xmlhttp.responseText is the content of your PHP answer! */
var result = xmlhttp.responseText;
//I am parsing a JSON response, which is a specific, universal language
//To exchange data without losing formatting or anything else.
result = JSON.parse(result);
/* The we use the name of our PHP array key as a property
Here it is "response" (see PHP json_encode line) */
alert(result.response);
}
}
/* Change this URL for the PHP filename. we use the GET method to send data. */
/* You should always use the POST method when sending sensitive data */
xmlhttp.open("GET","getUserClicks.php?clicks="+count+"&username="+username,true);
xmlhttp.send();
PHP (here it is the file named getUserClicks.php )
<?php
if(!isset($_GET['username']) || !isset($_GET['clicks']))
die("Error");
$username = $_GET['username'];
$jsClicks = $_GET['clicks'];
$phpClicks = null;
#I am using the mysqli class to execute the query since mysql is deprecated in PHP5.
$data = mysqli_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'");
while($row = mysqli_fetch_array($data))
{
$phpClicks = $row['clicks'];
}
#If your "IF" only contains one line, you don't need brackets.
#Otherwise they are needed.
if($phpClicks == null)
die("Could not get the number of clicks of the desired username");
#This is the string PHP will send to Javascript.
$response = "Same number of clicks!";
#If phpClicks is different and has the same type as jsClicks...
if($phpClicks !== $jsClicks)
{
$response = "Number of clicks changed!";
if($jsClicks > $phpClicks)
{
#Updates the number of clicks the user has done.
$mysqli_result = mysqli_query("UPDATE customerdetails SET clicks=$jsClicks WHERE customer_username='$username';");
}
}
echo json_encode(array('response'=>$response));
?>
Be sure to make some research if you see functions or methods you have no idea what they do (eg.: isset).
i have loaded a file into an array using ajax and after splitting it i need to save it to the file again.This all happens onClick of a button.
function updatetags(){
var alreadyexistingtags;
var responsetext;
var r2 = new XMLHttpRequest();
r2.open('GET', 'tagsupdated.txt', true);
r2.send(null);
r2.onreadystatechange = function() {
if (r2.readyState == 4 && r2.status==200) {
responsetext=r2.responseText;
alreadyexistingtags=responsetext.split(' ');
}
}
}
i understand that javascripts are not server side and that's why i cannot do what i want,but i'm sure there must be a way to write alreadyexistingtags[ ] to tagsupdated.txt.Any help?Perhaps i should somehow pass the array to PHP?And if so how is that possible given that PHP gets executed when the page loads,when i need to wait for the button to be pressed?
You're going to have to use AJAX or some other method to send the data back to your server, which can then write the file out.
To do this, just create a new script on your server, say writearray.php, which accepts the Javascript array as input. Then use AJAX to send a request to that file with your array.
The PHP file would look something like so (this is a highly simplified example):
<?php
file_put_contents("where_you_want_the_file.txt", $_POST['array']);
?>
It looks like you're just storing your Javascript array as a space separated list, so the Javascript would look something like this:
var str = your_array.join('%20'); // URL encoded spaces separating array entries
var params = "array=" + str;
var http = new XMLHttpRequest();
http.open("POST", "your_script.php", true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");
http.onreadystatechange = function() {
if(http.readyState == 4 && http.status == 200) {
// Do something on success?
}
}
http.send(params);
The way this works, is you're sending a POST with a field named array, which holds the textual representation of your Javascript array. The PHP code checks $_POST['array'] to get this value, then writes it to your file.
Note that if you want to do anything more complicated, you should look into using JSON. And also as always be very careful with what you do with user data.
For send data you must doing another ajax query but in .send method you have to pass a string with data
Example:
var r3 = new XMLHttpRequest();
r3.open('POST', 'writeTextWithoutTags.php', true);
var data_string='text='+alreadyexistingtags+'&etcParams='+etc_you_params;
r3.onreadystatechange = function()
{
if (r3.readyState == 4 && r3.status==200)
{
alert(r3.responseText);//write result
}
}
r3.send(data_string);
Before sent alreadyexistingtags variable you must implode array to string with separator or better to JSON string.
But in writeTextWithoutTags.php ypu must check data because javascript execute ib user brouser and you can not be sure that the data is sent from yavastsript not undergone processing intruder!
P.S. If you can access to PHP I dont understang I do not understand why you are here JS - all this actions you can douing in PHP and not to drive data from the server to the browser and back
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to pass a variable / data from javascript to php and vice versa?
I have 3 javascript variables which gives me an id, a name and a surname as such:
if (!response.error) {
document.getElementById("meName").innerHTML = response.id
+ " " + response.name
+ " " + response.surname ;
}
Now I want to pass those variables (response.id, response.name and response.surname) into my database.
Something like this:
<?php
$query = mysql_query("INSERT INTO users (id, name, surname) VALUES
('response.id', 'response.name', 'response.surname')") or die(mysql_error());
$result = mysql_fetch_array($query);
return $result;
?>
How can I do this?
This is what you need:
if (!response.error) {
var uid = response.id;
var firstname = response.name;
var surname = response.surname
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
xmlhttp.open("GET", "ajax.php?uid=" + uid + "&firstname=" + firstname + "&surname=" + surname , true);
xmlhttp.send();
return false;
}
and in your ajax file:
<?php include("YOUR_CONNECTION_FILE.php");
$uid = mysql_real_escape_string($_GET['uid']);
$firstname = mysql_real_escape_string($_GET['firstname']);
$username = mysql_real_escape_string($_GET['surname']);
$query = mysql_query(" YOUR MYSQL QUERY ") or die(mysql_error());
?>
Well, ajax would be the best choice in your case.
Check my answer here How to send a form without refreshing the page?
Check out some documentation also:
jQuery Documentation
jQuery.ajax() - jQuery API
Ajax - jQuery API
Tutorials
Net Tuts+ - 5 Ways to Make Ajax Calls with jQuery
Beginners Guide to Using AJAX with jQuery
I'm guessing you're trying to pass the javascript variables to php.
In order to do this you need to use a POST or GET method.
This question's answer will help.
You'd need to make an AJAX call to a separate PHP script which stores the variables.
Javascript runs browser-side, whereas PHP runs on the server - by the time the browser is running the Javascript code in the page, it has already finished running on the server and thus all of the PHP code has already executed.
I believe that response is your return via ajax, if so, you should check two things
First, set the ajax dataType to 'json'.
Second, replace
return $result
to
return json_encode($result);
By.
I'm sure it is just a simple issue, I have looked in the forums but couldn't find an example that was specific to my issue.
Basically I am displaying a table of hrefs, which each have an onclick() call to an ajax method, using a 'get' and a url.
function createRequestObject(){
var req;
if(window.XMLHttpRequest){
//For Firefox, Safari, Opera
req = new XMLHttpRequest();
}
else if(window.ActiveXObject){
//For IE 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
}
else{
//Error for an old browser
alert("Your browser is not IE 5 or higher, or Firefox or Safari or Opera");
}
return req;
}
//Make the XMLHttpRequest Object
var http = createRequestObject();
function sendRequest(method, url){
if(method == "get" || method == "GET"){
http.open(method,url,true);
http.onreadystatechange = handleResponse;
http.send(null);
}
}
function handleResponse(){
if(http.readyState == 4 && http.status == 200){
var response = http.responseText;
if(response){
document.getElementById("DIVNAME").innerHTML = response;
}
}
}
The call for an href looks like:
echo '<td><a href="#" onClick="sendRequest(\'get\', \''.$toPass.'\')"/>'.$variable.'</a></td>';
The $toPass variable is page.php?variable1='.$variable1.'&variable2='.$variable2.'&variable3=blah&action='.$option.'
When I pass a variable 1 for example : 'TP111010114' it works fine, the _REQUEST['variable1']; grabs the variable and pushes it the through my sql request.
if the variable contains a # for example : 'Blah #2' the only piece of data that gets through is
Variable 1 = 'Blah ' with the remaining variables being unassigned.
From what it looks like it is not getting anything after the #.
I tried encoding the url in php, then unescaping it in my ajax.js where you call window.open('get', unescape(url), true); but I had the same result, it worked with any variable that didn't contain #. When I tried to encode it using urlencode() and not decoding it in my ajax.js, the request was not going through.
The encoded request looks like:
page.php%3Fvariable1%3DTP111010114%26variable2%3D64%26variable3%3Dnew%26Action%3DOthers
if it is not encoded it looks like:
page.php?variable1=TP111010114&variable2=64&variable3=new&Action=Others
I used firebug to monitor the .js variables as they go through and it looks as though when I encode it that it should grab the proper variable, but it still only grabs before the # in the variable
http://www.randomsite.ca/page.php?variable1=WF225+Amendment+#2&variable2=543&variable3=new&Action=Others
Yet this request on the php side still gets $variable = $_REQUEST['variable1']
$variable = 'WF225 Amendment ', and the other variables are unnassigned.
It must be something to do with the way something is handling the #, but I do not see what I am missing here, if anyone could help it would be much appreciated.
I have renamed information for privacy purposes
You need to urlencode the values you're putting into the URL, not the whole URL including variable names. You want to encode the "blah #2" but not the "&variable1=" part. Ex:
$toPass = 'page.php?variable1=' . urlencode($variable1) . '&variable2=' . urlencode($variable2) ...etc
You won't need any decoding on the HTML/JS end.
I believe that it may be parsing anything after the # as a named anchor which will likely disregard the variables after this point... have you tried using a method that doesn't rely on the # character? Or even try using POST as the AJAX method?