Ansh
Ansh

Reputation: 261

How to pass javascript variable in .html() to php

I am adding a text area on click of a particular div. It has <form> with textarea. I want to send the jquery variable to my php page when this submit button is pressed. How can this be achievable. I am confused alot with this . Being new to jquery dizzes me for now. Here is my code,

`

<script type="text/javascript">
$(document).ready(function(){
 $('.click_notes').on('click',function(){
 var tid = $(this).data('question-id'); 
 $(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'><textarea cols ='50' class='span10' name='notes' rows='6'></textarea><br><input class='btn btn-primary' name= 'submit_notes' type='submit' value='Add Notes'><input type='hidden' name='submitValue' value='"+tid+"' /></form><br></div>");
 });
});
</script>`

Upvotes: 1

Views: 57

Answers (2)

Naveen K
Naveen K

Reputation: 889

Your code works fine in the fiddle I created here -> https://jsfiddle.net/xe2Lhkpc/

use the name of the inputs as key of $_POST array to get their values.

if(isset($_POST['submitValue'])) { $qid = $_POST['submitValue']; } 

if(isset($_POST['notes'])) { $notes = $_POST['notes']; }

Upvotes: 1

Sadeghbayan
Sadeghbayan

Reputation: 1163

You should send your data after form submitted, something like this :

    $(".comment_form form").submit(function(e) {


    var form = $(this);
    var url = form.attr('action');

    $.ajax({
           type: "POST",
           url: url,
           data: form.serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data); // show response from the php script.
           }
         });

    e.preventDefault(); // avoid to execute the actual submit of the form.
});

you can assign event after insert your form.

// handling with the promise

$(this).closest('ul').find('.demo').html("<div class='comment_form'><form action='submit.php' method='post'></form><br></div>").promise().done(function () {
       // your ajax call
  });;

Upvotes: 1

Related Questions