Corey
Corey

Reputation: 327

Passing session variable through AJAX to PHP file

My goal is to pass $userId variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users.

Im having a bit of trouble getting the variable data to go to the ajax statement. What am i doing wrong?

<?php

session_start();

if(isset($_SESSION['userid'])) {

    $userId = mysql_real_escape_string($_SESSION['userid']);

    echo $userId;

    echo ' (irrelevant code)...

        //button that loads form via ajax...
        <a href="#" class="small button radius expand" onClick="showAdd(\'$userId\');return false;">Add URL</a>

    (irrelevant code)... ';
}

AJAX code:

function showAdd(str)   {
     $('#response').html('Processing Request. Please wait a moment...');
       var userId = str;
       alert (userId);

       $.ajax({
           type: "POST",
           url: "addUrlForm.php",   
           data: "userId=" + str,                                        
           success: function(msg)   {
               $('#response').empty();
               $('#content01').html(msg).show();
           },
           error: function () {
               alert('error');
        }   
    });
};

EDIT: I took your suggestion (thank-you) and it some-what helped. Now the alert is returning "$userId" variable as a string. How do I make it be recognised as a variable containing the session data, not as a string? I tried "showAdd($userId)" but console is telling me $userId is not defined?.

Upvotes: 3

Views: 7172

Answers (2)

Cyclonecode
Cyclonecode

Reputation: 30121

Since you're sending the userId as a parameter to the showAdd() function you should change your code to:

function showAdd(str) {
   var userId = str;
   // ...
}

or simply rename the parameter to userId:

function showAdd(userId) {
    // use userId here
]

To make you above code send the correct userId and not the string $userId to the function you should wrap your output string in double quotes or output it directly:

echo '<a href="#" class="small button radius expand" onClick="showAdd('.$userId.');return false;">Add URL</a>';

or:

echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";

Upvotes: 1

Joke_Sense10
Joke_Sense10

Reputation: 5412

I do not understand why would you use $(this) when the userid is already present and is passed as function parameter.

Change this:

var userId = $(this).attr('userId');

To:

var userId = str;

Upvotes: 0

Related Questions