I have a form within a div that I want to submit via another page which will run the query and then return to the first page again all within the div which is in a larger page.
I have put the following javascript at the top of the page:
<script name='addactivity'>
function submitForm() {
$.ajax({type:'POST', url: 'activity_new.php', data:$('#newactivity').serialize(), success: function(response) {
$('#newactivity').find('.activities').html(response);
}});
return false;
}
</script>
and have placed the form in the div as follows:
<form id='newactivity' method="post">
<b>Activity Number:</b><input type=text name='activitynumber' class='textborder'>
<b>Title:</b><input type=text name='activitytitle' class='textborder'>
<b>Time (mins):</b> <input type=text name='activitytime' class='textborder'>
<b>Leaders:</b> <input type=text name='leaders' class='textborder'><br>
<b>Description:</b><textarea name='activitydescription' class='textareaborder'></textarea>
<input type='submit' value='Submit' id='submit'></form>
<div id="activities"></div>
The submit button does not appear to do anything. It should post the values to activity_new.php which looks like:
<?php
session_start();
$input2=$_SESSION[ 'unitid' ];
$meetingid=$_POST['meetingid'];
$activitynumber=$_POST['activitynumber'];
$activitytitle=$_POST['activitytitle'];
$activitytime=$_POST['activitytime'];
$leaders=$_POST['leaders'];
$activitydescription=$_POST['activitydescription'];
include 'connect_db.php';
$q1c="INSERT into activities (meetingid, unitid, activitynumber, title, description, time, leaders) VALUES ('$meetingid', '$input2', '$activitytitle', '$activitydescription', '$activitytime', '$leaders')";
$r1c = mysqli_query($dbc,$q1c);
echo $meetingid;
echo $activitynumber;
echo $activitytitle;
//header("location:editmeeting.php?id=$input2");
?>
I currently have the javascript on the main page that contains the divs but have also tried it at the top of the page with the form in. I've also tried these two combinations with the onsubmit = "return submitForm();" as onclick = "return submitForm();" on the button itself.
as per your code when you click on button it will not fire onsubmit() event .
if you change button type to submit it will work as you have added return false to your function
<input type='submit' value='Submit'>
Or use below code .you can use button click event to submit form via ajax using jquery
HTML
<input type='button' value='Submit' id="submit">
Jquery
$(document).ready(function(){
$(document).on('click','#submit',function(){
$.ajax({type:'POST', url: 'activity_new.php', data:$('#newactivity').serialize(), success: function(response) {
$('#newactivity').find('.activities').html(response);
}});
});
});
NOTE : from below code in success function . there is no element named '.activities' in your form. make sure to use correct selector attribute.
$('#newactivity').find('.activities').html(response);
Simply change input type:
<input type='submit' value='Submit'>
^^^^^
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
Why my page reloads even I used ajax to it and it also disappears my input text after clicking the submit button. I already used show to solve it but it doesn't work.
<form method="POST" action="<?php $_SERVER['PHP_SELF'];?>">
<input type="text" name="name" id="name">
<span id="namenotif" style="color:red;"> <span>
<br>
<input type="text" name="price" id="price">
<span id="pricenotif" style="color:red;"> <span>
<br>
<input type="submit" name="submit" id="save"><br>
</form>
<script>
$(document).ready(function() {
$(document).on("click","#save",function(){
var name = $("#name").val();
var price = $("#price").val();
if(name==""){
$("#namenotif").html("Enter a name");
$("#name").show("fast");
$("#save").show("fast");
}
else if(price==""){
$("#pricenotif").html("Enter a price");
$("#price").show("fast");
$("#save").show("fast");
}else{
$.ajax({
url:"addproduct.php",
type:"POST",
data:{name:name,price:price},
success:function(data){
alert("Successful");
}
});
}
});
});
</script>
add return false to end of function, that handle click event
Two solutions:
Change the button type='submit' to type='button'
or ( and preferably )
Change the event listener to listen for the form's onSumbit event then call event.preventDefault or in jQuery, I think you just do return false in the callback.
The form is being submitted I think, because it is the default behavior of submit button to submit the form, no matter if you used ajax or not. so you can prevent the default behavior by simple adding a code in jquery. Modify the code like this:
$(document).on("click","#save",function(e){
e.preventDefault();
...............
Rest of the codes can remain same. so only prevent the default action, it should work.
Its because of type="submit"
Use
<input type="button" name="submit" id="save"><br>
Or
<a href="javascript:void(0) id="save">
or
jquery's preventDefault();
i've got this script that send the variable recordID with GET (and works OK)
<input type="hidden" id="suggest1_hidden" name="suggest1_hidden" value="">
<input name="suggest1" type="text" class="suggest_table {th : ['nome', 'email', 'tel', 'cell']}" id="suggest1" style="width:650px;" alt="Adm_ut_search.php" />
<span id="comando"><span class="button">Dettagli utente</span></span>
<script language="javascript">
$(document).ready(function()
{
$('#comando').click(function () {
var url="Adm_ut_view_details.php?recordID=" + $('#suggest1_hidden').val()
document.location.href = url
});
});
</script>
I need to send the variable with POST and i wrote this... but doest work
<form id="myForm" action="Adm_ut_view_details.php" method="post"/>
<input type="hidden" id="suggest1_hidden" name="suggest1_hidden" value="">
<input name="suggest1" type="text" class="suggest_table {th : ['nome', 'email', 'tel', 'cell']}" id="suggest1" style="width:650px;" alt="Adm_ut_search.php" />
<input name="recordID" type="hidden" id="userID" value="" />
<button type="submit" id="comando">Submit</button>
</form>
<script language="javascript">
$(function(){
$('#myForm').on('submit', function(e){
document.getElementById('userID').value=+ $('#suggest1_hidden').val()
$('#myForm').submit();
});
});
</script>
what i do wrong ?
There is nothing inherently different that you need to do with your form fields because you are sending a POST request vs. a GET request. Changing the form's action to POST is all you need to do as long as no JavaScript pre-submit processing is desired.
And, the hidden form field is going to be sent along with the other form fields anyway, so why bother concatenating it to the userID?
But, to your question and your code, you have a typo:
document.getElementById('userID').value =+ $('#suggest1_hidden').val()
Should be:
document.getElementById('userID').value += $('#suggest1_hidden').val()
Now, you have code that sets up your submit event handler, but you have no code that sets the value of the hidden form field. That needs to be done prior to the submit taking place.
Also, you need to prevent the form from submitting first, so that you can modify the form field value.
$(function(){
$('#myForm').on('submit', function(e){
e.preventDefault(); // Stop the submit
// YOU NEED TO MAKE SURE THAT THE HIDDEN FORM FIELD'S
// VALUE HAS BEEN SET BY THIS POINT.
document.getElementById('userID').value += $('#suggest1_hidden').val()
$('#myForm').submit(); // Then manually submit
});
I would like to create a form with multiple submit link buttons. I know it can be done by using and specifying the name of <button> or <input type="button"> something like this:
In HTML:
<form action="" method="get">
Other form elements here...
<button type="submit" name="activated">Activated</button>
<button type="submit" name="pending">Pending</button>
<button type="submit" name="suspended">Suspended</button>
</form>
In PHP:
<?php
if(isset($_GET["activated"])) {
Activated codes here...
}
elseif(isset($_GET["pending"])) {
Pending codes here...
}
elseif(isset($_GET["suspended"])) {
Suspended codes here...
}
?>
I want the submit buttons to be done by using link, not <button> or <input type="submit"> something like this:
Activated
Pending
Suspended
I heard that it can be done by using JavaScript or JQuery but I don't know how, anyone knows?
Update: What I want to happen is when I clicked the "Activated" link for example, I want only to process the logic under isset($_GET["activated"]).
The reason behind:
The reason why I want to have a submit link buttons instead of normal submit button tags is that, I want to use this bootstrap dropdown button style to change the status of user(s) on table:
and it is based on links, so that's why.
PS: Sorry for bad English, not my native language.
You could use data attributes on your anchors, then load that attribute into a hidden field to check in your PHP code.
<form action="" method="post">
Activated
Pending
Suspended
<input type="hidden" id="actionName" name="actionName" value="" />
</form>
$('.anchor-btn').click(function(e) {
e.preventDefault();
$('#actionName').val($(this).data('name'));
$('form').submit();
});
<?php
if($_POST['actionName'] == "activated") {
Activated code goes here
}
...etc.
?>
Yes you can submit the form using jquery just add a class to your buttons and add a click handler
$(document).ready(function() {
$( ".buttons_class" ).click(function() {
$( "#target_form" ).submit();
});
});
so your buttons will look like this
<button type="button" name="activated" class="buttons_class">Activated</button>
<button type="button" name="pending" class="buttons_class">Pending</button>
<button type="button" name="suspended" class="buttons_class">Suspended</button>
if using anchors
Activated
Pending
Suspended
And in javascript
$(document).ready(function() {
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
$("#target_form").attr("action", "yourphpfile.php?"+$(this).text()+"=true"); //This will send the text inside the anchor as a GET param.
$( "#target_form" ).submit();
});
});
However if I were you I would consider using POST instead of GET for this. and do something like this
$( ".buttons_class" ).click(function(e) {
e.preventDefault(); //This will stop the default anchor action
var paramName = $(this).text(); //get text inside anchor
$( "#target_form" ).submit(function(eventObj) {
$('<input />').attr('type', 'hidden')
.attr('name', paramName);
.attr('value', "something")
.appendTo('#form');
return true;
}); //Add hidden field
});
Change your isset to $_POST instead of $_GET, it will then use the name attributes.
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['test1'])) {
###
} else if ($_POST['test2']) {
###
}
}
<form method="post">
<input name="test1" type="submit" value="TEST 1" />
<input name="test2" type="submit" value="TEST 2" />
</form>
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.");
}
});
});
});