How to handle click event on Submit Button [closed] - php

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Here is my script for handling submit button click event
$('#subbtn').on("click",function(){
var stcode = $('.stcode11').val();
var sem = $('.sem11').val();
var doa = $('.doa11').val();
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: 'stcode='+stocde+'&sem='+sem+'&doa='+doa,
success: function(msg)
{
$('.atnresult').html(msg);
}
});
});
And here is the button code
<button id='subbtn' type='submit' class='button'> Change </button>
But it not working properly. Please help me to handle click event of submit button.

You should handle the submit event of form Then you can use event.preventDefault() to cancel the default action.
$('YourFormSelector').on("submit",function(event){
//Cancel default event
event.preventDefault();
//Rest of your code
});

First, the way you are doing the submit requires you using e.preventDefault(); to prevent your form from being submited via html.
Second, the way you pass the data is wrong/the way you would do for a GET operation. As you are trying to submit via POST, you need to create data like this:
data: {
stcode : stocde
sem : sem
doa : doa
}
Full code:
$('#subbtn').on("click",function(e)
{
e.preventDefault();
var stcode = $('.stcode11').val();
var sem = $('.sem11').val();
var doa = $('.doa11').val();
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: {
stcode : stocde
sem : sem
doa : doa
}
success: function(msg)
{
$('.atnresult').html(msg);
}
});
});

Try this:
$(document).on("click","#subbtn",function(e)
{
e.preventDefault();
var formData = new FormData();
formData.append( 'stcode', $('.stcode11').val());
formData.append( 'sem', $('.sem11').val());
formData.append( 'doa', $('.doa11').val());
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: formData,
success: function(msg)
{
$('.atnresult').html(msg);
}
});
});

replace this line
data: 'stcode='+stcde+'&sem='+sem+'&doa='+doa,
with
data: 'stcode='+stcode+'&sem='+sem+'&doa='+doa,
full code with preventdefault
$('#subbtn').on("click",function(e) {
var stcode = $('.stcode11').val();
var sem = $('.sem11').val();
var doa = $('.doa11').val();
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: 'stcode='+stcode+'&sem='+sem+'&doa='+doa,
success: function(msg)
{
$('.atnresult').html(msg);
}
});
e.preventDefault();
});

Related

Post variable before redirect?

I am currently building on a CMS. I want to send a page-id or site-id to the next page on redirect. I tried doing it using the jQuery POST function:
$(document).ready(function(){
$('.sender').on('click','a',function(){
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: { siteid:siteid },
success: function(response){
console.log('check');
},
error: function(){
console.log('error');
}
});
});
});
But because the request is sent at the same time as the redirect, it does not seems to work.
Because I am using the apache rewrite_engine to redirect stuff, I cannot use GET.
Apart from session_variables, what are my options?
I want to keep it safe, so I don't want much info to be visible/available!
To achieve this you need to wait for the AJAX request to complete before the page is redirected. Try this:
$(document).ready(function(){
$('.sender').on('click', 'a', function(e){
e.preventDefault(); // stop the default redirect
var url = $(this).attr('href');
var n = url.indexOf('#') + 1;
var siteid = url.substr(n, url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: {
siteid: siteid
},
success: function(response){
console.log('check');
window.location.assign(url); // redirect once the AJAX has successfully completed
},
error: function(){
console.log('error');
}
});
});
});
I'm not sure to clearly understand why you need but I think this can answer your problem.
If what you need is to transfert informations using a real POST method, just create an hidden form with method="POST" and fill it on click event.
<script type="text/javascript">
$(document).ready(function(){
$('.sender').on('click','a',function(event){
event.preventDefault();
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$('input[name="siteid"]').val(siteid);
$('#redirectForm').submit();
});
});
</script>
<form id="redirectForm" action="pages.php" method="POST">
<input type="hidden" name="siteid" value=""/>
</form>

read more button shows again after click

i have a readmore link that allows people to read more posts once it has been clicked, what i don't want is the button showing again and i also don't want the whole post to show again, i just want the remaining posts to add to the previous that the reader has read or being reading just as its done on facebook page when you click seemore link.
Thanks
$(function(){
$(".readMore").click(function(event){
event.preventDefault();
var link = $(this).attr('href');
var dataString = 'link='+ link;
$.ajax({
type : "POST",
url: "readmore-post.php",
data: dataString,
cache : false,
success: function(html){
$(".read_more").before(html);
}
});
});
});
this is the html part
<?php echo substr($post,0,250); ?>..
<?php
if(strlen($post)>250)
{
echo"<a href='$postID' style='font-size:0.8em;' class='readMore'>readmore</a> </br>";
}
?>
<div class="read_more"></div>
this is the php part
<?php
include('../config/connect.php');
$read_id = $_POST['link'];
$srm = "SELECT * FROM page_timeline WHERE timelineID='$read_id' ORDER BY timelineID DESC";
$sre = $db->query($srm);
while($rowr = $sre->fetch_array())
{
$postID = $rowr['timelineID'];
$post = $rowr['post'];
}
echo "<p>".$post."</p>";
?>
Try this and see inline comments
$(function(){
$(".readMore").click(function(event){
event.preventDefault();
var that=$(this);
var link = $(this).attr('href');
var dataString = 'link='+ link;
$.ajax({
type : "POST",
url: "readmore-post.php",
data: dataString,
cache : false,
success: function(html){
$(".read_more").empty().append(html);
//clear all the contents and append new one to .read_more div
that.hide(); //hide the button on successful load
},
});
});
});

Send selectbox value to php variables without page reloading

I'm learning AJAX by reading some online tutorials, so please understand I am very new to AJAX and programming in general. I have managed to do the following with 3 selectboxes:
populates selectbox 2 based on selection from selectbox 1
populates selectbox 3 based on selection from selectbox 2
Everything is working perfectly
Here is my code:
$(document).ready(function()
{
$(".sport").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_sport.php",
dataType : 'html',
data: dataString,
cache: false,
success: function(html)
{
$(".tournament").html(html);
}
});
});
$(".tournament").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "get_round.php",
data: dataString,
cache: false,
success: function(html)
{
$(".round").html(html);
}
});
});
});
</script>
Here is an Example
What I want to do
I would like to send the value of the 3 selectboxes to 3 php variables without the form reloading.
My Problem
When the user clicks submit:
The form reloads (which I dont want)
The selectbox values does not get send to my php variables
my code to get the values after submit is clicked is as follows:
if(isset($_POST['submit'])){
$a = $_POST['sport'];
$b = $_POST['tournament'];
:
}
However my code is flawed as I mentioned above.
If any one can help me to explain how to send my form data to the 3 php variables without the form reloading it will be greatly appreciated
If you don't want to submit your form when you click the button, you need to set that input as button and not submit. You can, also, attach the submit event handler to the form and prevent it to submit:
$("form").on("submit", function(e){
e.preventDefault(); //This is one option
return false; //This is another option (and return true if you want to submit it).
});
So, being said this, you could probably do something like:
$("form").on("submit", function(e) {
var formData = $(this).serialize();
e.preventDefault();
$.ajax({
url: 'yoururl',
data: formData,
type: 'post', //Based on what you have in your backend side
success: function(data) {
//Whatever you want to do once the server returns a success response
}
});
});
In your backend:
if (isset($_POST["sport"])) {
//Do something with sport
}
if (isset($_POST["tournament"])) {
//Do something with torunament
}
echo "Successfull response!"; //You have to "write" something in your response and that is what the frontend is going to receive.
Hope this helps!
Try using the javascript function preventDefault().
See this SO question.
Use a <button>Submit</button> element instead of <input type="submit"/> since the submit automatically submits the form.
Edit: And you would have to use on.('click') instead of looking for submit event in your jQuery.

Selecting data Ajax

I would like to select streamitem_id from my insert.php and add it to my existing post div. I'm needing the id of the post made so I can add it into my div so later when I add my delete button it will delete the post and the div that holds it. Hope I've made sense and I can do this with what I have as I'm trying to learn but it is a difficult language like any when first starting out.
AJAX
<script>
$(document).ready(function(){
$("form#myform").submit(function(event) {
event.preventDefault();
var content = $("#toid").val();
var newmsg = $("#newmsg").val();
$.ajax({
type: "POST",
url: "insert.php",
data: "toid=" + content + "&newmsg=" + newmsg,
success: function(){
$("#homestatusid").prepend("<div id='divider-"+WHERE MY STREAMITEM_ID NEEDS TO BE+"'><div class='userinfo'>"+newmsg+"</div></div>");
}
});
});
});
</script>
INSERT.PHP
$check = "SELECT streamitem_id FROM streamdata WHERE streamitem_id=$user1_id";
$check1 = mysql_query($check);
$check2 = mysql_num_rows($check1);
echo $check2;
In your javascript should be
$.ajax({
type: "POST",
url: "insert.php",
data: {toid:content, newmsg: newmsg}, # pay attention to this line
success: function(data){
$("#homestatusid").prepend("<div id='divider-"+data+"'><div class='userinfo'>"+newmsg+"</div></div>");
}
});
PHP
$toid = isset($_POST['toid']) ? $_POST['toid'] : null;
$newmsg = isset($_POST['newmsg']) ? $_POST['newmsg'] : null;
And do not use mysql_* since it deprecated
The first argument passed to the success callback is the responseText from the AJAX call. Modify your jQuery code to this:
success: function(responseText){
$("#homestatusid").prepend("<div id='divider-"+responseText+"'><div class='userinfo'>"+newmsg+"</div></div>");
// I'm assuming that insert.php returns just the ID you're interested in
}
success: function(response){
$("#homestatusid").prepend("<div id='divider-"+response+"'><div class='userinfo'>"+newmsg+"</div></div>");
}

Rebind dymanically created forms after jQuery ajax response

I'm kinda new to jQuery but understand it for the most part. My problem is that when my ajax call which refreshes the entire div is done, all my dynamically created forms don't work. If you try and submit them, the event doens't work properly and just tries to do a normal form submit. I have all the other items such as links bound using the .live() which seem to work great. Just the form dies.
How do I rebind the dynamically created forms after the ajax call? They all have id of formname_id. I tried to use bind but it doesn't work as below. Any help is appreciated.
Here is the code
jQuery(document).ready(function(){
jQuery("form[id^='commentform_']").each(function(){
var id = parseInt(this.id.replace("commentform_", ""));
jQuery(this).bind('submit', function(e) {
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: "action="+ action +"& act_id="+ act_id,
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
});
});
Try doing something like this:
jQuery("form[id^='commentform_']").live('submit',function(){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
return false;
});
No need to loop over the forms to bind to them. If you can use delegate instead of live do so.
Why don't you over-ride the normal form submit:
function addNewitem() {
$('#new_item_form').submit(function() {
$.get("includes/ItemEdit.php", {
newItem: true
},
function(msg) {
isNewItem = true;
$("#new_item").hide();
$('#item_list').hide();
$("#item_edit").html( msg );
$("#item_edit").show();
editActiveEvent();
});
return false;
});
}
Don't forget to return false. or do a .preventDefault
I have gotten this to work adding the event in the function call and using event.preventDefault(); BUT of course only in FF. Doesn't work in IE7..
jQuery("form[id^='commentform_']").live('submit',function(event){
var id = parseInt(this.id.replace("commentform_", ""));
var action = jQuery('#action_' + id).attr('value');
var act_id = ('1');
jQuery.ajax({
type: "POST",
url: "ajax/modify.php",
data: {"action": action, "act_id": act_id},
success: function(response){
jQuery('#CommentsContainer_' + id).html(response);
jQuery('#commentform_' + id)[0].reset();
}
});
event.preventDefault();});
But IE7 still tries to sumbit the action. arrgggh.. Anything I'm doing wrong??

Categories