0

How I can get variable value from jsonp response and use it in other script function? In first function I have one value that I am getting from jsonp response. I am assigning this value to variable ( var userId ) in first function.

How I can get userId value and use it in second script function???

<script>
$(document).on('pageinit', '#login', function () {
$(document).on('click', '#submit', function () { 
    if ($('#username').val().length > 0 && $('#password').val().length > 0) {
        console.log($('#check-user').serialize());
        $.ajax({
            url: 'http://localhost/check.php',
            data: $('#check-user').serialize(),
            type: 'POST',
            beforeSend: function () {
            $.mobile.showPageLoadingMsg(true); 
            },
            complete: function () {
            $.mobile.hidePageLoadingMsg(); 
            },
            success: function (result, status, err) {
            if(result.login){
                    $.mobile.changePage( "#output", { transition: "slideup", changeHash: false });
var userID = //// HERE I NEED TO GET USER ID FROM  jsonp response!!!!

            });
            }
            else{
                alert("An error occurred: " + status + "nError: " + err.status);
            }
            },
            error: function (request, error) {
            }
        });
    } else {
        alert('Please fill all necessary fields');
    }
    event.preventDefault(); 
});

var output = $('#output');
var userid = ////HERE I NEED TO SET USER ID!!!!!!!!!!!!
$.ajax({
    url: 'http://localhost/data.php?user='+userid,
    dataType: 'jsonp',
    jsonp: 'jsoncallback',
    timeout: 5000,
    success: function(data, status){
        $.each(data, function(i,item){ 
            var landmark = '<h1>'+item.name+'</h1>'
            + '<p>'+item.lat+'<br>'
            + item.long+'</p>';

            output.append(landmark);
        });
    },
    error: function(){
       output.text('There was an error loading the data.');
    }
});
});
</script>  
user3432056
  • 325
  • 1
  • 5
  • 14

1 Answers1

1

you can use the global variable assignment feature of js

Declare your variable outside of any function.

<script>
var userId;
function foo(){
  //..
}
</script>

OR Use the window object to assign the global variable from inside a function

<script>
function foo() {
    window.userID = ...;
}
</script>

more info available here

Community
  • 1
  • 1
vinay
  • 1,366
  • 1
  • 13
  • 23