简体   繁体   中英

Sending data from php to javascript not working

I am trying to send a variable "userID" from php to javascript. But when i print the "data" it is showing the entire javascript document.

Below is the code

index.php:

$userID =10;
if(isset($_POST['userID'])){
    switch (($_POST['userID'])){
        case  'getUSerID':
            echo $userID;       
            break;
   }    
}

Javascript code:

$(document).ready(function(){
    var userID = getUserID("getUserID");

function getUserID(){
 $.ajax({
        url : 'index.php',
        type: 'POST',
        data : userID,
        success: function(data, textStatus, jqXHR)
        {   

            return data;
        },
        error: function (jqXHR, textStatus, errorThrown)
        {
            event.preventDefault();
            alert( 'Failed to toogle.');
        }
      });
     }
}

can anyone please tell me what's wrong in my code.

Thanks in advance

in your php you are showing a variable which doesn't have a value you should assign a value to $userID like this

$userID = $_POST['userID'];

The second problem is that in your javascript you made this

var userID = getUserID("getUserID");

which will return every time an undefined value to userID it's because getUserID doesn't return anything. it has a function inside which is $.ajax and doesn't return anything too because it's asynchronous

The third problem is that inside $.ajax you are sending the value of userID which will be undefined everytime

please explain more what data you want to send , and what you want to do with the result so that we can help you.

Try this on your js (assuming that you pass the values of userID to $userID ):

    <script>
      var userID = <?php 
      if(isset($_POST['userID'])){
        switch (($_POST['userID'])){
            case  'getUSerID': echo json_encode($userID);       
                               break;
            }    
      }
      ?>;
    </script>

Using json_encode() requires:

  • PHP 5.2.0 or greater
  • $userID encoded as UTF-8 (or US-ASCII, of course)

Since UTF-8 supports full Unicode, it should be safe to convert on the fly.

Well if you need to get data from your php file, no need to post a variable to get it changed as I understand from your code... all you need to do is to get it asynchronously using jQuery like this

var userID;
function getUserID()
{
    $.get( "test.php", function( data ) {
        userID = data;
    });
}

This one is asynchronous, which means , you call the function and once it gets the result it assign it to userID, and then you can use the userID variable

The second solution is to use a synchronous ajax function like this one

   function getUserID()
   {
        if (window.XMLHttpRequest)
            AJAX=new XMLHttpRequest(); 
        else
            AJAX=new ActiveXObject("Microsoft.XMLHTTP");
        if (AJAX)
        {
            AJAX.open("GET", "test.php", false);
            AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
            AJAX.send();
            return AJAX.responseText;                              
        } 
        else
            return null;
   }
   var userID = getUserID();

This one can allow you to call get your result once you call it becuase it has a return statement ... it may slow your application if you try to send huge date.

and don't forget to put on your .php file echo $userID no need to test isset($_POST... because you just need to get data from php you don't send as I understand from your question

last thing if you need to pass an array or an object from php to javascript you have to json encode and json decode ... just tell me and I'll help you with that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM