Assigning a php variable from a javascript variable - javascript

I am trying to set a php variable for use in a later page with out using $_GET or $_POST. I am also assigning the same variable to a text box. I already have the function to assign the textbox variable but not the php variable.
function setText(data){
document.getElementById("filtext").value = data.value
// <?php $_SESSION["provid"] = ?>
// I am trying to set the php variable above
}
Any help would be greatly appreciated!

I think in this case, setting a cookie would be the easiest solution. By setting the cookie using Javascript, the cookie key and value will automatically be sent to PHP with the next page request.
See also:
http://www.w3schools.com/js/js_cookies.asp, especially "A Function to Set a Cookie"
http://www.w3schools.com/php/php_cookies.asp, especially "How to Retrieve a Cookie Value?"

To send a value for a server-side language you can use AJAX.
function setPHPVariable()
{
var myAjax;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
myAjax=new XMLHttpRequest();
}
else
{// code for IE6, IE5
myAjax=new ActiveXObject("Microsoft.XMLHTTP");
}
myAjax.onreadystatechange=function()
{
if (myAjax.readyState==4 && myAjax.status==200)
{
alert('PHP returned: ' + myAjax.responseText);
}
}
myAjax.open("GET","my_file.php?my_var=12345", true);
myAjax.send();
}
In your PHP code, you can use:
$myVar = $_GET['my_var'];
$_SESSION['my_var'] = $myVar; // or even $_SESSION['my_var'] = $_GET['my_var'];
http://www.w3schools.com/ajax/ajax_examples.asp

Related

Call PHP function by name from JavaScript

I have a javascript function that's executed on a button click and I have an included file containing all my PHP functions. One of the PHP functions returns me an array of filenames encoded as a JSON object. I'd like to call this function from my Javascript function so that I can use the array. I know I can call a PHP file which would run but in this case I only want to call one specific named method.
I tried the following but couldn't get it to work (Console error: Unexpected < )
function getPHPArray(){
var picArray;
picArray = <?php getPicArrayJson(); ?>;
}
Can this be done using XMLHttpRequest or do I need to find another method? (If reasonably possible I'd prefer straight Javascript over JQuery but I can use JQuery if it makes this significantly easier)
If so how?
My PHP method is as follows:
function getPicArrayJson(){
global $fileArrayString;
If (!empty($fileArrayString)){
echo json_encode($fileArrayString);
}
}
My JavaScript so far:
function getPHPArray(){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST", "phpFunctions.php?name=getPicArrayJson", true);
xmlhttp.send();
}
This is essentially a Remote Procedure Call. For use with PHP, I'd check out JSON-RPC PHP.
Anyway, here's a basic way you can do it without much complexity to your app. You will have to make an ajax request to the server. The idea for you here is to use call_user_func.
call_user_func("getPicArrayJson");
You can use
call_user_func($_POST["name"]);
But I highly recommend that you only allow certain functions to be called
phpFunctions.php
$allowed_functions = array("getPicArrayJson");
$name = $_POST["name"];
function getPicArrayJson() {
$pics = array("1.jpg", "2.jpg");
return json_encode($pics);
}
// legal function
if (in_array($name, $allowed_functions)) {
header("Content-Type: application/json");
$json = call_user_func($name);
die($json);
}
// invalid access
else {
// Error 400
}
Then do you Ajax request per normal
...
xmlhttp.open("POST", "phpFunctions.php?name=getPicArrayJson", true);
xmlhttp.send();
ps my own two cents, I would use a GET request for this. Following RESTful API conventions for web services, a POST request would only be used to create a new element.

AJAX - Not getting a simple php response(returns "undefined")

I don't know why xmlhttp.response is returning undefined after contacting the php file.
index.php
<script language="Javascript">
var countdown;
countdown = setInterval(function(){
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){
alert(xmlhttp.responsetext);
}
}
xmlhttp.open("GET","updateindex.php?id=8",true);
xmlhttp.send();
},3000);
</script>
updateindex.php
<?php
echo "hi";
?>
It should alert "hi" every 3 seconds, but it alerts "undefined" every 3 seconds.
Note the capital T in responseText. So it should be xmlhttp.responseText.
In javascript, "undefined" means the variable you tried to access is not defined, i.e., it doesn't exist. When you see that, you should check right away for typos. In this case,
xmlhttp.responsetext should be xmlhttp.responseText. The lowercase property you selected does not exist.
In WebKit browsers like Chrome and Safari (and I'm sure in others, but those are the ones I use) you can also check your variable names in the console. Google how to use the developer tools in your browser. When you're having trouble referencing a property on an object like you are now, it's often helpful to type/log the object name into the console, which will then show you a list of all its properties. For instance, if you add console.log(xmlhttp) to your script, it will show the object and all its properties in the console, and you can see that the property you want is responseText, not responsetext.

Pass a variable from JS to AJAX to PHP [duplicate]

This question already has answers here:
How does Ajax work with PHP?
(2 answers)
Closed 9 years ago.
Below is the code I have.
The flow needs to be:
-On button click, value is passed to JS
-JS sets as variable
-The variable needs to be sent to PHP without refreshing the page (AJAX?)
-The variable needs to be output in php
Can anyone show me how to do this?
<button onclick="updateVar(2)" class="btn btn-acceptColor m-t-lg">Accept</button>
<script type="text/javascript">
function updateVar(profferRequestID){
var profferRequestID;
//pass to ajax then pass to php??
}
</script>
<?php
//echo out that JS variable
echo $profferRequestID;
?>
Oy. I need 6 more points before I can add a comment.
Please answer the following questions:
Does this have to be cross-browser compatible?
If so, you may want to consider using the jQuery JavaScript library. There are a "ton" of browser inconsistencies with AJAX that jQuery abstracts out.
Either way, you may consider using jQuery because of it's powerful AJAX libraries.
Do you want to return the php response to your JavaScript function, or display it somewhere on your HTML page?
After you answer that, I'll be happy to provide you with a complete answer. I'm trying to give back to the StackOverflow community. :)
try something like this
using jquery
javascript code
var name = "John";
$.get( "your_file.php", { user_name: name},function( data ) {
// on success perform action you want.
});
php code
$user_name = $_GET['user_name'];
ANOTHER WAY
In javascript (not checked)
var name = "John";
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)
{
// on success perform action you want.
}
}
xmlhttp.open("GET","your_file.php?user_name="+name,true);
xmlhttp.send();
EDITED CODE
function updateVar(val){
$.get( "path_to/your_file.php", { profferRequestID : val},function( data ) {
// on success perform action you want.
});
}
your_file.php
$profferRequestID = $_GET['profferRequestID'];
I'm not familiar with AJAX, or PHP, but I know that in javascript, you can read/edit innerhtml. I think your best bet would be to create a hidden element, and use that to store your variables.

Javascript Unexpected token ILLEGAL

I have a PHP script (fetchData.php) that fetches some data and outputs it to a page.
<?php
require 'config.php';
require 'jsonapiSDK.php';
$api = new JSONAPI($ip_address, $jsonapi_port, $username, $password, $salt);
$response = $api->call('BWMFunction');
echo(addslashes($response["success"].";"));
?>
You can see the output here: http://justicecraft.net/worldmap/fetchData.php
I have another page that uses an XMLHttpRquest to get the response from fetchData.php
Here's the JavaScript for it. It's supposed to take the response, and eval() it (to create an array called BWMFunction) then pass that array to another function I have. The Illegal token error occurs when I try to eval() the response.
function fetchData() {
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) {
res = xmlhttp.responseText;
alert(res);
eval(res);
generate(BWMFunction);
}
}
xmlhttp.open("GET", "fetchData.php", true);
xmlhttp.send();
}
This is my first time on StackOverflow, so any help would be appreciated. I have googled around for quite a while now, but none of the answers helped me.
You have invalid javascript returned from fetchData.php which is why the eval method crashes. Instead of \" in the output you should have simple ". I know strictly nothing about PHP but I am ready to bet some bucks that its the addslashes function which is causing the damage. So maybe you could try something along the lines of:
echo($response["success"].";");

How to stop xmlhttp.open duplicating the entire page? (ajax livesearch)

I am using a simple "live search" script that displays the results from a MySQL database as the user types into a text box. It works perfectly fine if the Javascript is pointing to a completely separate page but I need it to point to the same page. Unfortunately when I try and do this the page is duplicated within itself as the results are generated.
This works as expected:
Document called: "test.php" containing JavaScript below and test2.php containing the PHP code
xmlhttp.open("GET","test2.php?livesearch="+str,true);
xmlhttp.send();
This creates a page within a page:
Document called: "test.php" containing both the JavaScript and PHP code below
xmlhttp.open("GET","?livesearch="+str,true);
xmlhttp.send();
I understand that it's because it is opening itself in a loop but I'm not sure what I am supposed to change in the code to avoid this. Any help would be greatly appreciated as I haven't found much help via Google.
Here is all my code:
Javascript
function showResult(str)
{
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)
{
document.getElementById("livesearch").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","&livesearch="+str,true);
xmlhttp.send();
}
PHP Code
if(isset($_GET['livesearch'])) {liveSearch();}
function liveSearch() {
$q=$_GET["livesearch"];
$sqlQuery = "SELECT * FROM something WHERE something LIKE '%" . $q . "%' ;
etc etc etc
}
Why would you want the code to point to itself? Seems logical to have a web service that would return only the content that is needed. It is not like you have to duplicate the code, just make some common method that spits out the content in the full page or in the web service.
If you need to call the same page, you can always use a regular expression to rip out the content that you need instead of replacing the whole page.

Categories

Resources