changing content in a div using php, html ajax - php

i am trying to make the content in the div 'test' change according to the link i click and to go where the original text is
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>An XHTML 1.0 Strict standard template</title>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<meta http-equiv="Content-Style-Type" content="text/css" />
<style type="text/css">
</style>
<script type="text/javascript">
function ajaxFunction(id, url){
var xmlHttp;
try {// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
} catch (e) {// Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange = function(){
if (xmlHttp.readyState == 4) {
//Get the response from the server and extract the section that comes in the body section of the second html page avoid inserting the header part of the second page in your first page's element
var respText = xmlHttp.responseText.split('<body>');
elem.innerHTML = respText[1].split('</body>')[0];
}
}
var elem = document.getElementById(id);
if (!elem) {
alert('The element with the passed ID doesn\'t exists in your page');
return;
}
xmlHttp.open("GET", url, true);
xmlHttp.send(null);
}
</script>
</head>
<body>
<div id="test">THIS SHOULD CHANGE</div>
link1
a href="#" value="Make Ajax Call" id="ajax" onclick="ajaxFunction('test','example2.html'); return false;">link2</a>
</body>
</html>
the div is i am trying to change is this
<div id="test">THIS SHOULD CHANGE</div>
and the links im using are these
link1
link2
any ideas on this? as this is giving me a head ache
i am using the links in a sepreat php file named menu and includeing it with
<?php include 'menu.php'; ?>
would this make a diffrence?
if i rename one the html files i get a error saying it cant be found but other than that nothing shows when there correct
!!!update!!!
ok if i change the link text from
link1
to this
<form>
<input type="button" value="Make Ajax Call" id="ajax" onclick="ajaxFunction('test','example.html');"/>
</form>
it works fine but looks really bad so is there a better way to change the link?

If you are trying to load external content into a div depending on what link was clicked? Then you could try something like the following. It is basically a striped down version of what you have and works fine for me.
<script type="text/javascript">
function loadiv(temp){
var req = new XMLHttpRequest();
req.open("GET", temp, false);
req.send(null);
var page = req.responseText;
document.getElementById("test").innerHTML = page;
};
</script>
link1
link2
<div id="test"></div>
Or use jQuery
<script type="text/javascript">
$(function(){
$('a').on('click', function(e){
e.preventDefault();
var page_url = $(this).prop('href');
$('#test').load(page_url);
});
});
</script>
Load Form 1
Load Form 2
<div id="test"></div>

I was wrong with my advice, sequence doesn't matter when accessing the outer scope.
function z() {
var a=1;
function x() {
console.log(a);
console.log(b);
}
var b=2;
x();
}
z();
I still recommend using Firefox with firebug addon or your favorite browser with a similar feature: check the javascript console for errors. You cn also check the ajax response there.

Related

return value on ajax comes back with 0

I am trying to run a conversion in Ajax. I believe from what i found online, I have most everything correct. However when I use the calculate button, It returns 0 in my results div, instead of answer. I think the issue is my numeric value isn't getting properly pulled from the text box. I need to do it like this, so changing html input types isn't an option. I am extremely new to Ajax, and don't quite know how this works. Any help would be great.
my code:
<!DOCTYPE html>
<head>
<title>Ajax Money Conversion</title>
<script>
var http = createRequestObject();
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
function moneyConversion(argLB) {
http.open('get', 'Conversion.php?pound=' +argLB);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4){
result = http.responseText.split(",");
document.getElementById("results").innerHTML = result[0];
}
}
</script>
</head>
<body>
<div>
<form name="myForm" action="#">
<h1>Enter amount of Dollars You Want To Convert to Pounds</h1>
<input type="text" name="txtCurrency" />
<input type="button" name="calcBtn" value="Calculate" id="calcBtn" onclick="moneyConversion()" />
</form>
</div>
<h1>Total</h1>
<div id="results">
</div>
</body>
</html>
my function conversion.php
<?php
$dollars=$_GET["pound"];
$conversion=($dollars * .6302);
print ("$conversion");``
?>
onclick="moneyConversion()"
should be
onclick="moneyConversion(this.form.elements.txtCurrency.value);"
otherwise you passing empty string to php

jquery collapsible theme in php doesn't work

I have a jquery code that shows for me collapsibles, when i put the code in html5 it works , But i need that code to came from a php page and being shown in a div in the html5, but it doesn't work ,here is the code that i put in the php + the sql connection and the files of jquerys .....
echo"<div data-role='collapsible'>";
while($row=mysqli_fetch_array($result))
{
echo " <h4>" .$row['Nom']. "</h4>";
echo " <p>" .$row['Nom']. "</p>";
}
echo"</div>";
but it just shows me in my div the two lines of rows ...
ADD:
This is my php file :
<?php
$host = "localhost";
$port = number;
$socket = "";
$user = "root";
$password = "";
$dbname = "database name";
$value =$_GET['value'];
$con = new mysqli($host, $user, $password, $dbname, $port, $socket);
if (!$con)
{
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"ajax_demo");
$sql="request";
$result = mysqli_query($con,$sql);
echo'<div id="accordion">';
while($row=mysqli_fetch_array($result))
{
echo" <h3>test</h3>
<div>
<p>test </p>
</div>";
}
echo" </div>";
echo"</div>";
mysqli_close($con);
?>
and the html5 file is :
<!DOCTYPE html>
<head>
<LINK rel="stylesheet" type="text/css" href="style.css">
<script src="log.js" charset="ISO-8859-1"></script>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title> réclamation Interne </title>
<script>
$(function() {
$( "#accordion" ).accordion();
});
function showUser(str)
{
var x=document.getElementById('matr');
var str = x.value;
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://IP/File name/test.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
</div>
<div class="login">
<center><h1>Datas </h1></center>
<div id="landmark-1" data-landmark-id="1">
<div>
<center>
<form name="data" >
<input type="text" id="matr" onchange="showUser()" >
</form></center>
</div>
<br>
<center>
<div id="txtHint"><b>Click here to show data</b></div></center>
</div>
<div class="login-help">
</div>
</body>
</html>
You are trying to initialize the jQuery plugin on an element that does not exist yet. I think it is important to understand what is going wrong, so you can avoid this problem in the future, since this is a very common pattern you're using.
We'll look at your code, starting with this bit...
$(function() {
$( "#accordion" ).accordion();
});
...which is executed immediately, as the page loads. Since there is no element with the id accordion at that moment, nothing happens (check your console -- probably have an error).
Then, you have the onchange code on the input element, which uses non-jQuery ajax to send a request on to your php file. The php file generates some html, wrapped in a div with the id accordion, and adds it to the page. That element has never had the accordion-related javascript applied to it, and thus sits there with no functionality.
You've got some of the concepts right, but your timing is wrong. First of all, let's use the jQuery ajax method to simply that code. Also, since you're already paying a performance/load time cost to include jQuery in your project, you should take full advantage of the functionality and use the utility element selector as well:
The new javascript
(function ($) {
// used to keep a reference to the ajax request object
var searchQuery = false;
var showUser = function (str) {
if (searchQuery != false) // if there is a pending request, cancel it
searchQuery.abort();
var searchTerm = $('#matr').val();
if (searchTerm .trim().length < 1) {
$("#txtHint").html('');
return;
}
// clean up the old accordion
if ($("#accordion").length > 0)
$("#accordion").accordion('destroy');
$("#txtHint").html('seaching...');
searchQuery = $.ajax({
'url':'http://IP/file_name/test.php?q='+searchTerm,
'success':function (response) {
searchQuery = false;
$('#txtHint').html(response);
$('#accordion').accordion();
},
'error': function () {
searchQuery = false;
$('#txtHint').html('Sorry, there was an error');
}
});
};
// add the change event to the text field, once the page loads
$(document).ready(function () {
$('#matr').change(showUser);
});
})(jQuery);
The HTML
The only change required to the HTML is that you remove the inline onClick event from the input. That said, you are using center to center text, which is not a good practice. Use css text-align:center; instead -- the less tags, the better (generally speaking).
The PHP
Nothing needs to change here, but be certain you are correctly treating the user input that you're getting from $_GET. Using mysqli_* alone does not protect against SQL injection, if you don't use it correctly. We don't see that code here, so consider this a standard disclaimer: never trust user input!
Documentation
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
jQuery UI Accordion widget - http://jqueryui.com/accordion/

Multiple form submissions

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.

how can i change the output of JavaScript to go to directly to another page instead of an alert window?

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate Zip Code</title>
<script type="text/javascript">
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
alert('Valid ZipCode');
else {
alert('yep')
}
}
</script>
</head>
<body>
<form>
<input id="txtZip" name="zip" type="text" /><br />
<input id="Button1" type="submit" value="Check My Zipcode"
onclick="IsValidZipCode(this.form.zip.value)" />
</form>
</body>
</html>
I need to use this to allow the user to go either to a page that says sorry we cannot service your area or to another page that says yes we can service your area based on wheter their zipcode is listed.
also how can i add more than one zip code in the isValid = line?
Setting window.location.href = "your url here"; answers the first part of your question.
"also how can i add more than one zip code in the isValid = line?"
If you want to stick with a regex test you can use the regex or |:
var isValid = /^(20132|20133|20200|90210|etc)$/.test(zip);
Note that I've also added ^ and $ to match the beginning and end of the entered string - the way you had it you'd also get matches if the user entered a longer string containing that code, e.g., "abc20132xyz" would match.
I'd be more inclined to do this validation server-side though.
if (isValid)
document.location.href="validzipcode.html";
else {
document.location.href="yep.html";
}
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
document.location.href="valid_zip.html";
else {
document.location.href="not_valid_zip.html";
}
}
<script type="text/javascript">
function IsValidZipCode(zip) {
var isValid = /20132/.test(zip);
if (isValid)
window.location = baseurl."/valid.php"
else {
window.location = baseurl."/invalid.php"
}
}
</script>
You can redirect it in javascript with following code , that can be put in your example instead of alert()
window.location.href = "http://stackoverflow.com";
You can try ajax for this:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Validate Zip Code</title>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function IsValidZipCode(zip){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
//alert(ajaxRequest);
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
//var ajaxDisplay = document.getElementById('ajaxDiv');
//ajaxDisplay.innerHTML = ajaxRequest.responseText;
alert(ajaxRequest.responseText);
if(ajaxRequest.responseText=="")
{
alert("sorry we cannot service your area");
}
else{
window.location = "Page.php?zip="+zip+"";
}
}
}
//var age = document.getElementById('age').value;
//var wpm = document.getElementById('wpm').value;
//var sex = document.getElementById('sex').value;
var queryString = "?zip=" + zip;
ajaxRequest.open("GET", "zip_check.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
</head>
<body>
<form name="form1" method="post">
<input id="txtZip" name="zip" type="text" /><br />
<input type="button" id="Button1" value="Check My Zipcode"
onclick="IsValidZipCode(document.form1.zip.value)" />
</form>
</body>
</html>

Get value of HTML element within PHP on same page?

In the past, whenever I needed to get the value of an html element, I would always submit a form to load a different page. Something like:
page1.php
<form name="form1" action="page2.php" method="post">
<input type="hidden" name="input1" value="value1" />
</form>
page2.php
<?php
$data = $_POST['input1'];
?>
My question is, is it possible to get the value of 'input1' on the same page (page1.php) without requiring clicking a submit button?
With jQuery:
<?php
if (isset($_POST['data'])) {
$data = $_POST['data'];
print( "data is: $data" );
return;
}
?>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery-1.6.3.js"></script>
</head>
<body>
<div>Response from server: <span id="response"></span></div>
<script type="text/javascript">
$.post('test.php',{'data': "value1"}, function (data) {
$('#response').text(data);
});
</script>
</body>
</html>
Non-jQuery IE doesn't have the XMLHttpRequest object so here is a shim for IE:
Yes, using ajax / javascript:
var formData = new FormData();
formData.append("input1", "value1");
var xhr = new XMLHttpRequest();
xhr.open("POST", "page1.php");
xhr.send(formData);
if (typeof XMLHttpRequest == "undefined") XMLHttpRequest = function() {
try {
return new ActiveXObject("Msxml2.XMLHTTP.6.0");
}
catch (e) {}
try {
return new ActiveXObject("Msxml2.XMLHTTP.3.0");
}
catch (e) {}
try {
return new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
//Microsoft.XMLHTTP points to Msxml2.XMLHTTP and is redundant
throw new Error("This browser does not support XMLHttpRequest.");
};
What for? Do you want to submit it to another file without needing to actually "submit" the form?
You use JavaScript for that.
document.form1.input1.value

Categories