Javascript in a Included PHP File - php

I have a php file (a form) that includes javascript to check if all inputs are filled. When I view the php file directly the js works perfectly, but when I include the PHP file in another page the javascript no longer works.
My javascript code:
<script type="text/javascript" src="../js/modernizr.js"></script>
<script type="text/javascript">
window.onload = function(){
document.getElementById("topField").setAttribute("autocomplete","off");
}
window.onload = function() {
// get the form and its input elements
var form = document.forms[0],
inputs = form.elements;
// if no autofocus, put the focus in the first field
if (!Modernizr.input.autofocus) {
inputs[0].focus();
}
// if required not supported, emulate it
if (!Modernizr.input.required) {
form.onsubmit = function() {
var required = [], att, val;
// loop through input elements looking for required
for (var i = 0; i < inputs.length; i++) {
att = inputs[i].getAttribute('required');
// if required, get the value and trim whitespace
if (att != null) {
val = inputs[i].value;
// if the value is empty, add to required array
if (val.replace(/^\s+|\s+$/g, '') == '') {
required.push(inputs[i].name);
}
}
}
// show alert if required array contains any elements
if (required.length > 0) {
alert('The following fields are required: ' +
required.join(', '));
// prevent the form from being submitted
return false;
}
};
}
}
</script>

This is an explanation to anyone who finds this question later. In javascript you can only attach a single function to an event handler. If you want to attach more, you need to chain them. Pretty much all javascript framework/libraries has some sort of method to handle event chaining.
Javascript allows you to treat functions like variables. So you can assign an old onload function to a variable, then call it later within the new onload function.
If you are not using a framework, you can do something like this to handle event chaining.
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
You would call this with the following:
addLoadEvent(function(){
// Some code here
});

Related

If Jquery variable equals the class of a div then set display to block

I'm outputting several divs using php - each div has a different country name for the class.
I'm also outputting a variable using jquery which checks if content of a div has changed. That variable will also be a country name.
If the jquery variable matches a div class, I want that div to .show(), how can I do that?
This is my (horrible) attempt:
(function($) {
$(document).ready(function () {
$("#block1").bind("DOMSubtreeModified", function() {
message = $("#block1").html();
regiondiv = '.';
fullregion = regiondiv + message;
alert(fullregion);
if ($('.region-logos').hasClass(message)) {
$(fullregion).show();
} else {
$(fullregion).hide();
}
});
});
})(jQuery);
If I click on Canada for instance, it will show the .Canada div, but if I click on Spain after it, it's shows the .Spain div as well as the .Canada div. I.e once you click on more than one it just continues to show them all. It doesn't hide the divs if you haven't click on it.
var class = 'no-class';
$(document).ready(function () {
$("#block1").bind("DOMSubtreeModified", function() {
var regiondiv = '.';
var fullregion = regiondiv + class ;
$(".fullregion").hide();
class = $("#block1").html();
fullregion = regiondiv + class ;
$(".fullregion").show();
});
});
Not sure if I followed the question correctly. I assume you want to display a div if class of that div matches a variable in javascript. If so the you can try this:
(function($) {
$(document).ready(function () {
$("body").bind("DOMSubtreeModified", function() {
// Not sure how are you generating this jquery variable
var yourJqueryVariable;
// Check if class name exists
if ($(".yourJqueryVariable")[0]){
$(".yourJqueryVariable").show(); //or even $(".yourJqueryVariable").css('display','block');
}
});
});
})(jQuery);
(function($) {
$(document).ready(function () {
$("#block1").bind("DOMSubtreeModified", function() {
var message = $("#block1").html();
//ok so you have the variable to check
if($('.'+message).length > )) { //is there 1 or more of these classes in the DOM?
$('.'+message).each(function() { //there is, loop and show them all
$(this).show();
});
}
});
});
})(jQuery);
EDIT
Ok looking at your updated answer, assuming there are multiple .region-logos you need to perform your if else within a loop of those:
$('.region-logos').each(function() {
if($(this).hasClass(message)) {
$(fullregion).show();
}else {
$(fullregion).hide();
}
});

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);
});
});

Loading a jquery function on form submit instead on change event

I have a jQuery script that dynamically changes select menus. The script uses the function populate() everytime a change event occurs in one of the menus. I would like the same script to run after a form submit. To have an idea this is what the script looks like...
$(document).ready(function(){
function getUrlVars() {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars;
}
function populate() {
if ($('#STATEID').val() == 'AK' || $('#OB_USTATEID').val() == 'DC') {
// Alaska and District Columbia have no counties
$('#county_drop_down3').hide();
$('#no_county_drop_down3').show();
}
else {
fetch.doPost('../../getCounties2c.php');
}
}
$('#STATEID').change(populate);
var fetch = function() {
var counties = $('#countyid');
return {
doPost: function(src) {
$('#loading_county_drop_down3').show(); // Show the Loading...
$('#county_drop_down3').hide(); // Hide the drop down
$('#no_county_drop_down3').hide(); // Hide the "no counties" message (if it's the case)
if (src)
$.post(src, { state_code3: $('#STATEID').val() }, this.getCounties);
else
throw new Error('No SRC was passed to getCounties!');
},
getCounties: function(results) {
if (!results)
return;
var allCities = $("<option value=\"All\">All Counties</option>");
counties.html(results);
counties.prepend(allCities);
var first = getUrlVars()["countyid"];
if (first) {
counties.val(first).attr('selected',true);
}
else {
counties.val("All").attr('selected',true);
}
$('#loading_county_drop_down3').hide(); // Hide the Loading...
$('#county_drop_down3').show(); // Show the drop down
}
}
}();
populate();
});
How can I accomplish that? Any suggestions will be highly appreciated!
Use $(element).submit(function (e) {} ); to catch a submit event. You can even fire it off, by calling $(element).submit().
jQuery docs : http://api.jquery.com/submit/

How to call a PHP class method from a JavaScript function [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Call php function from javascript
I understand that php is server side and JavaScript is client side. But I would like to know how to run a PHP method when a JavaScript function is called. Below is my code, I know the error is but how can I perform the php method?
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
<?php Category::addCategory($inCatName)?>
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>
Thanks for your help.
Using the Prototype library (www.prototypejs.org):
Javascript:
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
var options={
method: 'get',
parameters: 'inCatName='+ele.value,
onSuccess: function(xhr) {
// TODO: Whatever needs to happen on success
alert('it worked');
},
onFailure: function(xhr) {
// TODO: Whatever needs to happen on failure
alert('it failed');
}
};
new Ajax.Request('addCategory.php', options);
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>
addCategory.php:
<?php
$inCatName=isset($_REQUEST["inCatName"]) ? $_REQUEST["inCatName"] : null;
Category::addCategory($inCatName);
?>
The idea is that the Javascript sends a GET (or it could be POST) request to the addCategory.php page behind the scenes, passing it whatever info it needs to create the category.
Hopefully this is enough to get you going. There's a lot missing from my code - you'll need to validate the variables addCategory.php receives and perform any other pertinent security checks before letting it anywhere near the database. addCategory.php will also require any include files, etc so that it knows about your Category class. Finally, addCategory.php should really return some form of variable back to the Javascript code that called it so that it knows what the outcome was.
You can use an Ajax request to an endpoint that triggers your PHP and then perform Category::addCategory($inCatName)
With Jquery:
$.ajax({
url: "addCategory.php",
context: document.body,
success: function(){
// whatever you need to do
}
});
This might help. Use ajax to call you php file (categories.php was used in the example). Send a parameter called "function" and set it as "addCategory". In your php file write code to detect if $_GET['function'] is set and also to detect if it is set as "addCategory". If it is, have the code call the function. I also saw that you were trying to pass the $inCatName parameter to the php function. To send this just add it into the url below.
<script type="text/javascript">
function toggle()
{
var ele = document.getElementById("addCatTextBox");
var text = document.getElementById("addCatButtonText");
if(ele.style.display == "block") {
ele.style.display = "block";
text.innerHTML = "Save category";
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","categories.php?function=addCategory",true);
xmlhttp.send();
}
else {
ele.style.display = "none";
text.innerHTML = "Add new category";
}
}
</script>

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