www.webdeveloper.com
Results 1 to 7 of 7

Thread: Need pass JS vars to PHP without using <form> <input> <button> w/ AJAX POST method.

  1. #1
    Join Date
    Nov 2010
    Location
    Rio de Janeiro / Brazil.
    Posts
    4

    Need pass JS vars to PHP without using <form> <input> <button> w/ AJAX POST method.

    Hello.

    I'm a newbie in web aplications development and I've been studing in the W3Schools tutorials ( and other places in web ).

    I'm using HTML with JavaScript, PHP and MySQL in a Xampp Lite environment.

    I want to record in a MySQL table the date and time the visitor entered and left tha page.

    I have the two informations stored in string javascript variables.

    But although I've found the AJAX, I just can't make it works.

    I don't need a form or input HTML tag.

    When the visitor call the page, I get the date and time. And when he leave the page ( onunload event ) I get the other date and time and, at this moment I want to pass this JavaScript variable to the PHP script.

    Both codes are ok and have been tested separated. The rows are inserted in the MySQL table correctly when I initialize them inside the PHP code.

    And in browser-side, with JavaScript, I can see that they ( the variables ) are Ok by displaying it.

    Thank everybody!!

    ClŠudio Baptista / Rio de Janeiro / Brasil.

  2. #2
    Join Date
    Nov 2010
    Posts
    21

    Something like this might work...

    Code:
    window.onunload = getInfo;
    
    function createRequest() {
      try {
        request = new XMLHttpRequest();
      } catch (tryMS) {
        try {
          request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (otherMS) {
          try {
            request = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (failed) {
            request = null;
          }
        }
      }
      return request;
    }
    
    function getInfo(visitorEnter, visitorExit) {
      request = createRequest();
      if (request == null) {
        alert("Unable to create request");
        return;
      }
      var url= "getInfo.php?visitorEnter=" + escape(visitorEnter) + "&visitorExit=" + escape(visitorExit);
      request.open("GET", url, true);
      request.onreadystatechange = checkRequest;
      request.send(null);
    }
    
    function checkRequest() {
      if (request.readyState == 4) {
        if (request.status == 200) {
         alert("success! Or is it?");
        }
      }
    }
    Last edited by andypants; 11-24-2010 at 05:11 PM.

  3. #3
    Join Date
    Nov 2010
    Location
    Rio de Janeiro / Brazil.
    Posts
    4

    Tanks.

    Well, Andy.

    As I told, I'm a newbie. (and don't speak english very well - forgive me some writing erros).

    Thank you very much. But I'm not making it work.

    I'd like to use the POST method, insted GET.

    Something like this:

    My JavaScript variable is visitorEnter.

    How can I type the send method?

    request.send(visitorEnter) Woud it work? is it correct?

    And in server-side (PHP)?

    How can a retrive the value of the visitorEnter variable?

    $visitorEnter = $_REQUEST["visitorEnter"]; So I could use it in my SQL INSERT command??

    Pardon for boring you and thanks a lot!!

    ClŠudio Baptista / Rio de Janeiro / Brasil.

  4. #4
    Join Date
    Nov 2010
    Posts
    21

    And the answer is...

    Code:
    // JavaScript Document
    window.onload = initSite;
    window.onclose = exitSite;
    var visitorEnter = "";
    
    function initSite() {
    	
    	var date = new Date();
    	var y = date.getFullYear();
    	var m = date.getMonth();
    	var d = date.getDay();	
    	var h = date.getHours();
    	var i = date.getMinutes();
    	var s = date.getSeconds();
    	
    	// make a timestamp
    	var timestamp = new Date(Date.UTC(y, m, d, h, i, s));
    	visitorEnter = timestamp.getTime()/1000;
    	//alert(visitorEnter);
    }
    
    function exitSite() {
    	var url = "php.php";
    	var requestData = "visitorEnter=" + visitorEnter;
    	
    	var request = createRequest();
    	if (request == null) {
    		alert("Unable to create request");
    		return;
    	}		
    	request.onreadystatechange = checkRequest;
    	request.open("POST", url, true);
    	request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    	request.send(requestData);
    }
    
    function checkRequest() {
    	if (request.readyState == 4) {
    		if (request.status == 200) {			
    			var response = request.responseText;
    			//alert(response);
    		}
    	}
    }
    
    function createRequest() {
      try {
        request = new XMLHttpRequest();
      } catch (tryMS) {
        try {
          request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (otherMS) {
          try {
            request = new ActiveXObject("Microsoft.XMLHTTP");
          } catch (failed) {
            request = null;
          }
        }
      }	
      return request;
    }
    PHP Code:
      //** you must first connect to your database **//
      
      // store timestamp as getdate() array
      
    $dArray getdate($_REQUEST['visitorEnter']);
      
      
    // SQL DATETIME() YYYY-MM-DD HH:MM:SS
      
    $visitorEnter date("Y-m-d H:i:s"mktime($dArray[hours],$dArray[minutes],$dArray[seconds],$dArray[mon],$dArray[mday],$dArray[year])); 
      
      
    $inssql "INSERT INTO put_your_data_base_here(id, enterTime, exitTime) VALUES(NULL, '" $visitorEnter "', NOW())";

    mysql_query($inssql);
    //echo $visitorEnter; 
    This probably isn't the best way to do this but let me know if it helps you out. Oh and, this was actually really interesting, not boring at all mang.
    Last edited by andypants; 11-24-2010 at 11:28 PM.

  5. #5
    Join Date
    Jan 2011
    Posts
    2
    Hi. Testing.

  6. #6
    Join Date
    Jan 2011
    Posts
    2

    been trying to move javascript variables to php variables for a VERY LONG TIME =(

    Hi, I wish to resurrect this topic because I am encountering some problem even after looking through your examples . I hope someone out there can help me with my coding in AJAX. I am trying to send two javascript variables to PHP variables using AJAX. Please have a look at my code, thank you in advance!

    In my javascript, I am using YUI dual slider, so when I end sliding the mouse I want to engage these functions such that....

    javascript code
    <code>
    var psavestate = function(){ // THESE ARE CURRENTLY SAVED VALUES, WE CAN NOW USE THESE VALUES FOR A PHP FUNCTION FOR QUERYING
    var url = "/Applications/MAMP/htdocs/trunk/application/modules/cne/admin/view/scripts/index/index.phtml",
    savemin = pconvert(pslider.minVal), // pconvert is some function
    savemax = pconvert(pslider.maxVal),
    requestMinData = "savemin=" + savemin,
    requestMaxData = "savemax=" + savemax;

    var request = createRequest();
    if (request == null) {
    alert("Unable to create request, please update your browser to use this feature.");
    return;
    }

    request.onreadystatechange = checkRequest();
    request.open("POST", url, true);
    request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    request.send(requestMinData);
    request.send(requestMaxData);
    }

    pslider.subscribe('slideEnd', psavestate); // Slider ends, start method psavestate
    })

    // Browser Support Code
    function createRequest(){
    var ajaxRequest; // The variable that makes Ajax possible!

    try{
    // Opera 8.0+, Firefox, Safari
    ajaxRequest = new XMLHttpRequest();
    } catch (e){
    // Internet Explorer Browsers
    try{
    ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {
    try{
    ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
    } catch (e){
    // Something went wrong
    alert("Your browser broke!");
    return false;
    }
    }
    }
    return ajaxRequest;
    }

    function checkRequest() {
    if (request.readyState == 4) {
    if (request.status == 200) {
    var response = request.responseText;
    //alert(response);
    }
    }
    }
    </code>

    As for my php code, I wrote the following to test to see if this worked... and so far it hasn't been working quite well for me....

    <code>
    <?php $v = $_REQUEST['savemin'];
    echo $v; ?>
    </code>

    Please take a look, thank you in advance again!

  7. #7
    Join Date
    Nov 2010
    Location
    Rio de Janeiro / Brazil.
    Posts
    4
    Well, my friend, I'm a newbie in webdevelopping and don't speak english very well, too.

    But lets try.
    See my PHP code (in blue) in the bottn of this message....

    The only difference from your code and the things I do in my code is that I use only one send command. The red part of the code above....See that I put all the variables in a unique string called "par&#226;metro"...

    par&#226;metro = "dataHoradeAcesso=" + dataHoradeAcesso // Par&#226;metro a ser passado na abertura da
    par&#226;metro = par&#226;metro + "&" + "dataHoradeSa&#237;da=" + dataHoradeSa&#237;da
    // requisi&#231;&#227;o HTTP (XMLHttpRequest / AJAX)

    // Trata a requisi&#231;&#227;o HTTP
    requisi&#231;&#227;o = false
    limite = 0
    while ( !requisi&#231;&#227;o ) //&& limite < 3000 ) // tenta 3.000 vezes antes de interagir com o usu&#225;rio
    {
    try
    {
    requisi&#231;&#227;o = new XMLHttpRequest();
    }
    catch (tryMS)
    {
    try {
    requisi&#231;&#227;o = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (otherMS)
    {
    try {
    requisi&#231;&#227;o = new ActiveXObject("Microsoft.XMLHTTP");
    }
    catch (failed)
    {
    requisi&#231;&#227;o = false;
    }
    }
    }
    limite ++
    }

    if (requisi&#231;&#227;o == null) { // Se n&#227;o foi capaz de efetuar a requisi&#231;&#227;o HTTP, retorna sem
    // fazer nada. &#201; indiferente para o usu&#225;rio.
    // alert("A requisi&#231;&#227;o HTTP falhou!!");
    return;
    }

    requisi&#231;&#227;o.open("POST", "escala.php", true);
    requisi&#231;&#227;o.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    requisi&#231;&#227;o.setRequestHeader("Content-length", par&#226;metro.length);
    requisi&#231;&#227;o.setRequestHeader("Connection", "close");
    requisi&#231;&#227;o.send(par&#226;metro);


    Then, in PHP I use this:

    $dataHoradeAcesso = $_POST["dataHoradeAcesso"];
    $dataHoradeSa&#237;da = $_POST["dataHoradeSa&#237;da"];
    .
    .
    .
    mysql_query("INSERT INTO escala020acessos (dataHoradeAcesso, dataHoradeSa&#237;da, TabelaConsultada, AnoM&#234;sMenor, AnoM&#234;sMaior)
    VALUES ($dataHoradeAcesso, $dataHoradeSa&#237;da, '9876', '&#193;&#201;&#205;&#211;&#218;&#199;', '&#225;&#233;&#237;&#243;&#250;&#231;') ");


    It's working here and I think it shoud work ther too.

    Good luck!!

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles