I'm currently trying to make a ajax comment function work once a user clicks "open comments".
Currently I'm getting data back from my php script and the status of the ajax call is "200 OK" so it definetely works but I'm just unable to get the correct value for the current comment which has been clicked on in order to post it to the php script.
What I'm asking is how do I get the value of the ".posted_comment_id" class and then how do I load the data which is returned into the ".commentView" class?
jQuery/AJAX:
$(".closedComment").click(function(){
var $this = $(this);
$this.hide().siblings('.openComment').show();
$this.siblings().next(".commentBox").slideToggle();
$.ajax({
type: "POST",
url: "http://example.dev/comments/get_timeline_comments",
data: {post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").val()},
dataType: "text",
cache:false,
success:
function(data){
$this.closest(".commentView").load(data);
}
});
return false;
});
HTML:
<div class="interactContainer">
<div class="closedComment" style="display: none;">
open comments
</div>
<div class="openComment" style="display: block;">
close comments
</div>
<div class="commentBox floatLeft" style="display: block;">
<form action="http://example.com/comments/post_comment" method="post" accept-charset="utf-8">
<textarea name="comment" class="inputField"></textarea>
<input type="hidden" name="post" value="13">
<input type="hidden" name="from" value="5">
<input type="hidden" name="to" value="3">
<input type="submit" name="submit" class="submitButton">
</form>
<div class="commentView"></div>
<div class="posted_comment_id" style="display:none;">13</div>
</div>
</div>
Replace .val by .html or .text. This will return the innerHTML of the element.
data: {
post_id: $this.siblings().next(".commentBox").find(".posted_comment_id").text()
}
You might need to convert the string to an integer to make it work.
If the query selector fails, this selector might do the job instead:
$this.parent().find(".posted_comment_id")
To add the returned data on your webpage, use the success handler. Here's an example of how it's done:
success: function(json) {
// Parse your data here. I don't know what you get back, I assume JSON
var data = JSON.parse(json),
content = data.whatever_you_want_to_print;
// Assuming your selector works, you put in in the element using .html
$this.closest(".commentView").html(content);
}
});
You probably want to do something like:
$(this).parents('.interactContainer').find(".posted_comment_id").text()
Related
On submit of class post_alternate_category_name I need to make value of input element alternate_category empty and I need to set the text of label .ermsg as saving... The code which I have written is not working:
<form method="POST" class="form-horizontal post_alternate_category_name">
<div class="control-group">
<label class="control-label">Alternate name</label>
<div class="controls">
<input class="m-wrap large alternate_category" name="alternate_category" type="text" value="">
<button type="submit" class="btn blue">Add</button>
<label class="ermsg" style="color: red"></label>
<input type="hidden" name="category_id" value="1">
</div>
<input type="hidden" name="_token" value="Jl3DOrLd0clH5cv17I5JQumqFtJzV8uNjblIZGu3">
</div>
</form>
$('.post_alternate_category_name').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "someurl",
data: "somedata",
beforeSend:function() {
$(this).children('.control-group').children('.controls').children('.ermsg').val('Saving');
$(this).find('.ermsg').html("");
},
success: function(response) {
$(this).children('.control-group').children('.controls').children('input[name="alternate_category"]').val('');
}
});
});
You can use
.find() function to get all children inside element.
jQuery find
Instead of using multiple ".children()" methods, you can reset and update values directly. See code below. Place it anywhere you like.
$('.post_alternate_category_name').on('submit', function(e) {
e.preventDefault();
$('input[name=alternate_category').val('');
$('label.ermsg').text(''Saving...);
)};
a) I need to make value of input element "alternate_category" empty.
$('input[name="alternate_category"]').val('');
b) I need to set the text of label ".ermsg" as "saving.."
$('.ermsg').html("saving..");
I have a lot of buttons, each opens its form . How do I get the input value of form opened at the moment, and post it on my server, like post("/addOrders", valueOfinputs)?
https://jsfiddle.net/ave6uvez/21/
<div class="rows">
<div class="row">
<button class="open">Buy</button>
<form id="myform" action="/index" method="post">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="namee" name ="name" >
</div>
<div class="form-group">
<label for="exampleInputPassword1">Phone</label>
<input type="phone" name = "phone" >
</div>
<button class="ave" >Close</button>
<INPUT type="submit" id = "submit" class = "close" value="Submit">
<!---- <button id="submit" class="close"></button>-->
</form>
</div>
</div>
try this,
$("#submit").click(function(e){
$.post("/addOrders",$("#myForm").serialize());
return null;
})
.serialize() will put all form elements data into the request
Also you need to give different id for different Forms submit button and you have to do the above code for each submit button
Hope this works for you.
This is a simple reference:
// this is the id of the forms, set the form ids accordingly.
$("#idForm").submit(function(e) {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").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.
});
I am searching a table for specific values based on the user input which queries the database for the LIKE condition. This works perfectly but I have to manually scroll to the buttom of the page to see my filtered table. I really want to redirect the user to the div of the table underneath the page. This is the form with the search box:
<form method="post">
<div class="col-lg-6 pull-right" style="margin-right:130px; width:30%;">
<div class="input-group">
<input required type="text" class="form-control" name="search" placeholder="Search Alerts for Today...">
<span class="input-group-btn">
<button class="btn btn-default" name="searchnow" type="submit" value="Submit">Go!</button>
</span>
</div>
</div>
</form>
This code below then checks to see if the button is clicked and then sets the variable that populates the table to equals the current search result from the database.
var searchIP = "";
if (Request.Form["searchnow"] != null & IsPost)
{
searchIP = Request.Form["search"];
alertForTheDay = dbConnection.searchDashboardTable(searchIP);
// Response.Redirect("Dashboard.cshtml#search");
}
Using Response.Redirect refreshes the table back to its original state. Commenting out the Response redirect as shown above allows the filter to be possible but I have to manually scroll down the page. I want this to redirect to the id of the div in that redirect. Please what can I do?
I guess you are doing a complete server round trip. From my point of view this is unnecessary.
I would suggest to do this via AJAX.
Change the HTML like this to call an AJAX operation on your button click:
<form method="post">
<div class="col-lg-6 pull-right" style="margin-right:130px; width:30%;">
<div class="input-group">
<input required type="text" class="form-control" name="search" id="search" placeholder="Search Alerts for Today...">
<span class="input-group-btn">
<button class="btn btn-default" name="searchnow" id="theButton">Go!</button>
</span>
</div>
</div>
</form>
Handle the button click and link to your anchor on success. (Assuming that the anchor to your table is present. In your case something like Dashboard.cshtml#contact)
$.fn.gotoAnchor = function(anchor) {
location.href = this.selector;
}
$(document).ready(function() {
// Add the page method call as an onclick handler for the div.
$("#theButton").click(function() {
$.ajax({
type: "POST",
url: "<YOUR URL>",
data: { search: $('#search').val() },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
// If everything is successful link to your anchor tag
$('#search').gotoAnchor();
}
});
});
});
I've a question about the method to make a ajax search request.
My form, the ajax call and the query is working, but i don't know, what's the best way to return the results.
I want to 'update' a existing table. What's the best and cleanest method to do this?
I don't want to recreate the whole table. But should i use JSON object or directly return the result with the html code.
Thanks for helping! I would appreciate it, when you also send example codes for your solution.
Greez Thandor
this code is for auto complete search
<script type="text/javascript">
function autocompelete(value)
{
$.ajax({
method: "POST",
url: "autocomplete.php",
data: { id: value }
})
.done(function( msg ) {
$('#autocomplete').html(msg);
$('#autocomplete').show();
});
}
</script>
html
<div id="search-bar">
<form action="youpage.php" method="POST">
<input type="submit" name="search" class="search-btn" value="" />
<input type="text" name="brand" autocomplete="off" onkeyup="autocompelete(this.value)" id="search" class="search-field" placeholder="Model Number, Brand, Company ..." />
</form>
<div style="display:none" id="autocomplete"></div>
</div>
sorry for the dumb question but I can't seem to get this going and I figured I best give you more info than not enough -
I have a form that I am running inside a loop in php like this:
<form name="primaryTagForm'.$post->ID.'" id="primaryTagForm'.$post->ID.'" method="POST" enctype="multipart/form-data" >
<fieldset class="tags">
<label for="post_tags'.$post->ID.'">Tags:</label>
<input type="text" value="" tabindex="35" name="postTags'.$post->ID.'" id="postTags'.$post->ID.'" />
</fieldset>
<fieldset>
<input type="hidden" name="submitted" id="submitted" value="true" />
'.wp_nonce_field( 'post_nonce', 'post_nonce_field' ).'
<button class="button" type="submit">Tag</button>
</fieldset>
</form>
I have tried adding my ajax under that form (Still within the loop so I can grab the post_id) and in my console it my tag-ajax.php file is posted just fine. Here is my weak attempt at that based on this: Save data through ajax jQuery post with form submit and other like questions.
<script>
jQuery(document).ready(function($) {
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "'.get_stylesheet_directory_uri().'/tags-ajax.php",
data: "primaryTagForm'.$post->ID.'",
success: function(data){
//alert("---"+data);
alert("Tags have been updated successfully.");
}
});
});
});
</script>
And lastly here is what is in my tags-ajax.php file -
if(isset($_POST['submitted']) && isset($_POST['post_nonce_field']) && wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) {
wp_set_object_terms( $post->ID, explode( ',', $_POST['postTags'.$post->ID] ), 'product_tag', true );
echo'Success!';
}
So when I try running this a couple of things happen by looking in the console, if I hit submit on one of the forms then all them forms on that page post to tags-ajax.php (Im sure it is because I am doing this in a loop but not sure how else to do it and bring in post->ID on tags-ajax.php)
The second, most important thing is that nothing actually saves, I click the "Tag" but (submit) and I get those success alerts (for each post unfortunately) but when I click through those the tags are not actually saved.
My question: How do I get the data to actually save with the ajax/php and how can I have that post refresh without reloading the page so the user sees they actually were added?
Latest Update: After making the serialize edits mentioned below I submit my form and check the console and see the post method is getting a 500 internal server error.. Im thinking if my problem is coming from because I have the form and an inline script with the ajax running in a loop? So there are technically 20 posts/forms/inline scripts on a page and when you submit one, all of them submit which may be causing the 500 internal error?
The data: option in ajax should be
data: $("#primaryTagForm'.$post->ID.'").serialize(),
Use serialize
You have to change
data: "primaryTagForm'.$post->ID.'",
to
data: $("#primaryTagForm'.$post->ID.'").serialize(),
Simplify your markup. You dont have to use id attributes everywhere. Just include a hidenn tag in your form with the value of $post->id. Also echo the ajax url at the form's acton attribute.
So the html should be similar to this:
<form method="POST" action="' . get_stylesheet_directory_uri() .'/tags-ajax.php" >
<input type='hidden" name="id" value="'.$post->ID.'">
<fieldset class="tags">
<label>Tags:</label>
<input type="text" value="" tabindex="35" name="tags" />
</fieldset>
<fieldset>
<input type="hidden" name="submitted" id="submitted" value="true" />
'.wp_nonce_field( 'post_nonce', 'post_nonce_field' ).'
<button class="button" type="submit">Tag</button>
</fieldset>
</form>
Then you can use a script like this:
jQuery(document).ready(function($) {
$(".button").click(function(e) {
e.preventDefault();
var $target = $(e.target),
$form = $target.closest('form');
$.ajax({
type: "POST",
url: $form.prop('action'),
data: $form.serialize(),
success: function(data){
//alert("---"+data);
alert("Tags have been updated successfully.");
}
});
});
});