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.");
}
});
});
});
Related
I just started learning ajax and its really great and time saving i agree.
But i got stuck at this point sending form data without page reload.
Below is my html code.
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<p class="form-message"></p>
</form>
Below is my Ajax script
<script>
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
var action = 'another_test';
var agreed = $("#agreed").val();
var submit = $("#form-submit").val();
$(".form-message").load("test3.php", {
test: agreed,
submit: submit,
action: action
});
});
});
</script>
Below is my php code
<?php
if (isset($_POST['action'])) {
if ($_POST['action'] == 'another_test') {
$test = $_POST["test"];
$errorEmpty = false;
if (!empty($test)) {
echo "<p>Click the checkbox pls</p>";
$errorEmpty = true;
}
else {
echo "<p>Checkbox clicked</p>";
}
} else {
echo "Error.. cant submit";
}
}
?>
<script>
var errorEmpty = "<?php echo $errorEmpty ?>";
</script>
The php file is on another page called test3.php
This particular code works if it was an input text but doesn't work for a checkbox.
Please help me so i can learn well.
Thanks in advance.
.load() (as per the documentation) performs a GET request, not a POST, but your PHP is (as shown by the $_POST references) expecting a POST request - and it usually makes sense to submit form data using POST.
So you'd be better to use $.post() - this will send a POST request. Then you can handle the response and load it into your "form-message" element in the "done" callback triggered by that request.
N.B. You could also make the code shorter by putting the "action" variable as a hidden field in the form, and then simply serialize the form in one command instead of pulling each value out separately.
Example:
HTML:
<form id="form4" method="post">
<input type="checkbox" name="test" id="agreed" value="check">
<br>
<br>
<input type="submit" id="form-submit" name="submit" value="Send">
<input type="hidden" action="another_test"/>
<p class="form-message"></p>
</form>
JavaScript
$(document).ready(function() {
$("#form4").submit(function(event) {
event.preventDefault();
$.post(
"test3.php",
$(this).serialize()
).done(function(data) {
$(".form-message").html(data);
});
});
});
Documentation:
jQuery Load
jQuery Post
jQuery Serialize
I have a form that is executed every time a submit button is clicked. When the submit button is clicked, a modal is shown and the modal is populated with JSON data. The application /addresschecker checks against the addresses posted and sends me an error message if I get a code return number of 2003. If not I select the return data via JSON using jQuery's $.each
The application works but when I close the modal, refill out the form and click submit, the form does not make a new call to /addresschecker I looked in my network tab of chrome and it seems to be using the old data. I am thinking that I need to force a new Ajax call everytime a user clicks on the submit button or clear the cache somehow. Not sure why I'm seeing old data
<form id="Validate">
<input class="form-control" id="adr1" name="address1" type="text" placeholder="Address 1" />
<input class="form-control" id="adr2" name="address1" type="text" placeholder="Address 1" />
<button type="submit" >Submit</button>
</form>
<div class="modal hide">
<!-- JSON Data returned -->
<div id="Message_1"></div>
<div id="Message_2"></div>
<div id="error_message"></div>
</div>
// My main form code
submitHandler: function(form) {
$.ajax({
url: '/addresschecker',
type: 'post',
cache: false,
dataType: 'json',
data: $('form#Validate').serialize(),
success: handleData
});
function handleData(data) {
var mesgcheck = data.message;
if (data.code == '2003') {
$("#error_messag").html(mesgcheck);
} else {
// Display Modal
$(".modal").removeClass("hide");
$.each(data, function(i, suggest) {
$(".adr1").val(suggest.address1);
$(".adr2").val(suggest.address2);
});
}
}
}
Let ajax handle your request.
Use this:
<input type="button" value="submit">
Instead of type submit.
I have the following code for an HTML form:
<form id="idForm" method="post" enctype="multipart/form-data">
<input type="text" name="first" value="Bob" />
<input type="text" name="middle" value="James" />
<input type="text" name="last" value="Smith" />
<input name="image" type="file" />
<input type="submit" name="submit" value="Submit" />
</form>
and the following Javascript code on the same page where the form is located. Also, this code is written below the form code:
$("#idForm").submit(function() {
alert("hi");
var url = "submit.php";
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(),
success: function(data) {
alert(data);
}
});
return false;
});
And here is the PHP code that I'm using to see if the form data is being posted:
if (isset($_FILES['image'])) {
$image = $_FILES['image'];
echo $image;
}
if (isset($_POST['first'])) {
$name = $_POST['first'];
echo $name;
}
With the above code, it seems as though the attached file is not being sent to the PHP file. Only the values are being sent, since they are echoed when I inspected the element using Google Chrome dev tool.
I want to be able to post both text value and files to the PHP file for processing.
Why am I getting this problem? How do I fix this?
Also, as part of the solution, I want to prevent the page from being refreshed when the submit button is clicked.
Thanks much!
Unfortunately input[type='file'] cannot be submitted by .serialize(), you have to manipulate by formData.
You will find a very good formData example in here
I have the following code in my HTML file (this is oversimplfied to save space and time):
<form role="form" name="popupForm" id="popupForm">
<input type="hidden" name="season1" id="season1" value="fall" />
<input type="hidden" name="season2" id="season2" value="fall" />
<input type="hidden" name="season3" id="season3" value="fall" />
<input type="hidden" name="ITEMCOUNT" id="ITEMCOUNT" value="3" />
</form>
<button type="button" class="btn btn-primary" id="orderSave">Save Changes</button>
I then have a JQuery routine that IS getting called:
$("#orderSave").click(function () {
$.post("ProductPopupLightboxSave.aspx", $('form#popupForm').serialize(), function (data) {
$("#productModal").modal("hide");
});
});
In the file ProductPopupLightboxSave.aspx I have the following code:
If IsNumeric(Request("ITEMCOUNT")) Then intItemCount = CInt(Request("ITEMCOUNT"))
The value in intItemCount is used in a For...Next loop to interate through the and grab the individual elements "season1", "season2", and "season3" (obviously the numbers vary depending upon the product) and saves the info to the database. The problem is that Request("ITEMCOUNT") is nothing when it gets here. In fact, it doesn't seem to serialize my form data at all.
UPDATE: I have used the name element and that didn't fix anything. What I have noticed is that this is a .NET application and it has a RADSCRIPTMANAGER tag in the master page. It has an open form tag but not a closing one (it was done by another developer so I don't know the reason for that). It appears that this is getting in the way because I just changed the FORM tag to be a DIV tag with the exact same ID and with that change only the form data serializes.
What am I doing wrong? I have even done an alert on the value of the #ITEMCOUNT and it is always correct. Thanks for your help!
I've tested in my computer using your form and it worked, however I had a strange behavior in IE 10. So I changed my code and it worked, find it below, using .ajax not .post
<form role="form" id="popupForm">
<input type="hidden" id="season1" name="season1" value="fall" />
<input type="hidden" id="season2" name="season2" value="fall" />
<input type="hidden" id="season3" name="season3" value="fall" />
<input type="hidden" id="ITEMCOUNT" name="ITEMCOUNT" value="3" />
</form>
Changed the button just in case, it worked with the other button too.
<button type="button" class="btn btn-primary" id="Button1"> More Save</button>
And set an .ajax post
$("#Button1").click(function() {
$.ajax({
url: 'Default.aspx',
type: 'POST',
data: $('form#popupForm').serialize(),
success: function(data) {
alert('success');
},
error: function() {
alert("error");
}
});
});
For testing purposes I've added alerts on success and error, I'm posting to a default.aspx webpage and I get results properly.
I hope it helps.
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()