1

I pretty much just want to pass a json object over to another function when it happens (for example a click event gets called).

$(document).on('click', '.some_link', function() {
var something = "something";

    $.get('/someDirectory/someScript.php', {
        'some_var': something
    }}.done(function(data) {
        var json = jQuery.parseJSON(data);
        $('#json-item-container').val(json);
    });
});

$('.hidden-input').click(function() {
    var json = $('#json-item-container').val();
    //Do something with json
});
dtgee
  • 1,272
  • 2
  • 15
  • 30
  • It's possible, but because ajax is async, it could cause issues ? – adeneo Aug 22 '13 at 20:08
  • Is it so you want to get the json when you click on the hidden input, but don't want to call the ajax before the clicking. – Krasimir Aug 22 '13 at 20:13
  • Actually, I just want to to call the ajax whenever .some_link is clicked, but I want to save the json from there in case .hidden-input is clicked. When .hidden-input is clicked, I will need the json object. .some_link will pretty much open up a modal, and .hidden-input is a clickable field inside the modal. – dtgee Aug 22 '13 at 20:18
  • My answer should work. I would also disable the `.hidden-input` button, or prevent the modal from showing until after the ajax request has completed, though. –  Aug 22 '13 at 20:27

2 Answers2

2

Use jQuery's data method, instead of val, to store arbitrary data associated with an element.

bdukes
  • 152,002
  • 23
  • 148
  • 175
1

Store the json data in the global scope:

var json; // json var defined in global scope

$(document).on('click', '.some_link', function() {
var something = "something";

    $.get('/someDirectory/someScript.php', {
        'some_var': something
    }}.done(function(data) {
        json = data;
    });
});

$('.hidden-input').click(function() {
    console.log('Ohai! Im the json object: ' + JSON.stringify(json));
});
  • I think that get will parse result if it find JSON by default. – jcubic Aug 22 '13 at 20:15
  • 1
    Better yet, use a anonymous scoping function (see http://stackoverflow.com/a/5786899/664577) to avoid polluting global scope. Just wrap the code (including `var json`) with `(function() { /* YOUR CODE HERE */ })();`, `json` will be visible for both functions, but will not be global. – Anthony Accioly Aug 22 '13 at 20:29