Good evening everyone,
I am currently trying to cleanup my inline JS and break it up into its own .js file, as well as breaking up some of my code into functions. Below I provide my code, I have an HTML file with an empty div named #main. On document ready I want to call my firstLoad function. It simply calls $("#main").load("login.php"); Seems simple enough, however my next step is that on submit of the form I want to serialize the submitted data, turn to string and submit via post. This for some reason will work if I hard code the form into the index.php file, but not if I use .load to fill in #main. I can't figure out why this is, I am sure it's simple if someone could explain it little that would be wonderful. My code follows:
UPDATE
After more searching I came across this thread that says the following:
As it turns out, the jquery .load() function is working flawlessly,
and I'm approaching this wrong.
Once the .load() function completes successfully, it calls any
"callback" function included by the programmer, just like any other
jquery function that accepts a callback as one of its "arguments". The
.load() function is complete once it either errors or successfully
begins the HTML replacement and loading of new content, but that is
IT! The content will then take however long it takes to load, but your
.load call is already complete before that. Therefore, expecting the
callback to run after the .load content has loaded will only
disappoint you. ;)
I hope others can learn from this just as I did, including those who
thought what I thought was the case. Proof: as stated in the jquery
ajax .load page, the callback is executed when the request completes,
not when the load completes. Eureka. Whoops.
Which leads to the follow up question, how can I manipulate the form after the load content has been added to the DOM? This is surely a simple fix, but I am new to AJAX and could use a nudge in the right direction. I notice adding a document(ready) within the login.php script works properly as it is added with the html, but it doesn't seem like the cleanest way of doing things, as I'm trying to keep out inline JS. Any more advice?
/UPDATE
PHP/HTML
index.php
<?php
session_start();
$sessionNumber = session_id();
?>
<!doctype html>
<!-- Conditional comment for mobile ie7 blogs.msdn.com/b/iemobile/ -->
<!--[if IEMobile 7 ]> <html class="no-js iem7" lang="en"> <![endif]-->
<!--[if (gt IEMobile 7)|!(IEMobile)]><!--> <html class="no-js" lang="en"> <!--<![endif]-->
<head>
<meta charset="utf-8">
<title>MyMobile</title>
<meta name="description" content="">
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="viewport" content="width=device-width">
<link rel="apple-touch-icon-precomposed" sizes="114x114" href="img/h/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" sizes="72x72" href="img/m/apple-touch-icon.png">
<link rel="apple-touch-icon-precomposed" href="img/l/apple-touch-icon-precomposed.png">
<link rel="shortcut icon" href="img/l/apple-touch-icon.png">
<meta http-equiv="cleartype" content="on">
<link rel="stylesheet" href="css/style.css">
<script src="js/libs/modernizr-2.0.6.min.js"></script>
</head>
<body>
<div id="container">
<header id="header">
<img alt="Logo" src="img/logo.png" />
<div id="blackHead">Please sign-in to continue</div>
</header>
<div id="main" role="main">
</div>
<footer id="footer">
<div id="greyFoot">
© 2012 ACME<br />
<pre id="result"></pre>
</div>
</footer>
</div> <!--! end of #container -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>window.jQuery || document.write('<script src="js/libs/jquery-1.7.1.min.js"><\/script>')</script>
<script type="text/javascript" src="js/firstLoad.js"></script>
</body>
</html>
login.php
<?php session_start();
$sessionNumber = session_id();
?>
<!-- begin login form -->
<?php if(isset($_SESSION['sessionemail'])){ ?>
Logout
<?php }else { ?>
<form id="logForm" name="login" method="post" action="#">
<label for="sessionemail">Email</label><br />
<input id="sessionemail" type="email" name="sessionemail" autofocus="autofocus" autocapitalize="off" maxlength="150" required="true" value="" class="inputText" /><br />
<label for="password">Password</label>
<input id="password" type="password" name="password" required="true" value="" class="inputText" /><br />
<br />
<input type="hidden" name="sessionid" id="sessionid" value="<?php echo $sessionNumber; ?>" />
<input type="hidden" name="subtocall" id="subtocall" value="g2.web.login.sub" />
<input type="submit" value="Sign-In" name="submit" class="submitBox" />
</form><!-- end login form -->
<?php } ?>
And finally, my JS/Jquery
firstLoad.js
//function serializes our object
(function($){
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
})(jQuery);
//firstLoad function runs on document ready
//it loads the login form into the main div and slides
//the container down
(function($){
$.fn.firstLoad = function(){
return this.each(function() {
$("#container").slideUp("slow", function(){
$("#main").load('./login.php', function(){
$("#container").slideDown("slow", function(){
});
});
});
});
};
})(jQuery);
//logParse takes the loginResponse from the server
//changes from string to object, runs a check for authentication then
//manipulates the object dropping excess keys and adding new relevant ones for
//the intial to do list call
(function($){
$.fn.logParse = function(xml){
return this.each(function() {
//parse the JSON login check string from the XML response
var loginResponse = $(xml).find('string').text();
//setup isBad variable for error check
var isBad = false;
//convert to JSON object from parsed string data
loginResponse = $.parseJSON(loginResponse);
//check if the sessionID is correct and user authenticated properly
if((loginResponse.SESSIONID != "<?php echo $sessionNumber; ?>") || (loginResponse.ISAUTHENTICATED == 0)){isBad = true;}
//if error flag is raised alert and bounce back to login
if(isBad){
alert("Unauthorized connection, please try again.");
}
//if there are no errors
else{
alert("so far so good!");
//set up a new JSON object for to do list passback
//and import the values from the lognResponse object
//var todoPost =
}
});
};
})(jQuery);
$(document).ready(function(){
//hide screen for slidedown
//$("#container").addClass("noShow");
//allow cross domain scripts
$.support.cors = true;
//call firstLoad function to slide in the login prompt
$("#main").firstLoad(function(){
//create JSON object to store form input for AJAX POST
//create submit listener
$("#logForm").submit(function(){
alert("inside submit");
//parse form into formObj for data passing and manipulation
var formObj = JSON.stringify($("form").serializeObject());
//output initial formObj into result pane
$("#result").text(formObj);
$("#main").text("submitted: " + formObj);
//AJAX POST call
$.ajax({
//type of communication
type: "POST",
//action for form
url: "http://mydomain.com/JSONService.asmx/G2WebRequest",
//data to be passed
data: "request="+ formObj,
//type of data passed in
contentType: "application/x-www-form-urlencoded; charset=utf-8",
//enable cross domain
crossDomain: "true",
//data type returned from webservice
dataType: "xml",
//if login POST was successful
success: function(xml){
alert("post successful");
$.logParse(xml);
},
//if login POST failed
error: function(XMLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
});
});
You are probably setting up the listener on $("#logForm") before the login form is fully loaded into the DOM. This would explain why the login form works when hardcoded. You can test this by alert($("#logForm").length);- this will be zero if not found.
If this is the case you will need to ensure you wait until the login page is completely loaded before attempting to attach the listener. I would probably make firstLoad call a function once load completes.
Good luck.
JQuery.on() solved this issue. Took me a while to figure that out.
Related
I am trying to submit a form with jquery/AJAX but my function is never called when I am clicking on the submit button.
My website looks like that:
CarMenu.php
<html lang="en">
<html>
<head>
<meta charset="ISO-8859-1">
<title>ArsenalAutoBrokers - Backend - add car</title>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.min.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.theme.css" type="text/css"/>
<link rel="stylesheet" href="../js/jquery-ui-1.11.4/jquery-ui.structure.css" type="text/css"/>
<link rel="stylesheet" href="../css/carForm.css" type="text/css"/>
<script charset="UTF8" src="../js/jquery/jquery-1.11.3.js"></script>
<script charset="UTF8" src="../js/jquery-ui- 1.11.4/external/jquery/jquery.js"></script>
<script charset="UTF8" src="../js/jquery-ui-1.11.4/jquery-ui.js"></script>
<script charset="UTF8" src="../js/app/carForm.js"></script>
<script charset="UTF8" src="../js/app/addCar.js"></script>
</head>
<body>
<div id="container">
<div id="leftMenuContainer">
<ul id="menu">
<li id="addCarItem">Add car</li>
<li id="saveCarItem">Edit cars</li>
</ul>
</div>
<div id="rightMainContent">
</div>
<div class="clear"></div>
</div>
</body>
</html>
On that page, I am using jquery menu and I am loading the data into the div with the id 'rightMainContent'.
The javascript code to do this looks like: carForm.js
$(document).ready(function () {
$( "#menu" ).menu({
select: function(event, ui) {
if (ui.item.attr('id') === 'addCarItem') {
$("#rightMainContent").load(
'/CarDealer/CarForm/CreateCar/AddCar.php');
}
}
});
});
If you are clicking on the 'addCar' menu item parts of the site will load from this php site:
<script type="text/javascript">
$('input[type=submit]').button();
//$('#activeCheck').button();
$("#activeCheck").attr('checked','checked');
$('#saveButton').hide();
$('#tabs').tabs();
$('#accordion' ).accordion({heightStyle: "content"});
$('#tabs').tabs({
activate: function (event, ui) {
var act = $("#tabs").tabs("option", "active");
if (act == 0 || act == 1) {
$('#saveButton').hide();
} else {
$('#saveButton').show();
}
}
});
$('#fileToUpload').on('change', function(){
var fileSelect = document.getElementById('fileToUpload');
var files = fileSelect.files;
if (files.length > 10) {
$('.info').html('The file upload is limited to <font color="red"><b>10 pictures per car</b></font>.<br>Only the 1st ten pictures will be stored.');
$('.info').show();
} else {
$('.info').html('');
$('.info').hide();
}
});
</script>
<form id="carSaveForm"
action="/CarDealer/CarForm/CreateCar/CarCreation.php" method="POST"
enctype="multipart/form-data">
<div id="tabs">
<ul>
<li>General Car Information</li>
<li>Car Descriptions</li>
<li>Picture Upload</li>
</ul>
<div id="tabsGen">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carGeneralData.php"); ?>
</div>
<div id="tabsDescr">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/carDescriptions.php"); ?>
</div>
<div id="tabsPics">
<?php include($_SERVER['DOCUMENT_ROOT']."/CarDealer/CarForm/CreateCar/PictureUpload.php"); ?>
</div>
</div>
<br> <input id="saveButton" type="submit" name="submit" value="save" />
</form>
This site is containg only form elements like input buttons, file pickers, etc.
Well, so far so good. Everything is displaying properly but if I am clicking the submit button this function isn't getting called: addCar.js
$('#carSaveForm').on('submit', function(event){
event.preventDefault();
var formData = new FormData();
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
formData.append('carBrand' , $('input[name=carBrand]').val());
formData.append('carModelYear' , $('input[name="carModelYear"]').val());
formData.append('carModel' , $('input[name=carModel]').val());
formData.append('carTrim' , $('input[name="carTrim"]').val());
formData.append('carDriveTrain' , $('input[name="carDriveTrain"]').val());
formData.append('carCondition' , $('input[name="carCondition"]').val());
formData.append('carType' , $('input[name="carType"]').val());
formData.append('carFuelType' , $('input[name="carFuelType"]').val());
formData.append('carTransmission' , $('input[name="carTransmission"]').val());
formData.append('carEngine' , $('input[name="carEngine"]').val());
formData.append('carCylinder' , $('input[name="carCylinder"]').val());
formData.append('carMileage' , $('input[name="carMileage"]').val());
formData.append('carExteriorColor' , $('input[name="carExteriorColor"]').val());
formData.append('carInteriorColor' , $('input[name="carInteriorColor"]').val());
formData.append('carLocation' , $('input[name="carLocation"]').val());
formData.append('carVin' , $('input[name="carVin"]').val());
formData.append('carStock' , $('input[name="carStock"]').val());
formData.append('carPrice' , $('input[name="carPrice"]').val());
formData.append('carPriceDetails' , $('input[name="carPriceDetails"]').val());
formData.append('carTax' , $('input[name="carTax"]').val());
formData.append('carTaxDetails' , $('input[name="carTaxDetails"]').val());
formData.append('carCurrency' , $('input[name="carCurrency"]').val());
formData.append('carOnline' , $('input[name="carOnline"]').val());
formData.append('carDescr' , $('input[name="carDescr"]').val());
formData.append('carBodyDescr' , $('input[name="carBodyDescr"]').val());
formData.append('carDriveTrainDescr' , $('input[name="carDriveTrainDescr"]').val());
formData.append('carExteriorDescr' , $('input[name="carExteriorDescr"]').val());
formData.append('carElectronicsDescr' , $('input[name="carElectronicsDescr"]').val());
formData.append('carSaftyFeaturesDescr' , $('input[name="carSaftyFeaturesDescr"]').val());
formData.append('carSpecialFeaturesDescr', $('input[name="carSpecialFeaturesDescr"]').val());
var fileSelect = document.getElementById('fileToUpload');
var files = fileSelect.files;
// Loop through each of the selected files.
for (var i = 0; i < files.length; i++) {
var file = files[i];
// Add the file to the request.
formData.append('files[]', file, file.name);
}
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : '/CarDealer/CarForm/createCar/carCreation.php', // the url where we want to POST
data : formData, // our data object
contentType: false,
processData: false,
success: function (data) {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
},
error: function (data) {
$('.success').fadeIn(200).hide();
$('.error').fadeOut(200).show();
}
});
return false;
});
I have no clue why this function is never getting called, I have tried everything, I have googled a lot but I am not getting it. I am searching for the error the whole day but I can't see it.
Please help me.
Your help is apreciated.
Thanks in advance.
jQuery is only aware of the elements in the page at the time that it runs, so new elements added to the DOM are unrecognized by jQuery. To combat that use event delegation, bubbling events from newly added items up to a point in the DOM that was there when jQuery ran on page load. Many people use document as the place to catch the bubbled event, but it isn't necessary to go that high up the DOM tree. Ideally you should delegate to the nearest parent that exists at the time of page load.
For instance, this button has been added to the DOM via AJAX:
<input id="saveButton" type="submit" name="submit" value="save" />
In order to properly handle this (if it is the only form with this id added to the page) is to delegate the click or submit event:
$(document).on('click', '#saveButton', function(event) {...
In addition, if you continue to add forms as you show here, you will have duplicate id's in your page and id's must be unique. Failure to make them unique will result in a number of problems.
Make sure to watch the AJAX request / response in the browser's console as outlined here to find and correct errors that you may be having.
change $('#carSaveForm').on('submit', function(event) to $('#carSaveForm').on('click','#saveButton', function(event)
Cut (ctrl+x) this line from CarMenu.php
<script charset="UTF8" src="../js/app/addCar.js"></script>
And paste (ctrl+v) the script in AddCar.php
I am struggling with getting this code to work. My intention is to be able to save the contents of a div to an html file, so that I can recall it later...
It works partially, in that if I change $data=$_POST['id'] to $data=$_POST['memory'] in readInput.php it will indeed save any text I enter into the input named 'memory' to an html file, and will correctly save the file with whatever name I give it. Where it fails is if I try to grab the data of DIV 'readDiv' and its contents $data=$_POST['id']; it will save a blank html page, with whatever name I gave it... Here is the code:
<!DOCTYPE html>
<html><head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>readInput</title>
<meta name="description" content="HTML5 web page">
<meta name="keywords" content="HTML5">
<meta name="author" content="You">
<meta charset="UTF-8">
<link href="jquery-ui.htm" rel="stylesheet" type="text/css">
<script type="text/javascript" src="jquery-latest.htm"></script>
<script name="saveMemory" type="text/javascript">
$(document).ready(function() {
$('#saveMemory').click(function() {
//e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content}
//dataType: "html" // test
});
});
});
</script>
</head>
<body onload="document.readWrite.writeInput.focus();"><!--form name.input name.focus!-->
<div id="formContainer" style="display:block">
<form name="readWrite" action="readInput.php" method="POST">
<input name="memory" placeholder="...enter text here..." type="text">
<input name="readMemory" id="readMemory" class="readMemory" placeholder="...read..." type="text">
<input id="writeInput" name="writeInput" class="writeInput" placeholder="...write..." type="text">
<input class="saveMemory" id="saveMemory" name="saveMemory" value="...saveMemory..." type="submit">
</form></div>
<div name="readDiv" id="readDiv" class="readDiv">
<div id="writeDiv" class="writeDiv" title="writeDiv">test text
<div id="topDropbox" class="topDropbox" title="topDropbox">
<img src="car.jpg">
</div></div></div>
</body></html>
readInput.php:
<?php
$writeInput = $_POST['writeInput'];
$data = $_POST['id'];
$fileName = ("memories/$writeInput.html");
$fileHandle = fopen($fileName, 'w+') or die("Cannot open file");
fwrite($fileHandle, $data);
fclose($fileHandle);
echo($fileName);
echo($data);
?>
It probably looks like a horrible hack job to you pros because I have tried so many bits of code, and I am sure I am just missing something silly, but I am at a loss...thank you anyone for any help!
This update should do the trick:
$(document).ready(function() {
$('#saveMemory').click(function(e) {
e.preventDefault();
var content = $('#readDiv').html(); // orig
//var content = document.getElementById('readDiv').value; // test
$.ajax({
type: 'POST',
url: 'readInput.php',
data: {id: content, writeInput : $('#writeInput').val()}
//dataType: "html" // test
}).done(
function( data ){
$('#result).html( data);
}
);
});
});
Changes:
Added e to the click function. It provides the function with a reference to the event object.
Uncommented e.preventDefault() so the form won't execute breaking the ajax call.
Added writeInput to the post data.
Added a callback (.done). When the request is finished this function will execute writing the responseData into writeDiv
Add the following div directly in the body tag.
<div id="result" style="background-color: #f4f4f4;width:100%;height:300px;overflow: auto"></div>
I working on a page with some JQuery and Kendo UI. This is my first JQuery project and I getting things along. However, my page refreshes for some reason. This is what I am trying to do: I have a text field where I can enter a search term and when I press a button, the query is sent to a php file and some json info will pop up. So far, I can get it to return something, but the page refreshs and all the data is gone.
code:
*<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<link href="styles/kendo.common.min.css" rel="stylesheet" />
<link href="styles/kendo.default.min.css" rel="stylesheet" />
<script src="js/jquery.min.js"></script>
<script src="js/kendo.web.min.js"></script>
</head>
<body>
<div id="example">
<form id="search">
<label for="search">Search For:</label>
<input type="text" id="txtSearch" name="q">
<button type="submit" id="submit">Find</button>
</form>
<div id="grid">
</div>
</div>
<script>
$(function() {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: "include/showsearch.php"
},
schema: {
data: "data"
}
},
columns: [{field: "id"},{field: "name"},{field: "season"}]
});
$("#submit").click(function(){
var textVal = $("#txtSearch").val();
var dynamicURL = "include/showsearch.php?show_name=" + textVal;
var grid = $("#grid").data("kendoGrid");
alert("sdf123");
grid.dataSource.transport.options.read.url = dynamicURL;
grid.dataSource.read();
alert("sdf");
});
});
</script>
</body>
</html>*
NOTE:
I used the alert functions to stop and see how the page reacts. How do I get the page from refreshing?
The reason this is happening is that the default action for your submit button is still occurring; submitting the form.
It's probably best to catch the form submission event rather than the button click as hitting Enter in a text field may also submit the form.
You will also need to prevent the default event action.
Change this
$("#submit").click(function(){
to this
$('#search').on('submit', function(e) {
e.preventDefault();
// and the rest of your code here
Just to give some context I'm a self taught programmer with no formal education or experience so apologise for my code in advance...
Code below attempts to turn a site designed for an iphone into a single page site (i.e. using ajax). I'm having an issue with multiple form submissions... looks like this is occurring when clicking the submit button on form #id2.
I've done some research and was thinking of implementing the below jquery solution for preventing multiple form submissions:
How to prevent form from submitting multiple times from client side?
and this php solution for preventing multiple form submissionson the server side:
http://www.ideologics.co.uk/programming/how-to-prevent-multiple-form-submissions-in-php
Also some sites suggest that the ajax post code should set async to false and cache to false but I'm not entirely sure of the reason and whether this is applicable in my case.
The reason I had to use the delegate function is because clicking submit on form #id1 loads a form with id#2... I tried using the on function which jquery site says supersedes the delegate function but this didn't seem to work. I'm loading version 1.8.2 using google CDN.
var startUrl = 'menu.php';
$(document).ready(function(){
loadPage(startUrl);
});
function loadPage(url) {
$('body').append('<div id="progress">Loading...</div>');
scrollTo(0,0);
if (url == startUrl) {
var element = ' #header ul';
} else {
var element = ' #content';
}
$('#container').load(url + element, function(){
var title = $('h2').html() || 'Menu';
$('h1').html(title);
$('h2').remove();
$('.leftButton').remove();
if (url != startUrl) {
$('#header').append('<div class="leftButton">Menu</div>');
$('#header .leftButton').click(function(e){
$(e.target).addClass('clicked');
loadPage(startUrl);
});
}
$("#container").delegate("a", "click", function(e){
var url = e.target.href;
if (url.match(/example.com/)) {
e.preventDefault();
loadPage(url);
}
});
$("#container").delegate("form", "submit", function(event){
event.preventDefault();
});
$('#id1').submit(function(){
var formData = $(this).serialize();
$.post('processform1.php',formData,processResults);
function processResults(data) {
$('#id1').remove();
$('#container').html(data);
}
});
$("#container").delegate("#id2", "submit", function(event){
var formData = $(this).serialize();
$.post('processform3.php',formData,processResults);
function processResults(data) {
$('#id2').remove();
$('#container').html(data);
}
event.preventDefault();
});
$('#progress').remove();
});
}
Below is the index page:
<html>
<head>
<title>Title</title>
<meta name="viewport" content="user-scalable=no, width=device-width" />
<meta name="apple-mobile-web-app-capable" content="yes" />
<meta name="apple-mobile-web-app-status-bar-style" content="black" />
<link rel="apple-touch-icon-precomposed" href="myCustomIcon.png" />
<link rel="apple-touch-startup-image" href="myCustomStartupGraphic.png" />
<link rel="stylesheet" href="iphone.css" type="text/css" media="screen" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript" src="iphone.js"></script>
</head>
<body>
<div id="header">
<h1>Menu</h1>
</div>
<div id="container"></div>
</body>
</html>
Just place this in your JS for the page the submit button is on
<script type="text/javascript">
$(document).ready(function(){
$("input[type='submit']").attr("disabled", false);
$("form").submit(function(){
$("input[type='submit']").attr("disabled", true).val("Please wait...");
return true;
})
})
</script>
You may need to use an on() event handler or do other tinkering depending on if the form is generated on page load.
I have the following php script which works flawlessly in normal circumstances (i.e. visiting the page directly):
HTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<link rel="stylesheet" type="text/css" href="css/contact_search.css" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.watermarkinput.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).click(function() {
$("#display").hide();
});
var cache = {};
$("#searchbox").keyup(function() {
var searchbox = $(this).val();
var dataString = 'searchword=' + searchbox;
if (searchbox.length < 3 ) {
$("#display").hide();
} else {
$.ajax({
type: "POST",
url: "contact_search/search.php",
data: dataString,
cache: false,
success: function(html) {
$("#display").html(html).show();
}
});
return false;
});
});
jQuery(function($) {
$("#searchbox").Watermark("Search for Group");
});
</script>
</head>
<body bgcolor="#e0e0e0">
<div class="body">
<div class="liquid-round" style="width:100%;">
<div class="top"><span><h2>Contacts List</h2></span></div>
<div class="center-content">
<img src="images/search.gif" style="float:right;" />
<input type="text" id="searchbox" maxlength="20" value="<?php echo $_SESSION['hello'];?>" />
<div id="display"></div><div style="clear:both;"></div>
</div>
<div class="bottom"><span></span></div>
</div>
<div class="liquid-round" style="width:97%;">
<div class="top"><span><h2>My Messages</h2></span></div>
<div class="center-content" style="min-height:200px;">
</div>
<div class="bottom"><span></span></div>
</div>
</div>
</body>
</html>
HOWEVER - when I add the following piece to the top of the page, the javascript/jquery functions simply stop working altogether.
<?php
session_start();
if( $_SERVER['SERVER_PORT'] == 80) {
header('Location:https://'.$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"]);
die();
}
?>
These pages require login so I need to ensure they are https protected but this error messes all that up. Any ideas what could be causing the issue?
It's probably the browser not displaying insecure (http) content on https pages, there's a simple fix though, use a scheme relative URL, like this:
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
This way you'll get http://ajax.googleapis.com/.... on the http:// version of your page and https://ajax.googleapis.com/.... on the https:// version.
Since session_start produces HTTP-Headers I recommend to do the port check before session_start.
But, these lines should not affect your JS in any circumstances, because the redirect to HTTPS is independend from the fact if your site is working via HTTPS. So, if you are not sure, remove the lines and access your page with HTTPS. Bring JS to work there. And afterwards implement the redirect.