HandiworkNYC.com
HandiworkNYC.com

Reputation: 11114

AJAX Post response data does not write to DOM with $('input').val()

I have some bizarre behavior going on with this AJAX response.

On the PHP page, I have:

echo $items = $_POST["items"];

And my ajax function:

  $j('.share-pdf').on('click', function () {
    var $body = $('body');
    $body.addClass('loading');

    var pullsheetName = "pullsheet-backbone",
        pullsheet = localStorage.getItem(pullsheetName);

    $.ajax({
        cache: false,
        data: {
            items: pullsheet
        },
        url: '/create-pdf?store=true',
        type: 'POST',
        success: function (data) {
            alert(data);
            $body.removeClass('loading');
            $('#share-url input').val(data).select();
            $('#share-url').addClass('shared')
        }
    });
    return false;
});

While alert(data) alerts the data that has been posted, nothing appears in the input, as $('#share-url input').val(data).select(); is supposed to do.

What am I doing wrong here and why isn't val() writing the data correctly to the specified input?

Upvotes: 0

Views: 327

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34217

Try a little colon:

$('#share-url:input').val(data).select();

Your

$('#share-url input').val(data).select();

means: in jQuery find inputs inside of such as:

 $('#share-url').find('input').val(data).select();

Which is an ancestor/descendant form of a selector re: $('div span') - find spans in divs

Upvotes: 1

forivall
forivall

Reputation: 9913

I suspect that you'll need to use the following instead:

$('#share-url input').val(function(){ 
    return data[$(this).attr('name')]; 
}).select();

This is assuming that data is a javascript object that contains the data, rather than just a string of your data. My assumption might be wrong. However, without further information, it's hard to figure out where the problem is.

Upvotes: 0

Related Questions