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

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.

Related

Assigning a php variable from a javascript variable

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

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.

How can i dialog-answer yes or no in PHP and do php code depending on answer? [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 figured how i can get a dialog and seems like i need to use javascript but this doesnt let me follow up with php code depending on the answer unless there is a way?
<?php
$ime = "Marko";
echo <<< EOT
<SCRIPT language="JavaScript">
var hi= confirm("Do you really want to deactivate $ime?");
if (hi== true){
<?php ?>
alert("$ime Deactivated!");
// I need to do php code here...
}else{
alert("Skipping $ime");
// I need to do php code here...
}
</SCRIPT>
EOT;
?>
Improving on #papirtiger's answer, you could use AJAX to pass onto the PHP code seamlessly without a page reload.
All AJAX really is is the way you can pass data from javascript to a PHP file. Because PHP is server side, any PHP script that needs to be executed MUST be on the server. PHP generates the script and sends it to the client and the connection between the client and the server is done when the generated page downloads. Javascript can continue its work as it is client side. But since it's on the client's machine, it can't run a PHP script inside it as it can't be interpreted.
AJAX takes data from PHP and sends it like a Form would (using POST or GET variables), executes a separate PHP file on the server, grabs the response from the script and puts it into the javascript without the entire page reloading.
Here is what your script could look like.
<script>
if (window.confirm("Are you sure?")){
// Begin the AJAX function
$.ajax({
// Declare the type (GET or POST)
type = "POST",
// The local server location to the PHP script to get the response from
url = "yes.php",
// Data to send (in this case nothing needs to be sent)
data = "",
// Get the response if a script is executed successfully
success: function(response) {
// Display the response from the script in an alert box
alert(response);
}
)};
} else {
// Rinse and repeat using another file
$.ajax({
type = "POST",
url = "no.php",
data = "",
success: function(response) {
alert(response);
}
)};
}
</script>
You would also need to include the jQuery library in the head of your HTML otherwise this AJAX markdown will not work and you would have to result to traditional (and ugly/messy) pure javascript AJAX executions.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
Hope this helps! :)
PHP is a server-side scripting language. You can not trigger it with JavaScript.
#StashCat´s answer is totally correct, however the pattern you are looking for is something like this:
<script>
if (window.confirm("Are you sure")){
window.location("/yes.php");
} else {
window.location("/no.php");
}
</script>
Note that the script that is running will continue until it exits.
The user is then presented with the web page and the confirm box. When they click the yes or no they will be redirected and a new script will be run.
in a nutshell, its not a good solution for languages mix like this. According to a code you have, i can declare a global varaibale with php like <?php <script> var some = "123"; </script> ?> and then use it in client javascript code, but i'll repeat its bad approach. You'd better to refactor your code.
Php code runs on Server, while javascript code runs on client i.e., your browser. So, you can't write code to display a dialog box at server side, But you can dynamically remove and add HTML elements using Ajax. You can code your dialog box in javascript and call an Ajax block. A typical example of Ajax(Ajax--> Async Javascript) code,
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
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)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>

Calling multiple perl scripts over APACHE server?

I am pretty new to creating web applications, so I am very unfamiliar with working over a web server. Just to let everyone know, I am implementing html, javascript, strawberry perl, AJAX, and running over an APACHE 2 web server. I finally have my web app working, I have an html file that calls a perl script that is in my htdocs directory. Here is a mock up of my .html file for reference, this one simply alerts the user of the output printed by the perl script:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
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()
{
var str;
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// Get output from perl script and print it
str = xmlhttp.responseText;
alert(str);
}
}
xmlhttp.open("GET","http://localhost/try.pl" , false); //perl script
xmlhttp.send();
}
</script>
</head>
<body>
<h2>Example</h2></div>
<button type="button" onclick="loadXMLDoc()">Display</button>
</body>
</html>
So this file test.html calls a perl script [try.pl] within the same directory. Also, the perl script just prints a number so this alerts the user of the number. This is just an example of my implementation. My actual perl script and java script [inside the ready state block] is much more complicated. Now I have to add functionality to my web app, so to my questions:
I am looking to run a second and separate perl script when a different event happens. For example, when a button is clicked this perl script is being ran. I am going to have another different event, say a double click on an icon or something, that will need to call this second perl script. Will I simply have the new event call a different function [the first is called Loadxmldoc()] that is almost identical to the one I have here except it will have different code in the ready state block and call a different perl script at the end of it? I am a little confused as to how to implement this.
Also, If I have a list of file names within my javascript code, I need to process EACH of the files using a perl script. Currently I am only processing one so calling the perl script as I have here is fine. I have looked all over the internet to try to find how I would do this but it seems every explanation just covers how to call "a" CGI script. So within my code, say where I am "alerting" the user, I am going to have an array that stores the file names. I need to iterate over this array and for each filename [array element] I need to call the same perl script to process that file. How should I go about implementing this? Currently, my html file is only calling the perl script once and I do not know how I could call it for EACH file since my GET command is outside of my ready state block...
Any help or direction would be appreciated. I am expected to deliver soon and have been spending way too much time sifting through repetitive examples that haven't helped me...:/
As far as generalizing your AJAX request, you can create a function (or rather, a set of functions) that would process different types of responses, as follows:
var requests = [];
requests['script1'] = "http://localhost/try.pl";
requests['script2'] = "http://localhost/try2.pl";
var response_processing = [];
response_processing['script1'] = function (xmlhttp) {
var str = xmlhttp.responseText;
alert(str);
};
// Here, you can add more functions to do response processing for other AJAX calls,
under different map keys.
Now, in your AJAX code, you call an appropriate request AND appropriate response processor, based on your script name (passed to loadXMLDoc() call as follows): loadXMLDoc("script1");
function loadXMLDoc(script_name) {
// Your generic AJAX code as you already implemented
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
response_processing[script_name](xmlhttp);
// Careful so script_name doesn't get closured in onreadystatechange()
}
}
xmlhttp.open("GET", requests[script_name], false); //perl script
xmlhttp.send();
}

beginner question: using open method does not load my text file

server: apache http server 2.2
problem: code does not load my text file
hello people. im currently trying to learn javascript and am following several tutorials. written below is a code off of w3schools. what its supposed to do is change the displayed text upon clicking the button. however, this does not work for me. the html file where the code below is save and the text file im trying to open are in the same folder.
im accessing the html file off of chrome using this: http://localhost/ajaxtutorial.html. while it does display the html file correctly, upon clicking the button nothing happens. ive tried changing the file to php and making an equivalent php file to the said text file but still nothing happens. please help.
<html>
<script type="text/javascript">
//comments are from http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php
function loadXMLDoc(url , cfunc)
{
var xmlhttp;
//XMLHttpRequest object is used to exchange data with a server behind the scenes
//creates an xmlhttprequest object
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//The XMLHttpRequest object has a special property called onreadystatechange
//onreadystatechange stores the function that will process the response from the server
//every time the "ready state" changes, this function will be executed
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function myFunction()
{
loadXMLDoc
("ajax_info.txt",
function()
{
//The XMLHttpRequest object has another property called readyState
//This is where the status of our SERVER'S RESPONSE is stored
//The SERVER RESPONSE can be processing, downloading or completed
//When the property readyState is 4 that means the response is complete and we can get our data
//Download worked as intended, data request successful if status property = 200
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
);
}
</script>
<div id="myDiv">
<h2>Let AJAX change this text</h2>
</div>
<button type="button" onclick="myFunction()">Change Content</button>
In myFunction the xmlhttp variable is not in the scope of the function. This should be causing a JavaScript error, which you can view in Chrome by going to Menu > Tools > JavaScript console. One way to fix this would be to pass the xmlhttp object as a parameter.
function loadXMLDoc(url , cfunc) {
//some code...
xmlhttp.onreadystatechange=function() {
//pass xmlhttp as a parameter to this function and preserve the context
//see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/call
cfunc.call(this, xmlhttp);
}
//some more code...
}
function myFunction() {
loadXMLDoc("ajax_info.txt", function(xmlhttp) {
//xmlhttp is now in scope because we passed it as a parameter
});
}
Update
I created a working example at http://jsfiddle.net/6rPgE/
As for your question about the modifications I suggested...
The second parameter to the loadXMLDoc method (cfunc) is a function. In this case, an anonymous function is created inside myFunction which will be passed as the cfunc parameter to loadXMLDoc. When the onreadystatechange callback is invoked, the cfunc function is called with xmlhttp as the first parameter. This parameter is passed into the anonymous function defined inside myFunction, and is responsible for actually doing something with the AJAX response. On an entirely different note, I highly recommend using a debugger (Chrome has one built-in) and the information provided by the browser's error console to assist you in debugging these issues in the future. Learning how to use a debugger will save you countless hours of banging your head against the wall.
Update 2
Just thought it would be nice to look at how this can be done using jQuery with quite a bit less code. AJAX is one area where it can be really nice to use a library that abstracts away the details.
Another example that uses jQuery at http://jsfiddle.net/j9QvE/1/
Update 3
Note that in my code I replaced the path to ajax_info.txt with a path specifically used for testing AJAX functionality in jsFiddle (/echo/js/?js=Success!). This was necessary because ajax_info.txt does not exist on the jsFiddle servers, so requesting it would have resulted in a 404 error. Don't forget to change the path to point to an appropriate resource on your own domain.

Categories

Resources