0

I am giving the user a possibility to comment, when he comments I would like that comment to be saved in my database. I will take care of the saving to database part, but I need help with passing the text input from JavaScript to PHP. I would like to simply echo the 'imeBoxa' and 'komentar' variables. My problem is inside the ajax function.

HTML within index.php:

<button class="pointer comment">Komentiraj</button>

<script type="text/x-jquery-tmpl" id="fieldTemplate2"/>
<p><div class="imeBoxa"><b>{{imeBoxa}}</b>:</div> {{komentar}}</p>
<hr/>
</script>

JavaScript:

$("#leftColumn").on("click", ".comment",function()
    {
        var imeBoxa = prompt("Komentar za vijest:","");
        var komentar = prompt("Komentar","");

        if(komentar != null && imeBoxa != null)
        {
            var fieldTemplate2 = $("#fieldTemplate2").text();

            fieldTemplate2 = fieldTemplate2.replace("{{imeBoxa}}", imeBoxa);
            fieldTemplate2 = fieldTemplate2.replace("{{komentar}}", komentar);

            $.ajax
            ({
                type: 'post',
                url: 'index.php',
                data:
                {
                    imeBoxa,
                    komentar
                },
                success: function( data ) 
                {
                    console.log( data );
                }
            })

            var jField = $(fieldTemplate2);

            $(".komentari").append(jField);
        }
    });

1 Answer 1

1

You have a syntax error in your code. AJAX call should look like this:

$.ajax({
    type: 'post',
    url: 'index.php',
    data: {
        imeBoxa: imeBoxa,
        komentar: komentar
    },
    success: function (data) {
        console.log(data);
    }
});

Pay attention how you construct data object to be passed to server. In this example it will pass two POST parameters: imeBoxa and komentar.

Sign up to request clarification or add additional context in comments.

5 Comments

while I was wondering and wondering, if it would be possible to send the parameters like in the question above, you were faster :-) Perfect answer. One voteup from me.
I would recommend, to run the fieldTemplate2 things and .append inside of the success:function, so one can make sure, that the comment appears only when successfully stored in db.
After doing this i try to echo the variable with this if(isset($_POST['imeBoxa'])) { $uid = $_POST['imeBoxa']; } echo $uid; If I use the button and add a comment should it then automatically echo what I wrote @dfsq
Server should respond with $uid in your case.
It says undefined variable $uid before and after adding a comment, and my comment is shown on the page, javascript does its work.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.