I am having a table td which contains a textarea and a button and I want to send the value of textarea on button click via AJAX however there is a problem selecting the closest textarea to the button.
JavaScript
$(document).ready(function () {
$(document).on("click", ".addR", function () {
paperID = $(this).attr("paperID");
commentID = $(this).attr("commentID");
text = $(this).closest("textarea").val();
$.ajax({
data: {
paperID: paperID,
commentID: commentID,
text: text
},
type: 'POST',
url: 'add_rebuttal.php',
success: function (response) {
alert(response);
window.location.href = window.location.href;
}
});
});
});
PHP:
while ($row = mysql_fetch_assoc($comments)) {
echo "<tr><td>{$row['text']}</td>";
?>
<td><br /><textarea class="reText" rows='5' name='reText' id='reText' style='width:98%;' type='text'></textarea>
<button commentID="<?php echo $row['comment_id'] ?>" paperID="<?php echo $paper_id ?>" class="addR" type="button" name="addR" id="addR">send rebuttal</button></td></tr> <?
}
The problem is $(this).closest("textarea").val(); return undefined, so how I can solve this problem?
closest() returns the closest ancestor. Your textarea is not an ancestor of your button, it's a previous sibling. Instead, try:
text = $("textarea", $(this).parent()).val();
To get the text of a textarea you have to use text() instead of val(). As pointed out by Scotty, the textarea you want is not an ancestor so don't use closest().
Related
Hello I am really new to AJAX PHP and JQuery so any suggestion is really apprecciated.
I have an HTML page with a form, in this form I have 3 radio buttons with 3 values. My objective is to print some HTML depeding on this values.
For example if I select the radio button 2 (value=2) so -->
echo <input type="text">
echo <input type="text">
I managed to print the value in a empty div under the buttons but I don't know how to generate code with the $_POST variable (I tried to iclude the action page but it didn't work)
HTML:
<div class="hide">
<input type="radio" name="cat_2" value="1">One
<input type="radio" name="cat_2" value="2">Two
<input type="radio" name="cat_2" value="3">Three
</div>
<div id="response"></div>
<?php include 'gen.php'; ?> //my failed test
JQuery:
<script>
$(document).ready(function () {
$('.hide input[type="radio"]').click(function(){
var value= $(this).val();
$.ajax({
url: "ajax_page.php",
type: 'post',
data: {ajax: 1, value: value},
success: function (response) {
$('#response').text(value);
}
});
});
});
</script>
ajax_page.php just to test the value:
<?php
if ($_SERVER['REQUEST_METHOD'] == "POST") {
echo $_POST['value'];
} else {
echo "Nothing to Show";
}
?>
I don't know if I was enough clear, any idea would be really helpful I don't even know what to search for :)
gen.php is run before the webpage is sent to the browser. You won't be able to access any return variables or information from the ajax call because the gen.php code will already have run. gen.php will need to have all the information BEFORE it runs/the browser loads the page. If you need code to run AFTER the browser loads the page, you'll have to do that on your ajax_page.php.
Just a hint for your ajax_page. You should avoid using the supervariables directly and filter the input first (to prevent malicious or accidental problems). Something like this:
if($value = filter_input(INPUT_POST, "value", FILTER_VALIDATE_INT)){
echo $value;
} else {
echo "Nothing to Show";
}
You should capture the error from the ajax call as well and log it to the console (or present it to the user). Here is how you can log it to the console.
$(document).ready(function () {
$('.hide input[type="radio"]').click(function(){
var value= $(this).val();
$.ajax({
url: "ajax_page.php",
type: 'post',
data: {ajax: 1, value: value},
success: function (response) {
// Loop to output repeated HTML
var output = "";
for (i = 0; i < response; i++) {
// Put the HTML in here for example you could create the output:
output = output + "<p>test</p>";
}
// and then display it
$('#response').html(output);
},
error: function (response){
console.log(response)
}
});
});
});
I have this form being outputted from a PHP while loop :
echo '<div id="postCont" class="postCont'.$pid.'" style="block;">
<div id="clLink">
<a id="clLink" href="'.$plink.'" target="_blank"" title="'.$ptitle.'">'.$ptitle.'</a>
</div>
<div id="clDate">Posted on '.$pdate.'</div>
<div id="clDesc">'.$pdesc.'</div>
<form method="post" class="ibadForm">
<input type="hidden" name="id" value="'.$pid.'">
<input type="hidden" name="hiddenBad" value="yes">
<input type="image" src="../img/bad.png" name="subBad" value="Bad" class="bad">
</form>
</div>';
I am trying to remove the individual .postCont when the ibadForm is clicked with jquery.
$(".ibadForm").submit(function(e) {
var url = "add_form.php";
var id = <?php echo $pid?>;
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data)
{
$('.postCont' + id).hide();
}
});
e.preventDefault();
});
It submits the form to add_form.php fine but doesn't hide the postCont. If I remove the id from the class then it hides all post Cont's. Can anyone tell me where I am going wrong?
You could use closest() to get the parent div then hide it using hide() method like :
$(".ibadForm").submit(function(e) {
var url = "add_form.php";
var id = <?php echo $pid?>;
var _this = $(this);
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function(data)
{
_this.closest('.postCont').hide();
}
});
e.preventDefault();
});
NOTE : You should store the $(this) object that refer to the clicked form in some variable (_this in my example) then use it inside the success callback since $(this) inside callback doesn't refer no more to the form, e.g :
_this.closest('.postCont').hide();
Hope this helps.
Basically I have a list of files composed from a foreach loop that all have the same code except for the name, which carries the file_id for each file. My problem is that when I added an on-click pop-up event I lose the ability to fetch the current $(".flag") attribute name. Is there a way that I can pass it along the way so I can use it in the end?
PHP: (the user sees the link which they can click...remember there are several of these as a result from the foreach loop. I'm showing one for example)
echo "<td><a href='#' class='flag' name='$files[id]' >Click Here</a> ( $files[nums] )</td>";
jQuery: (on-click this will happen)
$(".flag").live('click', function() {
$(".pop").show("slow");
return false;
});
HTML: this div will popup
<div class="pop">
<form method="post" id="new_folder" >
<p><label for="folder">Reason for Reporting?</label><textarea id="report_reason" name="report_reason" maxlenght="100" style="resize:none" cols="30" rows="5">Please limit your response to 100 characters.</textarea></p>
<p><input type="submit" value="Submit" id="message_submit"/> or <a class="close" href="/">Cancel</a></p>
</form>
</div>
jQuery: on submit I need to send the current $files['id'] and textarea value via ajax. The textarea sends the correct data, but the $(".flag") instead of being the id of the selected link it is the id of the first fetched id from the foreach loop
$("#message_submit").on("click", function(e){
var fileID = $(".flag").attr("name");
var text = $("#report_reason").val();
$(".pop").hide("slow");
$.ajax({
url: '<?php echo base_url().'home/report_file';?>',
type: 'POST',
data: { val: fileID, val2: text },
dataType: 'json',
success: function(output_string){
$(".success").text("You have flagged this file!!").show().css({"color" : "green", "margin-top" : "10px"});
$(".success").fadeOut(10000);
}
});
return false;
});
You can save the .flag link being clicked and later use it.
var flagClicked;
$(".flag").live('click', function() {
$(".pop").show("slow");
flagClicked = $(this);
return false;
});
$("#message_submit").on("click", function(e){
var fileID = flagClicked.attr("name");
....
I have buttons and divs and in each part I have them with the same ID I want to get the ID of button and use it for refreshing the div html.how should I write the * section?
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
*********I HAVE PROBLEM HERE**************
$('how to get the id of the div from var id of button above?').html(html);
}
});
});
});
Div:
Downloaded:<div id="<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
Button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
If I get class It will update the whole divs I want to update just the div realted to the button
You cannot have the same id on both the button and the div, id values must be unique in a document.
What I'd probably do is put the div's id on the button as a data-divid attribute (all attributes with the prefix data- are valid on all elements as of HTML5, and harmless in earlier versions of HTML), like this:
<input type="button" value="Download" class="button" data-divid="<?php echo $id; ?>" name="dl">
Then change
var id=$(this).attr('id');
to
var id=$(this).attr('data-divid');
...and then use that id var in your success callback (as the callback is a closure created within the context where id is defined, and so the callback has access to id).
Here's a simple example: Live copy | source
HTML:
<div id="div1">This is div1</div>
<div id="div2">This is div2</div>
<div>
<input type="button" data-divid="div1" value="Update div1">
<input type="button" data-divid="div2" value="Update div2">
</div>
JavaScript:
jQuery(function($) {
$("input[type=button]").click(function() {
var id = $(this).attr("data-divid");
// I'll use setTimeout to emulate doing an ajax call
setTimeout(function() {
// This is your 'success' function
$("#" + id).html("Updated at " + new Date());
}, 10);
return false;
});
});
Use the id but prefix them then build the name up...
<div id="div_<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
button:
<input type = "button" value="Download" class="button" id="<?php echo $id; ?>" name="dl">
Then in you're code you have the id used in the buttons already (and also it will be div_), so you can then in you're 'success' just do:
$("#div_"+id).html(html);
change your html to this:
Downloaded:<div id="<?php echo $id; ?>" class="downloaded" ><?php echo $downloadcount;?></div>
then do something like:
var element_id = $(".downloaded").prop("id");
if(element_id = this.id){
$("#"+element_id).html(/* ... */);
}
$(function() {
$(".button").click(function(){
var id=$(this).attr('id');
var dataString = 'id='+ id ;
$.ajax({
type: "POST",
url: "download_number.php",
data: dataString,
cache: false,
success: function(html)
{
$('.count-' + id).html(html); // for class
}
});
});
});
<div class="count-<?php echo $id; ?>" ><?php echo $downloadcount;?></div>
First of all avoid using same IDS.
Then you can use CSS selectors:
$('div.class') //div
$('input[type="button"].youridclass')
You cannot use the id attribute for that purpose, the id cannot be a number (valid html) and thereby id's needs to be unique. Use the data attrib instead.
Try something like:
$('.button').attr('id');
to get the id of the button, then to change it:
$('.button').attr('id',''); //delete previous id if existing
$('.button').attr('id','yourNewId'); //set new id
then to use the new id:
$("#yourNewId").doSomething();
First and foremost, ids should be unique, you'll run into problems, particularly when using jQuery, if you have elements with the same id.
Without seeing your markup it's hard to give you a working example. But you can get the id of the div which corresponds to the clicked button by traversing the DOM.
Example markup:
<div id="example-div">
<input type="button" value="Example" />
</div>
jquery
$('input[type="button"]').click(function() {
console.log($(this).parent('div').prop('id'));
});
// outputs 'example-div'
for your reference check the below link for the various ways that you can use to select the dom elements given the parent element.
jsperf.com/jquery-selectors-context/2
I have a form with a textarea and a button. To show the textarea value in another tab of the same window on a button click I used this:
<input type="button" name="preview" id="inline_submit_a" value="PREVIEW" />
<script>
$('#inline_submit_a').click(function(evt) {
var msg = document.getElementById('message').value;
var myLineBreak = msg.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '<br />');
jQuery.ajax({
type: 'POST',
url: '/someajax.php',
data: "msg="+myLineBreak,
success: function(data) {
window.open("<?=SITEURL?>includes/templates/preview/template1/postoffer_preview.php?offer="+data,'_blank');
return false;
}
});
});
</script>
I'm sending through query string,
How to send the value to another page through POST and not the query string(GET) since it takes only upto limited characters.
Also, How to get the html content (With breaks),
I used this: var myLineBreak = msg.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '<br />');
But breaks for some text.
Also, window.open("<?=SITEURL?>test.php?msg="+data,'_blank'); this works good in firefox, but in Chrome, it opens a new window,
Can someone pls help me on this.. am I going in the right direction?
Thanks
Something like this, using form.target and empty window.open (code not tested) :
<form name="myform" action="postoffer_preview.php" target="myNewWin" method=post">
<input type="button" name="preview" id="inline_submit_a" value="PREVIEW" />
</form>
<script>
var open_post_window = function ()
{
window.open("","myNewWin","width=500,height=300,toolbar=0");
document.myform.submit();
}
$('#inline_submit_a').click(function(evt) {
var msg = document.getElementById('message').value;
var myLineBreak = msg.replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '<br />');
jQuery.ajax({
type: 'POST',
url: '/someajax.php',
data: "msg="+myLineBreak,
success: function(data) {
open_post_window();
return false;
}
});
});
</script>
Add a little setTimeout on document.myform.submit() may be necessary.