Barbarah
Barbarah

Reputation: 85

Passing data variables from PHP to jquery ui dialog

I have this bit of php code:

    <?php
$posts = new Posts();

foreach($posts->getPosts() as $post){ ?>
    <div class="post">
        <h3><a class="post-link" data-post-id="<?php echo $post['id']; ?>" href="javascript:void(0)"><?php echo $post['title']; ?></a></h3>
    </div>

<?php } ?>

<div id="insert-answer" title="Add new idea to post">
<form id="myForm" action="insertidea.php" method="post">
    <fieldset>
        <p><label for="idea">Your idea:</label>
            <input type="text" name="idea" class="idea"</p>
        <p><label for="pic">Have a pic? Paste its URL here! (optional)</label>
            <input type="text" name="pic" class="pic"></p>
        <input type="hidden"class="author" name="author" value="<?php echo $_SESSION['google_data']['id']; ?>" />
        <input type="hidden"class="forpost" name="forpost" value="<?php echo $post['id']; ?>" />
    </fieldset>
</form>

And I want to pass the post id data variable to a jquery ui dialog:

    $( "#insert-answer" ).dialog({
    autoOpen: false,
    modal:true,
    buttons: {
        "Add idea": function() {
            var
                forpost = $(this).data("post-id"), // HOW CAN I GET THIS???
                author = $(".author").val(),
                idea = $(".idea").val(),
                pic = $(".pic").val();

            $.post('insertidea.php',{
                forpost: forpost, author: author, idea: idea, pic: pic, action:'joined'
            });//End Post

            $(".forpost").val('');
            $(".author").val('');
            $(".idea").val('');
            $(".pic").val('');

            $(this).dialog("close");
        },

        Cancel: function() {
            $( this ).dialog( "close" );
        }
    }
});

$( ".post-link" ).click(function() {
    $( "#insert-answer" ).dialog( "open" );
});

Problem is I'm mostly a php girl and I don't quite grasp the million JS examples I've checked already. What I'm trying to do is use the post id as a variable that comes from php that I can in turn use in my dialog to send to another php script via post.

Upvotes: 0

Views: 852

Answers (1)

Jan
Jan

Reputation: 43169

You could change your post-link function as follows:

$( ".post-link" ).on('click', function() {
    var postid = $(this).data("post-id");
    var answer = $("#insert-answer");
    $(answer).data('post-id', postid);
    $(answer).dialog( "open" );
});

And then grab in in the "Add idea": function() { part with:

var forpost = $("#insert-answer").data("post-id"),
    author = $(".author").val(),
    idea = $(".idea").val(),
    pic = $(".pic").val();

So what you are doing is basically saving the current post-id to #insert-answer and getting it from there in your dialog. Is this what you were after?

UPDATED CODE: @charlietfl is absolutely right, var post-id is not correct, I have edited the name of the variable.

Upvotes: 1

Related Questions