Jump to content

Passing a Javascipt variable via $_POST array


alan_k

Recommended Posts

I am trying to pass a variable from a javascript function to my php file. All I do is extract the user_name from a cookie in javascript and then use AJAX to $_POST the variable to my php file for processing. I do not use a form to submit the POST variable which I have done in the past.The problem is my $_POST array is not getting passed to the php file. I've looked here and looked at several other suggestions but none work. Do you have to submit the $_POST variable via an html form? I dont think so but maybe I'm wrong. Here is the code:Javascript -

function clearDoneItems()  {    var user_name = getNameFromCookie();        if (window.XMLHttpRequest)   {       // code for IE7+, Firefox, Chrome, Opera, Safari       xmlhttp=new XMLHttpRequest();     }    else {        // code for IE6, IE5       xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");     }       alert(user_name);    xmlhttp.open("POST","todolist/clear_done_items.php",true);    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");    xmlhttp.send(user_name);    displayHomeInformation(user_name);    }

PHP -

<!DOCTYPE html>    <html>        <head>    <meta content="text/html; charset=utf-8" http-equiv="Content-Type">    <title>Clear Done Items</title>    </head>        <body>    <?php        ini_set('display_errors',1);    error_reporting(E_ALL);    print_r($_POST);          $xml_name=$_POST['user_name'];        $xml_file = $xml_name . ".xml";      echo $xml_file;            /* Here we will use the The DOMDocument class functions to delete           the text nodes.               Format XML to save indented tree rather than one line */    $domxml = new DOMDocument('1.0');        if ($domxml->load('$xml_file') === TRUE) {    $domxml->preserveWhiteSpace = false;    $domxml->formatOutput = true;        // Start Delete process of node    echo "<br>";        $xpath = new DOMXPath($domxml);    // Here we use the The DOMXPath class function evaluate to do the heavy lifting.        foreach ($xpath->evaluate('//doneitems/item') as $node) {      $node->parentNode->removeChild($node);    }        //Save XML to file - remove this and following line if save not desired    $domxml->save('alan.xml');    echo "<strong>XML Document updated.</strong>";     }         else {    echo "  <strong>Error in loading XML file:</strong>";     echo "<br>";     print_r(error_get_last());         }          ?>        </body>        </html>

>Errors on php page:Notice: Undefined index: user_name in /var/www/bb/todolist/clear_done_items.php on line 160Warning: DOMDocument::load(): I/O warning : failed to load external entity "/var/www/bb/todolist/$xml_file" in /var/www/bb/todolist/clear_done_items.php on line 24

I thought from reading up on AJAX the POST variable is set from the three commands xmlhttp.open,.setRequestHeader and .send. Dont these take the place of the POST action in an html form?

Link to comment
Share on other sites

I changed line to

xmlhttp.open("POST","todolist/clear_done_items.php",true);    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");    xmlhttp.send('user_name='+ user_name);

but get same exact error. $_POST array is still empty. Just to be clear I dont need the ".onreadystatechange" event handler if all I want is to pass the user_name to the php script and dont need anything back form the script?

Edited by alan_k
Link to comment
Share on other sites

It does have to be submitted by form, it just needs event to send to function to process and send as $_POST array

 

What i would do, is first to check if is actually getting to php file for processing, just do it the normal way where the returned value is returned and go from there, you know from there on that it works and go from there.

Link to comment
Share on other sites

I'm sorry it does or it doesnt have to be submitted in form? I know i'm not getting to php file because print_r($POST) is printing out array ().

Edited by alan_k
Link to comment
Share on other sites

Using ajax you don't need to submit, that is the point of ajax you don't submit, leave/reload page, you just use event to send value/s to ajax codingit send value to php and processes blah blah blah, without leaving page and without reload of page.

 

look at http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_post2

 

NO FORM. event is onclick

Edited by dsonesuk
Link to comment
Share on other sites

That's what I thought by reading up on ajax, that all I needed was the xmlhttp.send. Any ideas then on why the _POST array is empty when I send it to my php file? I even tried GET and that didnt work. I'm really stumped by what I'm doing wrong here. Any input much appreciated...

Link to comment
Share on other sites

You can use print_r to print the entire $_POST array to see what's in it, or you can also use your browser's developer tools to check the ajax request going out to make sure that it's a post request with the correct data.

Link to comment
Share on other sites

Just out of curiosity, how exactly are you using this? What does the displayHomeInformation function do? It looks like the page you're contacting through ajax is returning a full HTML page with display_errors on, that's not usual with ajax. You're not pulling up that clear_done_items.php page in the browser, are you? You understand that ajax runs in the background?

Link to comment
Share on other sites

Here is function:

function displayHomeInformation(user_name) {  document.getElementById("loginArea").innerHTML =  "<h3>Welcome, "  + user_name + ". <br>" +  "<a href='#' onClick='logout(); return false'>logout</a> </h3>";   displayLegalLists(user_name);}

It just displays some login information for user. But forget about that I cant even get the POST array to my php page. I'm lost as to why this happening. I've verified you dont need

a form to submit and create the POST array, yes? These 3 lines should create and send the POST array to my php file:

  xmlhttp.open("POST","todolist/clear_done_items.php",true);    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");    xmlhttp.send(user_name); 

And yet the array is empty??? Is my understanding wrong? What is responsible for creating and sending the POST array? And what is it I'm doing wrong. So to be clear step 1 I get user_name from cookie and put it in a variable step-2 I issue the xmlhttp commands mentioned above that will create the POST array and send my user_name variable in the array to my php file step -3 The php file looks for the user_name in the POST array and assigns it to php variable and then I can work on the appropriate XML file based on the user_name. Thanks for your time.

Edited by alan_k
Link to comment
Share on other sites

You should use the developer tools to look at the request going out so that you can see exactly what it looks like, especially the post data you're sending. Like was mentioned before, when you send post data you do it as a URL-encoded string with name/value pairs, you don't just send a value. When you submit a form the browser will URL-encode all of the data into a string of name/value pairs and send that as the request body, you need to replicate that behavior when sending your own post request. If a post request comes in and the request body has data in the correct format then PHP will use it to populate the $_POST array.

Link to comment
Share on other sites

AGAIN! this xmlhttp.send(user_name);

 

should be xmlhttp.send('user_name='+user_name);

 

and this

if ($domxml->load('$xml_file') === TRUE) //ends up looking for '$xml_file'

 

should be

 

if ($domxml->load($xml_file) === TRUE) //ends up looking for in this case 'wellThisIsLoadOfBollocks.xml'

 

You won't be able to tell if it has carried out any of the code, cause it runs in the background you can only see return confirmation with onreadystatechange function.

 

These are rough mock up to get same result you should be getting

 

html

<!DOCTYPE html><html>    <head>        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">        <meta name="viewport" id="viewport" content="target-densitydpi=high-dpi,initial-scale=1.0,user-scalable=no" />        <title>http://w3schools.invisionzone.com/index.php?showtopic=53422</title>        <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>        <script  type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1.10.4/jquery-ui.min.js"></script>        <script type="text/javascript">            window.onload = function() {                clearDoneItems();            }            function clearDoneItems() {                var user_name = getNameFromCookie();                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;                    }                }                alert(user_name);                xmlhttp.open("POST", "todolist/clear_done_items.php", true);                xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");                xmlhttp.send('user_name=' + user_name);                displayHomeInformation(user_name);            }            function getNameFromCookie()            {                return "wellThisIsLoadOfBollocks";            }            function displayHomeInformation(user_name) {                document.getElementById("loginArea").innerHTML =                        "<h3>Welcome, " + user_name + ". <br>" +                        "<a href='#' onClick='logout(); return false'>logout</a> </h3>";                displayLegalLists(user_name);            }            function displayLegalLists(user_name)            {                alert('legal List ' + user_name);            }        </script>        <style type="text/css">        </style>    </head>    <body>        <div id="loginArea">TODO write content</div>        <div id="myDiv">TODO write content</div>    </body></html>

php file placed in A folder 'todolist' at same location/level as above file

<?phpini_set('display_errors', 1);error_reporting(E_ALL);print_r($_POST);$xml_name = $_POST['user_name'];$xml_file = $xml_name . ".xml";echo $xml_file;/* Here we will use the The DOMDocument class functions to delete  the text nodes.  Format XML to save indented tree rather than one line */$domxml = new DOMDocument('1.0');if ($domxml->load($xml_file) === TRUE) {    $domxml->preserveWhiteSpace = false;    $domxml->formatOutput = true;    // Start Delete process of node    echo "<br>";    $xpath = new DOMXPath($domxml);    // Here we use the The DOMXPath class function evaluate to do the heavy lifting.    foreach ($xpath->evaluate('//doneitems/item') as $node) {        $node->parentNode->removeChild($node);    }    //Save XML to file - remove this and following line if save not desired    $domxml->save('alan.xml');    echo "<strong>XML Document updated.</strong>";} else {    echo "  <strong>Error in loading XML file:</strong>";    echo "<br>";    print_r(error_get_last());}?>

xml file 'wellThisIsLoadOfBollocks.xml'

<?xml version="1.0" encoding="UTF-8"?><!--To change this license header, choose License Headers in Project Properties.To change this template file, choose Tools | Templatesand open the template in the editor.--><root>    </root>

result

Welcome, wellThisIsLoadOfBollocks.logoutArray ( [user_name] => wellThisIsLoadOfBollocks ) wellThisIsLoadOfBollocks.xmlXML Document updated. 
Edited by dsonesuk
Link to comment
Share on other sites

Sorry for the delay in responding. I just want to thank every one for input and post how I solved issue. I will have to revisit using the $_POST array with

AJAX cause I was never able to pass a variable thru it.

Javascript:

// Clear Done Items Functionfunction clear_done_items(){var xmlhttp;var temp = document.getElementById("list_section");var temp_list_name = temp.innerHTML;var str_len = temp_list_name.length;var list_name = temp_list_name.slice(17,str_len);var user_name = getNameFromCookie();if (user_name == list_name) {  if (window.XMLHttpRequest) {    // code for IE7+, Firefox, Chrome, Opera, Safari    xmlhttp=new XMLHttpRequest();   }  else {    // code for IE6, IE5  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }xmlhttp.open("POST","todolist/clear_done_items.php",true);xmlhttp.send();} else {   alert("Warning: You Must be Logged in as this User, " + list_name + ", to Delete the Completed Items List");  }}

and php:

<!DOCTYPE html><html><head><meta content="text/html; charset=utf-8" http-equiv="Content-Type"><title>Clear Done Items</title></head><body><?phpini_set('display_errors',1);error_reporting(E_ALL);$xml_cookie = $_COOKIE['user'];$xml_file_name = $xml_cookie . ".xml";    /* Here we will use the The DOMDocument class functions to delete       the text nodes.*/         //Format XML to save indented tree rather than one line$domxml = new DOMDocument('1.0');if ($domxml->load($xml_file_name) === TRUE) {$domxml->preserveWhiteSpace = false;$domxml->formatOutput = true;// Start Delete process of nodeecho "<br>";$xpath = new DOMXPath($domxml);// Here we use the The DOMXPath class function evaluate to do the heavy lifting.foreach ($xpath->evaluate('//doneitems/item') as $node) {  $node->parentNode->removeChild($node);}//Save XML to file - remove this and following line if save not desired$domxml->save($xml_file_name);echo "<strong>XML Document updated.</strong>"; } else {echo "  <strong>Error in loading XML file:</strong>"; echo "<br>"; print_r(error_get_last()); } ?></body></html>

so basically I'm using a cookie to get the user_name variable to php to process from the main page.

 

 

Link to comment
Share on other sites

There's not much security with that, a user can change whatever cookies they want (and you even tell them what to change it to in order to get it to work). The normal way to do that is to store things like a username in the session instead of a cookie, and then when someone tries to do something that requires authorization you look them up in the session and see if they're allowed. Your PHP code isn't authorizing the username in the cookie either, it's just using it as part of a filename to delete. The end result is that someone can keep changing the value of their cookie with different names and then refreshing clear_done_items.php to delete each file.

Link to comment
Share on other sites

Yes you are right. Never do this on a production site. I am just learning JS & php and did this as an exercise

following "The Book of JavaScript, 2nd Edition: A Practical Guide to Interactive Web Pages". I was trying

to add on to what author had left out which was a way to clear the todo list's completed items.

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...