bɪˈɡɪnə
bɪˈɡɪnə

Reputation: 1085

How to pass multiple variables through Ajax?

Below is a ajax code for a comment box which calls php code on another page that inserts comment into comments table. This code works well but it was just a test. Now I want to add userto, userfrom, postid along with comment into comments table For which I will need to pass variables of userto, userfrom etc from index.php to addcomment.php. Can I pass them through this ajax code to addcomments.php?

index.php

<script type="text/javascript">
$(function() {
    $(".comment_button").click(function() {

        var test = $("#content").val();
        var dataString = 'content=' + test;

        if (test == '') {
            alert("Please Enter Some Text");
        } else {
            $("#flash").show();
            $("#flash").fadeIn(400).html('<img src="ajax-loader.gif" align="absmiddle"> <span class="loading">Loading Comment...</span>');

            $.ajax({
                type: "POST",
                url: "addcomment.php",
                data: dataString,
                cache: false,
                success: function(html) {
                    $(".db").after(html);
                    document.getElementById('content').value = '';
                    document.getElementById('content').focus();
                    $("#flash").hide();
                }
            });
        }
        return false;
    });
});
</script>

addcomment.php

if(isset($_POST['content'])) {
  $comment=strip_tags($_POST['content']);
  $com = $db->prepare("INSERT INTO comments (comment) VALUES (:comment)");
  $com->execute(array(':comment'=>$comment)); 
}

Upvotes: 1

Views: 1220

Answers (1)

cor
cor

Reputation: 3383

Your dataString variable can be a javascript object:

{ "data1" : "value1", "data2": "value2" }

Upvotes: 4

Related Questions