Reputation: 1847
I've been trying to send a variable from php to AJAX, and it used to work before, and suddenly it does not. I've been trying to understand why for the past few hours, reading about passing variable with no luck.
For some reason i cannot get the textarea into my ajax and post it to the rest of the application. It gives me an empty alert, but var name = $("input[name='name']").val();
alerts correctly.
here is the html
<script type="text/javascript" src="http://example.com/_data/js/addreply.js"></script>
<input type="hidden" name="hiddenid" value="6" />
<div id="writeCommTxt" >
<textarea name="text" cols="90" rows="12" class="txtclassic" ></textarea>
<div id="writeCommCapt">
<div id="writeCommCaptSub"><input type="submit" name="postcomm" value="Submit" class="subclassic" /></div>
</div>
</div>
And here is the AJAX in a separate file.
$(document).ready(function (){
$(".subclassic").click(function (){
var id = $("input[name='hiddenid']").val();
var name = $("input[name='name']").val();
var text = $(".txtclassic").val(); //i also tried to add textarea['text'].val() with no success.
var capt = $("input[name='captcha']").val();
alert(text); //it alerts an empty window.
if (name != "" && text != ""){
$.ajax({
type: 'POST',
url: "/article/add_reply/" + id,
data: {
rename: name,
retxt: text,
recapt: capt
},
success: function (data){
...
}
});
}
});
});
Upvotes: 1
Views: 592
Reputation: 42736
Why not just use jQuery's serialize() function?
Put all the input controls in between a <form>
tag give it an id and then call the serialize function on that element
<form id="myform">
<input type="hidden" name="hiddenid" value="6" />
<div id="writeCommTxt" >
<textarea name="text" cols="90" rows="12" class="txtclassic" ></textarea>
<div id="writeCommCapt">
<div id="writeCommCaptSub"><input type="submit" name="postcomm" value="Submit" class="subclassic" /></div>
</div>
</form>
Then in your script have
var myFormData = jQuery("#myform").serialize();
$.ajax({
type: 'POST',
url: "/article/add_reply/" + id,
data: myFormData,
success: function (data){
...
}
});
As for the the original problem, you might have other elements with the class "txtclassic", and if so it will grab the first one it finds and try to get its value (if its not a input control it will return nothing)
Upvotes: 0
Reputation: 601
first add id attribute to textarea as follows.
<textarea name="text1" id="text1" cols="90" rows="12" class="txtclassic" ></textarea>
now access value like this
var text = $('#text1').val();;
Upvotes: 0
Reputation: 12693
Why don't you use id? In your case, I guess it is:
$('textarea[name="text"]').val();
Upvotes: 1