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
Related
I am wondering how to get 2 actions in PHP from a single Button.
Attached here is an screenshot of the page:
I have the following code:
For the Submit button
<form method='POST'>
<div class="form-group">
<input type="text" name="s_amount" style='width:20%;' required>
<input type="submit" class="btn btn-primary" name="submit" value="Submit" />
</div>
</form>
<?php
$s_amount = $_POST['s_amount'];
echo $s_amount;
?>
AND for the Submit Code button
<button id="submitcode"type="button" class="btn btn-default">Submit Code</button>
<pre><code id="output">.../...</code></pre>
When the Submit code is pressed, this executes the following script
<script>
$(document).ready(function(){
$("#submitcode").on("click", function(){
ocpu.seturl("https://public.opencpu.org/ocpu/library/base/R")
//arguments
var mysnippet = new ocpu.Snippet("V_CT="+$('[name="CT"]:radio:checked').val()+"\r V_TP="+$('[name="LENGTH"]:radio:checked').val()+$('#input2').val());
//perform the request
var req = ocpu.call("identity", {
"x" : mysnippet
}, function(session){
session.getObject(function(data) {
//data is the object returned by the R function
$("#output").text(data);
});
});
})
});
</script>
What I would like to have is a single button, which not only gets the value next to the first submit button (here 12, see attached pciture) but also executes the script.
Many thanks !
try giving id to form tag and on click on submitcode button call the form using its id.
for ex.
<form method='POST'>
function(session){
session.getObject(function(data) {
//data is the object returned by the R function
$("#output").text(data);
// using form id call the form
$("#formdata").submit(); // it will simply submit the form.
});
});
<form method="post" id="formdata"> <!--assign id to form tag-->
</form>
Could finally do it very easily using js.
<input type="text" id="VTP" value="0">
and get the value in the javascript form
document.getElementById("VTP").value
# nikhil borikar: Thanks but it did not work
My task is triggering php script from HTML form, which is updating JSON file from which HTML is generated. Here is how i am trying to do that.
HTML Form:
<form method="post">
<label for="board">Board to update:</label><br>
<input type="text" id="board" name="board"><br><br>
<input type="button" value="Submit" onclick="update()">
</form>
Javascript:
function update() {
var board=$('#board').val();
$.post('update.php',{boardname:board}, function() {
alert("update successfull");
})
}
and PHP:
<?php
$q=$_POST['boardname'];
echo ($q);
shell_exec('curl https://cyberland.club/' . $q . '/?num=1000 > posts.json');
?>
There is no error after clicking button, but website is not updating. Can you tell me why is that? What am i doing wrong? I was using this tutorial https://www.youtube.com/watch?v=jVAaxkbmCts
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.");
}
});
});
});
I am using javascript validation for my input box from javascript-coder and it works fine on my non-ajax pages but when I use ajax to POST inputs the script runs through without stopping even if validation fails. I tried an example from here but when I tried the suggestion the validation didn't work at all. In my ajax script I can get everything to work with jquery validation by simply putting this in before posting data:
var frm = $(this).closest('form');
if($(frm).valid()){
But I really want to stick with this validation library so I am hoping someone in the community more familiar javascript and maybe even this validation library can help me find an equivalent because I haven't been able to find anything in all the documentation that allows you to test if validation failed or not before moving my ajax script forward.
My form:
<form method="post" name="send_message_frm" id="send_message_frm">
<div style="margin-top:20px;"></div>
<fieldset>
<div class="clear"></div>
<div style="margin-top:20px;"></div>
<label>Product Group Name:</label>
<input name="desc" class="text-input medium3-input required" type="text" id="desc" value="">
<div style="color:red;" id='send_message_frm_desc_errorloc' ></div>
<div style="margin-top:20px;"></div>
</fieldset>
<input name="user" class="text-input medium3-input" type="hidden" id="user" value="<?php echo $myid ; ?>">
<div style="margin-top:20px;"></div>
<input type="submit" id="send-message" name="submit" value="Send" class='button' />
<div style="margin-top:20px;"></div>
</form>
<script type="text/javascript">
var frmvalidator = new Validator("send_message_frm");
frmvalidator.EnableOnPageErrorDisplay();
frmvalidator.EnableMsgsTogether();
frmvalidator.addValidation("desc","alnum","Only numbers and letters are allowed");
frmvalidator.addValidation("desc","req","Please enter a description");
</script>
My Ajax script:
<script type="text/javascript">
$(document).ready(function(){
//Validate form....what can I put here to test if validation is completed properly????
//onclick handler send message btn
$("#send-message").click(function(){
$(this).closest('form').submit(function(){
return false;
});
var frm = $(this).closest('form');
$("#ajax-loading").show();
var data = $(frm).serialize();
$(frm).find('textarea,select,input').attr('disabled', 'disabled');
$.post(
"productgroup_add.php",
data,
function(data){
$("#ajax-loading").hide();
$(frm).find('textarea,select,input').removeAttr('disabled');
$("#send_message_frm").prepend(data);
}
);
}
);
});
</script>
After reviewing the validation script, I discovered (as suspected) that it attaches the validation method to the form's OnSubmit event handler, which sounds about right...
this.formobj.onsubmit = form_submit_handler;
But... it also attaches itself to the form object:
this.formobj.validatorobj = this;
which has a method that you can call to validate your form:
if (!this.runAddnlValidations())
To run the validations, it looks like you can just do something like:
if(!document.forms[0].validatorobj.runAddnlValidations()) return;
I'm trying to modify the post url of a form depending on the name of the file being posted. Any suggestions very much appreciated. Here is the code (which doesn't work):
<script type="text/javascript">
function submit_form()
{
document.uploadform.action = "upload?name=" + document.uploadform.codejar.value;
return 1;
}
</script>
<form name="uploadform" method="post" onsubmit="return submit_form();">
<table>
<tr><td>Select your jar to upload</td></tr>
<tr><td> <input type="file" name="codejar" style="width: 400"></td></tr>
<tr><td><input type="submit" name="send" value="Upload jar"></td></tr>
</table>
</form>
"I'm trying to get it to do a plain http post of the file, to a url with the filename as a parameter"
Just do this then:
function submit_form() {
document.uploadform.action = document.uploadform.codejar.value;
document.uploadform.submit();
}
...and think about changing your "send" button to
<button type="button" onclick='submit_form()'>Upload jar</button>
Why would you need to do that?
You should be able to access that once the form is POSTed.
Also, browsers can send different things when getting the value from file inputs.