Paul
Paul

Reputation: 3368

How to get variable from one Ajax function to work in another Ajax function

I am attempting use a variable that I create through data being sent from php in one ajax function in a another ajax function. I'm not sure what I am doing wrong. I tried creating making this a global variable by doing var nameOutput and also tried var nameOutput = 0. You will see alert code in the second ajax function. This is outputting nothing. If I remove the .val(), I receive object Object.

The code in question is in the second Ajax function: data: { 'nameOutput': nameOutput.val() }

Does anyone have any idea what I have to do?

var nameOutput;

$('#shuffle').on('click', function() {
    $.ajax({
        url: 'php/name-selection.php',
        type: 'POST',
        success: function(data) {
            nameOutput = $('#name-output').html(data);
            $(nameOutput).html();
        },
        complete:function(){
            $('#send-info').slideDown(1500);
        },
        error: function(xhr, textStatus, errorThrown) {
            alert(textStatus + '|' + errorThrown);
        }
    });
});
//var datastring1 = $('#name-output').serialize();
$('.check').click(function() {
    alert(nameOutput.val());
    $.ajax({
        url: 'php/name-selection-send.php',
        type: 'POST',
        data: {
            'nameOutput': nameOutput.val()
        }
        ,
        success: function(data) {
            if (data == 'Error!') {
                alert('Unable to  submit inquiry!');
                alert(data);
            } else {
                $('#success-sent').html(data);
            }
        },
        complete:function(){

        },
        error: function(xhr, textStatus, errorThrown) {
            alert(textStatus + '|' + errorThrown);
        }
    });

Upvotes: 0

Views: 43

Answers (1)

Ali Sheikhpour
Ali Sheikhpour

Reputation: 11121

if you can set inner html of nameOutput using .html('blah') , so you can extract the html again using nameOutput.html() not nameOutput.val();

however I think you have to define the element like this to be a HTML element:

var nameOutput=$('<div></div>');

also in first ajax function,set the html using this:

nameOutput.html(data);

and if there is a real element with ID name-output , and you want the result to be visible, do both of these:

nameOutput.html(data);
$('#name-output').html(data);

Upvotes: 2

Related Questions