$("#form").submit() doesnt send the name of the pressed button through - php

I have a long form, that's a sliding page form so that it is broken up into parts for the user.
I do my error checking through jQuery, here is the code:
$("input.next").click(function(e) {
e.preventDefault();
var stage = ((($("#container").position().left) / 950) * -1) + 1;
var thispage = $(this).closest("div.page");
var errors = false;
var isFinal = $(this).hasClass("send");
thispage.find("input.txt").each(function () {
if(($(this).val() == "") && (!$(this).hasClass("optional"))) {
$(this).css("background","#FFE5E5");
errors = true;
} else {
$(this).css("background","#E5FFEA");
}
});
thispage.find(".checkbox").each(function () {
if(!$(this).is(':checked')) errors = true;
});
if(thispage.find("#profileimage").val() == "") errors = true;
thispage.find("textarea.txt").each(function () {
if(($(this).val() == "") && (!$(this).hasClass("optional"))) {
$(this).css("background","#FFE5E5");
errors = true;
} else {
$(this).css("background","#E5FFEA");
}
});
if(!errors) {
// if no errors, slide to next page.
if(!isFinal) {
thispage.find("div.errormessage").fadeOut(50);
$("#container").animate({left: "-=950px"}, 800, function () {
$("ul#stages li").removeClass("active");
$("ul#stages li.stage"+stage).addClass("active");
console.log("Stage: " + stage);
});
}
} else {
thispage.find("div.errormessage").fadeIn(100);
}
console.log("isFinal: " + isFinal);
console.log("Errors: " + errors);
if((isFinal) && (!errors)) {
console.log("submitting form...");
$("#enrolform").submit(); }
});
However when the div.next.send button is pressed, it has a name of sendapplication and in my PHP code I am using:
if(isset($_POST['sendapplication'])) {
..To check whether the entire form was submitted or not. The reason I need to do this is because I also have a 'save' feature of the form, which allows the user to save the data and come back later.
The problem is when the user clicks 'sendapplication' button I don't get that through in the $_POST or $_REQUEST variables. And I think the reason why is because it's the jQuery script that's sending it, and not the button. The button is suppressed because of the e.preventDefault() line.
How can I check that that particular button was pressed? is there someway I can manipulate the .submit() function?

You can add following code into the click() method:
var self= $(this),
form = self.closest(form),
tempElement = $("<input type='hidden'/>");
// clone the important parts of the button used to submit the form.
tempElement
.attr("name", this.name)
.val(self.val())
.appendTo(form);
See jQuery submit() doesn't include submitted button for more details
Anthony Grist's comment is probably a lot better solution to this :)

Related

jQuery load() not functioning as expected

I've a jquery script that call the number2.php page, which is supposed to execute and show the result in a <div>. The problem is that is not working. Can you help me? Thanks.
<script>
$(function() {
$('#submit').click(function() {
if ($('#taille').val() != 0) {
var param = 'l=' + $('#taille').val();
}
else {
var param = 'b=' + $('#datepicker').val() + 'c=' + $('#datepicker1').val() + 'num' + $('#num').val();
}
$('#retour').load('number2.php', param);
);
});
</script>
Your code has a syntax error; it's missing closing } in the click handler function.
now it works but after loading number2.php my main page is refreshed and i lose the result !!!
In this case, you should hook to the submit event of the form element and call preventDefault() on the event to prevent the normal form submission. Try this:
$(function() {
$('#myForm').submit(function(e) { // change #myForm to target the <form>
e.preventDefault();
var param = {};
if ($('#taille').val() != 0) {
param.l = $('#taille').val()
}
else {
param.b = $('#datepicker').val();
param.c = $('#datepicker1').val();
param.num = $('#num').val();
}
$('#retour').load('number2.php', param);
});
});

Pressing backbutton on browser going back history url

I am using
window.history.pushState
and popstate functions for getting the previous page url's while clicking on back button of browser and i want to reload the page every popstate function calls.
My code is..
function refresh_results() {
page_link = $("#form").serialize();
if(page_link!=window.location){
window.history.pushState({path:pageurl},'',pageurl);
}
}
In popstate function
$(document).ready(function($) {
var popped = ('state' in window.history && window.history.state !== null), initialURL = location.href;
if (window.history && window.history.pushState) {
$(window).bind('popstate', function(e) {
var initialPop = !popped && location.href == initialURL;
popped = true;
if (initialPop) return;
pageurl = location;
console.log(pageurl);
window.location = location.href;
//window.location = pageurl;
return e.preventDefault();
});
}
});
But, for every time when i click on back button page is refreshing continuosly in chrome,but in firefox it's fine.
Can u suggest me how my functionlity will workable, and suggest me if i am missing anything

Saving form state with javascript only on submit

So. I have a Form with a lot of checkboxes. Along with that I have a piece of javascript code that is supposed to save the state of every checkbox when the user presses submit. My short and irritating problem is two things.
Question: I want to save Checkbox state to cookie ONLY when I submit the form, right now it saves if I mark a checkbox and reload the page, without submitting. Im working with Javascript and Cookies, two things that Im quite new to. So Im very greatful for all help. Here is my code that I got from here:
function getStorage(key_prefix) {
if (window.localStorage) {
return {
set: function(id, data) {
localStorage.setItem(key_prefix+id, data);
},
get: function(id) {
return localStorage.getItem(key_prefix+id);
}
};
} else {
return {
set: function(id, data) {
document.cookie = key_prefix+id+'='+encodeURIComponent(data);
},
get: function(id, data) {
var cookies = document.cookie, parsed = {};
cookies.replace(/([^=]+)=([^;]*);?\s*/g, function(whole, key, value) {
parsed[key] = unescape(value);
});
return parsed[key_prefix+id];
}
};
}
}
jQuery(function($) {
var storedData = getStorage('com_mysite_checkboxes_');
$('div.check input:checkbox').bind('change',function(){
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
}).each(function() {
var val = storedData.get(this.id);
if (val == 'checked') $(this).attr('checked', 'checked');
if (val == 'not') $(this).removeAttr('checked');
if (val == 'checked') $(this).attr('disabled','true');
if (val) $(this).trigger('change');
});
});
So I want to save to cookie only on submit basically.
Bind to the submit event of the form instead of the change event of all the checkboxes.
Try this in place of your second function:
jQuery(function($) {
// bind to the submit event of the form
$('#id-of-your-form').submit(function() {
// get storage
var storedData = getStorage('com_mysite_checkboxes_');
// save checkbox states to cookie
$('div.check input:checkbox').each(function() {
// for each checkbox, save the state in storage with this.id as the key
storedData.set(this.id, $(this).is(':checked')?'checked':'not');
});
});
});
jQuery(document).ready(function() {
// on load, restore the checked checkboxes
$('div.check input:checkbox').each(function() {
// get storage
var storedData = getStorage('com_mysite_checkboxes_');
// for each checkbox, load the state and check it if state is "checked"
var state = storedData.get(this.id);
if (state == 'checked') {
$(this).attr('checked', 'checked');
}
});
});

Detect page refresh or new load using PHP or Javascript

How to detect tab close in browsers using PHP or Javascript. In other words, How to find if page is refreshed or opened in new tab. I am concerned about tab, not browser.
You can have a listener for the window.onbeforeunload event. You won't be able to detect if the tab is closed from JavaScript, though.
Actually Javascript can tell you if a Tab is going to be closed. Two different methods need to be used (one for IE and one for everyone else).
I wrote a Javascript process to do just what you are asking. Pre-requisites for the process is jQuery and one plugin (livequery - because some of the HTML is dynamically generated after page load). Anyway, here is the js file that does all this (checkclosing.js):
// Global Var
var bodyclicked = false;
var datachanged = false;
var nodirtycheck = false;
// Start the engines :)
$(document).ready(function () {
init();
});
function init() {
bindEvents();
}
function bindEvents() {
// Bind the onClick event for the DOM body
$(document).livequery(function () {
bodyclicked = true;
});
// Bind our event handlers for the change and reset events
$(':input').not('.excludeFromDirtyCheck').bind('change', function () {
if ($(this).hasClass('dataLoader')) {
if (!datachanged) {
return;
}
}
datachanged = true;
$(".hidDataChanged").val("True");
});
$(':reset,:submit').bind('click', function () {
// .NET renders some ASP Buttons as Submit and Reset types
if ($(this).hasClass('notSubmit')) {
return;
}
if ($(this).hasClass('notReset')) {
return;
}
datachanged = false;
$(".hidDataChanged").val("False");
});
// Must have the livequery plugin referenced for this to work
$('.resetchangedform').livequery('click', function (event) {
//alert("resetchanged"); // FIXME
datachanged = false;
// Set our hidden input (on the Administration Master page)
$(".hidDataChanged").val("False");
});
// Must have the livequery plugin referenced for this to work
$('.setchangedform').livequery('click', function (event) {
//alert("setchanged"); // FIXME
datachanged = true;
// Set our hidden input (on the Administration Master page)
$(".hidDataChanged").val("True");
});
// Must have the livequery plugin referenced for this to work
$('.excludeFromDirtyCheck').livequery('click', function (event) {
nodirtycheck = true;
});
// Must have the livequery plugin referenced for this to work
$('.notSubmit').livequery('click', function (event) {
nodirtycheck = true;
});
// Must have the livequery plugin referenced for this to work
$('.dataReloader').livequery('change', function (event) {
nodirtycheck = true;
});
window.onbeforeunload = function () {
//alert("datachanged = " + datachanged + " | nodirtycheck = " + nodirtycheck + " | hidDataChanged = " + $(".hidDataChanged").val());
// Check the hidden textbox
if ($(".hidDataChanged").val() == "True") {
datachanged = true;
}
if (nodirtycheck) {
nodirtycheck = false;
}
else {
if (navigator.appName == "Microsoft Internet Explorer") {
// IE
if (bodyclicked) {
if (datachanged) {
return "You may have unsaved changes...";
}
}
else {
bodyclicked = false;
// Do Nothing
}
}
else {
// Not IE
if (datachanged) {
return "You may have unsaved changes...";
}
else {
// Do Nothing
}
} //if (navigator.appName == "Microsoft Internet Explorer") {
} //window.onbeforeunload = function () {
} // if (nodirtycheck) {
}
Then just include a reference to this file on any page you want to check for a tab close on:
This was built to help prevent users from navigating away from pages with unsaved changes to form values. Yes, I know that most of the time, it is bad practice to prevent the user from closing a tab or navigating away, but in this case - the users requested it and this is an internal application that is not for public consumption.
Any controls that you don't want to be checked for changes prior to letting the user close the tab or navigate away would just be given a class name of excludeFromDirtyCheck.
This may be more than you need, but you can strip off the parts that aren't useful. The basic premise is the same.

jQuery get() php button submit

I have the following jquery code
$(document).ready(function() {
//Default Action
$("#playerList").verticaltabs({speed: 500,slideShow: false,activeIndex: <?=$tab;?>});
$("#responsecontainer").load("testing.php?chat=1");
var refreshId = setInterval(function() {
$("#responsecontainer").load('testing.php?chat=1');
}, 9000);
$("#responsecontainer2").load("testing.php?console=1");
var refreshId = setInterval(function() {
$("#responsecontainer2").load('testing.php?console=1');
}, 9000);
$('#chat_btn').click(function(event) {
event.preventDefault();
var say = jQuery('input[name="say"]').val()
if (say) {
jQuery.get('testing.php?action=chatsay', { say_input: say} );
jQuery('input[name="say"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#console_btn').click(function(event) {
event.preventDefault();
var sayc = jQuery('input[name="sayc"]').val()
if (sayc) {
jQuery.get('testing.php?action=consolesay', { sayc_input: sayc} );
jQuery('input[name="sayc"]').attr('value','')
} else {
alert('Please enter some text');
}
});
$('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
});
});
Sample Form
<form id=\"kick_player\" action=\"\">
<input type=\"hidden\" name=\"player\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn\" value=\"Kick Player\"></form>
And the handler code
if ($_GET['action'] == 'chatsay') {
$name = USERNAME;
$chatsay = array($_GET['say_input'],$name);
$api->call("broadcastWithName",$chatsay);
die("type: ".$_GET['type']." ".$_GET['say_input']);
}
if ($_GET['action'] == 'consolesay') {
$consolesay = "§4[§f*§4]Broadcast: §f".$_GET['sayc_input'];
$say = array($consolesay);
$api->call("broadcast",$say);
die("type: ".$_GET['type']." ".$_GET['sayc_input']);
}
if ($_GET['action'] == 'kick') {
$kick = "kick ".$_GET['player_input'];
$kickarray = array($kick);
$api->call("runConsoleCommand", $kickarray);
die("type: ".$_GET['type']." ".$_GET['player_input']);
}
When I click the button, it reloads the page for starters, and isn't supposed to, it also isn't processing my handler code. I've been messing with this for what seems like hours and I'm sure it's something stupid.
What I'm trying to do is have a single button (0 visible form fields) fire an event. If I have to have these on a seperate file, I can, but for simplicity I have it all on the same file. The die command to stop rest of file from loading. What could I possibly overlooking?
I added more code.. the chat_btn and console_btn code all work, which kick is setup identically (using a hidden field rather than a text field). I cant place whats wrong on why its not working :(
use return false event.instead of preventDefault and put it at the end of the function
ie.
$(btn).click(function(event){
//code
return false;
});
And you should probably be using json_decode in your php since you are passing json to the php script, that way it will be an array.
Either your callback isn't being invoked at all, or the if condition is causing an error. If it was reaching either branch of the if, it wouldn't be reloading the page since both branches begin with event.prevntDefault().
If you're not seeing any errors in the console, it is likely that the callback isn't being bound at all. Are you using jQuery(document).ready( ... ) to bind your event handlers after the DOM is available for manipulation?
Some notes on style:
If both branches of the if contain identical code, move that code out of the if statement:
for form elements use .val() instead of .attr('value')
don't test against "" when you really want to test truthyness, just test the value:
jQuery(document).ready(function () {
jQuery('#kick_btn').click(function(event) {
event.preventDefault();
var player_name = jQuery('input[name="player"]').val()
if (player_name) {
jQuery.get('testing.php?action=kick', { player_input: player_name} );
} else {
alert('Please enter some text');
}
})
});
I figured out the problem. I have a while loop, and apparently, each btn name and input field name have to be unique even though they are all in thier own tags.
$("#playerList").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name
});
jQuery('input[name="player"]').attr('value','')
alert('Successfully kicked ' + player_name + '.');
});

Categories