How to rebind jQuery script after it has been called used once? - php

I have three things going on:
I am sending information with this form.
<form method="post" id="myForm" action="includes/functions.php">
<input type="hidden" name="group_id" value="$group_id" />
<input type="hidden" name="submit_join"/>
<button class="request" id="sub" name="submit_join">Join</button>
</form>
This jQuery script runs a PHP script.
$("#sub").click(function() {
$.post( $("#myForm").attr("action"),
$("#myForm :input").serializeArray(),
function(){ $("#sub").html("Applied").fadeIn().addClass("applied").removeClass("request");
});
});
$("#myForm").submit(function() {
return false;
});
This is what the PHP script does. (Not a prepared statement)
if (isset($_POST['submit_join'])) {
//User ID
$user_id = $_SESSION['user_id'];
$group_id = $_POST['group_id'];
$sql="INSERT INTO group_assoc (user_id, group_id, permission, dateTime) VALUES ('$user_id', '$group_id', 0, now())";
if (!mysqli_query($connection, $sql)) {
die('Error: ' . mysqli_error($connection));
}
}
-It works just fine when someone clicks the button once.
It triggers the jQuery script
The jQuery script triggers the PHP script
The PHP does its job
The jQuery removes the class "request" and puts a class "applied"
Problem:
When the same user clicks another button (meaning a duplicate of the button that they just clicked), the page ignores the jQuery script and does what it would normally do, refresh the page. This is the unwanted process.
Why several forms and therefore why several buttons? I am doing a PHP while loop for every group in the website and every form contains a button (Join) that allows you to join the group and change the value on the database using the jQuery script above.
Question: How can I rebind the jQuery script so that when another button (<button class="request" id="sub" name="submit_join">Join</button>) is clicked, it will not ignore the jQuery script?

The problem seems to be that you are working with duplicate IDs, try with classes instead of id
<form method="post" class="myForm" action="includes/functions.php">
<input type="hidden" name="group_id" value="$group_id" />
<input type="hidden" name="submit_join" />
<button class="request" class="sub" name="submit_join">Join</button>
</form>
and
$(document).on('submit', '.myForm', function () {
return false;
})
$(document).on('submit', '.sub', function () {
var $form = $(this).closest('form');
$.post($form.attr("action"),
$form.serializeArray(), function () {
$("#sub").html("Applied").fadeIn().addClass("applied").removeClass("request");
});
})

Its always a good idea to pass in the event to the event handler, and do a event.preventDefault() to avoid browser's default behaviour on the elements.
$("#myForm").submit(function(event) {
event.preventDefault();
});
As for the multiple forms, you can use one handler to handle form submits. $('#sub') will bind to only the first button on the page, use a class to attach to multiple buttons of the same type which will still be inefficient. Here is a sample :
$('.subbtn').click(function(e){
var $form = $(this).parents('form'),
subUrl = $form.attr('action');
e.preventDefault();
$.post(...) ;
})
This handler should take care of your requirement. You can however use a single handler attached to the common wrapper of the forms (worst case 'body') to improve efficiency.

Like what jagzviruz said, it's always best to use the submit event's event handler to prevent the page refresh. And also, make sure you don't have any duplicate element IDs.
My approach would be something like this: (untested)
HTML
<form method="post" class="myForm" action="includes/functions.php">
<input type="hidden" name="group_id" value="$group_id" />
<input type="hidden" name="submit_join"/>
<button class="request" class="submit" name="submit_join">Join</button>
JS
$(".myForm").each(function() {
var $form = $(this),
action = $form.attr('action'),
$submit = $form.find('.submit');
$form.submit(function(event) {
event.preventDefault();
return false;
});
$submit.click(function(event) {
event.preventDefault();
$.post(...);
});
});
It's pretty much the same solution as what jagzviruz proposed, but I prefer to do things like this inside an .each() for clarity.

Related

isset validation in PHP failing when form submitted through jquery

My if(isset) validation is returning false after I have submitted the form through jQuery ,however works fine when done without jquery. Reason I am using jQuery is because I need to submit multiple forms:
Button
<input class="btn btn-primary" type ="submit" id="myButton"
name="create_record" value="Submit 1">
jQuery:
<script>
$(document).ready(function () {
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
// $("#form2").submit();
});
});
</script>
PHP
<?php
if(isset($_POST['create_record'])){
$ecode = $_POST['ecode'];
$ename = $_POST['ename'];
$date = $_POST['date'];
$jobRole = $_POST['jobRole'];
}else{
echo "did not receive anything";
}
?>
Always getting "did not receive anything" . Can someone please help.
The submit button value only gets sent if the form is submitted in the traditional way by a button click. Since you are submitting the form via javascript, you'll need to explicitly include the submit button's value or validate your post data in some other way. If you need the value of the specific button that was clicked, something like this should work:
$("#myButton").click(function (event) {
event.preventDefault();
var el = '<input type="hidden" name="' + $(this).prop('name') + '" value="' + $(this).val() + '">';
$("#form1").append(el).submit();
});
As for your objective of submitting multiple forms at once, I believe it's impossible without using ajax as discussed here. If you need guidance on how to do that, better to open a new question.
Your code, isset($_POST['create_record']) maybe false or it didn't receive any values. If your query is only in one PHP file together with your jQuery, you need to check first your algorithm or use var_dump() for testing. Second, If it didn't work, make an alternative solution for it. Do the proper HTML code when using form or make another PHP file for receiving post purpose only.
<form action="directory_to_another_file" method="POST">
<!-- SOME INPUTS HERE -->
<input type="submit" value="Submit 1" name="create_record">
</form>
Try to test all of your codes.
You have to set form method as "POST" type and if you want to receive the form data in same page then empty the "action" key otherwise give the target link.
<?php
if(isset($_POST['create_record'])){
print_r($_POST);
}
?>
<form action="" method="POST" id="form1">
<input type="text" name="create_record" value="Submit 1"/>
</form>
Submit
<script>
$(function(){
$("#myButton").click(function (event) {
event.preventDefault();
$("#form1").submit();
});
})
</script>
Let me know if it's work for you.

Having Issues with ajax submit reloading, the anonymous function is not executing

I spent quite a bit of time looking for this and maybe I'm not approaching this correctly, but I'm trying to .submit and .post after clicking a submit. In other instances I have been able to get the ajax submit to work properly without the refresh, but when I do it in this manner it just doesn't work. I'm curious to know why.
Form
<form id="search" action="process.php" method="post">
Name: <input id="search_text" type="text" name="name" />
<input type="submit" value="Submit" />
</form>
Ajax
$('#search').submit(function() {
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
$('#page_nav').html(data.html_page_nav);
$('#results').html(data.table_html);
},
"json"
);
return false;
});
This works and it will submit without reloading just fine
Below is where I have the problem.
On the php server side I am sending back html that I want to be able to submit, which the initial search will put into the original html page.
$html_page_nav = "
<ul>
";
for($i=1; $i <= get_query_pages(get_query_count($query), 50); $i++) {
$html_page_nav .= "
<li>
<form id='page_".$i."' action='process.php' method='post'>
<input type='hidden' name='action' value='change_page'/>
<input type='hidden' name='page' value='".$i."'/>
<input type='submit' value='".$i."'>
</form>
</li>
";
}
$html_page_nav .= "
</ul>
";
I try to do the same thing as above, but the submit does not work properly
$(document).ready(function() {
$('#page_1').submit(function() {
console.log("this will not display");
$.post(
$(this).attr('action'),
$(this).serialize(),
function(data){
},
"json"
);
return false;
})
...other jquery
});
This submit will not work properly, the function() will not execute and it will submit like the regular submit and go to the url rather then execute without refreshing the entire page.
Any suggestions or approaches would be much appreciated.
Thanks in advance!
Delegate the submit action to execute on content which will be loaded in future. By default the normal event handlers attached to the content loaded on DOM but not the one which will gets loaded in future, say through Ajax. You can use jQuery "on" function to delegate the action on content which will load in future.
eg.
$('body').on('submit', '#page_1', function() {
// do it here
});
I had a similar problem using ajaxForm n all. I jus used $("#Form").validate();
for it and the page doesnt get refresh

jQuery Ajax Call inside of PHP

I'm clearly doing something wrong here, but I can't figure out why the Ajax isn't firing and instead insists upon a page load. The newBatable() fires fine, I just can't seem to get the vote to respect the ajax call.
HTML - not sure how to put html in here as code :/ - I feel dumb.
<form class="form-horizontal" id="batable1" action="vote.php" method="GET">
<div id="success-vote-1"></div>
<input type="radio" name="batableResult" value=" include ()" /> include ()<br/>
<input type="radio" name="batableResult" value="require ()" />require ()<br/>
<input type="radio" name="batableResult" value="both of above" />both of above<br/>
<input type="radio" name="batableResult" value="None of above" />None of above<br/>
<button class="btn btn-primary" onClick="vote(1)">Vote</button>
<input type="hidden" name="batableId" id="batable-id" value="1"/>
</form>
JS - the console display everything I want, the php script processes everything nicely and functions perfectly, it is just it has to load the php in the browser so it's not using AJAX
/***************************************/
function newBatable() {
var batableData = $('#new-batable').serialize();
//console.log(batableData);
$.ajax({
url: "process.php",
data: batableData,
success: function(data){
$('#success-new-batable').html(data);
}
});
}
/***************************************/
function vote(poll_id) {
//console.log(poll_id)
var batableId = "#batable" + poll_id;
//console.log(batableId)
var pollData = $(batableId).serialize();
//console.log(pollData);
$.ajax({
url: "vote.php",
data: pollData,
success: function(data){
var batable_success_id = "#success-vote" + poll_id;
$(batable_success_id).html(data);
}
});
}
The submit button fires the JavaScript and then immediately submits the form.
If you are using onclick, then return false to stop that.
You would be better off using a more modern event binding technique though.
how about attaching a click event via jquery to the button?
$(".btn").on('click', function(e){
e.stopPropagation()
e.preventDefault();
vote(1);
});
this would usually be placed in document .ready jquery in an external file or somewhere near the bottom of your page inside script tags.
Does this help?
Since you're already using jQuery, as SubstanceD, you should use jQuery's on() method and stop the event propagation and prevent the default action (submitting the form).
I also noticed a possible bug in your code. It looks like there is a typo. You have
var batable_success_id = "#success-vote" + poll_id;
and <div id="success-vote-1"></div>. You have a dash after vote in the div's ID while you are concatenating batable_success_id into #success-vote1, for example. So even if the AJAX call is made, it probably won't update your HTML like you're expecting.

Run PHP code after button click but without refreshing page

I have a form in HTML to apply a Discount Coupon to a current shopping cart.
I would like the user to just click on APPLY (after entering the coupon code) and then without refreshing the page, to have some PHP code run so it computes the corresponding discount.
Here is my form:
<form action="">
<input type="text" name="couponCode">
<input type="submit" value="Apply">
</form>
PHP to be run:
if (isset($_REQUEST['couponCode']) && $_REQUEST['couponCode']!='')
{
$couponCode = $_REQUEST['couponCode'];
if ($couponCode == "TEST1")
{
$discount=0.2;
}
}
How would this be done using javascript?
You need to use either the onsubmit event of the form or the onclick event of the button.
In the event handler, you assemble a URL and "get" it. For example:
<script type="text/JavaScript">
function submitCouponCode()
{
var textbox = document.getElementById("couponCode");
var url =
"https://www.example.com/script.php?couponCode=" + encodeURIComponent(textbox.value);
// get the URL
http = new XMLHttpRequest();
http.open("GET", url, true);
http.send(null);
// prevent form from submitting
return false;
}
</script>
<form action="" onsubmit="return submitCouponCode();">
<input type="text" id="couponCode">
<input type="submit" value="Apply">
</form>
Use jQuery AJAX. When it's complete, refresh your page as needed.
You can use Jquery to do an AJAX post you your PHP script, and then use JS to change the contents of the calling page.
http://api.jquery.com/jQuery.post/
It's simple with jQuery. You just have to use the right tag. If you use an "a" tag the page will refresh.
<button id="MyButton">Click Me!</button>
<script>
$("#MyButton").click( function(){
$.post("somefile.php");
});
</script>

Enter to submit rather than refresh [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Enter button on Keyboard refreshes rather than submitting
I have the following form structure
structure of my form:
<form name="form">
<label>Name:</label>
<input type="text" name="name" id="id" size="50"/></br>
<label></label>
<input type="button" value="Get Info" onClick="get();">
</form>
<div id="age"></div>
My javascript for the get function is as follows:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
}
Now when i use button(input type="button") to post information it works well,But when i fill the information and press enter on the keyboard page gets refreshed.
How can i make Enter button to post the info?
Many times the default behavior in a form when enter is pressed in a non-textarea field is to submit, even when a submit button was not pressed or even present.
Try this:
<form name="form" onsubmit="get();return false;">
In fact, using this technique, you would be able to change your input button to a submit to simplify the form with the same outcome:
<input type="submit" value="Get Info"/>
try return false; in your function. This will stop the button from having its usual behaviour:
function get() {
$.post('XXX.php', { name: form.name.value },
function(output){
$('#age').html(output).show();
});
return false;
}
I do it a little differently (which probably means its the wrong way). I dont make a form at all. I just create inputs, selects, etc.. and then when i do my POST i just get the values wen the function is called..
$.ajax({
type: "POST",
url: "someFile.php",
data: { 'name': $("#ElementID").val()},
success: function(data) {
//some function....
{
});
Hope that may be helpful....
I see you posted this as jQuery so I figured I'd give you a solution using that.
$('form[name=form]').submit(function(e) {
var $form = $(this);
$.post( $form.attr('action'), $form.serializeArray(), function( result ) {
$('#age').html( result ).show();
});
e.preventDefault();
});
This will keep you from having to create a crazy json object for the data parameter and from repeating yourself with the form's action attribute. This will also keep the browser's behavior where pressing enter when on an input will submit the form.
Here goes some code I have from an example earlier. The only thing in the form's action file is <?php print_r($_POST); ?>.

Categories