jquery collapsible theme in php doesn't work - php

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/

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

changing content in a div using php, html ajax

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.

AJAX calls PHP show date

Here is my html/ajax code
<head>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
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;
}
}
}
// 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;
}
}
var date = document.getElementById('Date').value;
var queryString = "?date=" + date;
ajaxRequest.open("GET", "php.php" + queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<!--showDate AJAX script -->
<!-- //Calender Script -->
<link rel="stylesheet" type="text/css" media="all" href="scripts/jsDatePick_ltr.min.css"/>
<!--JavaScript-->
<script type="text/javascript" src="scripts/jsDatePick.min.1.3.js"></script>
<!--For javascript Calendar-->
<script type="text/javascript">
window.onload = function(){
new JsDatePick({useMode:2, target:"Date", cellColorScheme:"orange", dateFormat:"%d-%m-%Y",});};
</script>
</head>
<body>
<form action="">
Date : <input type="text" size="20" id="Date" name="Date"/>
<input type="submit" name="submit" value="Submit" onClick="ajaxFunction()"/>
</form>
<div id="ajaxDiv">Time slots will be listed here...</div>
</body>
and here is my PHP code
<?php
$d = $_GET['date'];
$timestamp = strtotime($_GET['date']);
$date = date("Y-m-d",$timestamp);
echo "Time is $date";
?>
I can choose date from the calender and date will be displayed at below. Unfortunately, it doesn't work. Someone please helps me to solve my problem. I have tried many times to fix the error but still cannot done it. Almost faint.
First of all I advise you to use jQuery for Ajax handling, then why on Earth would you query the server for getting the date, passing the date itself?
Use moment.js or xdate for client-side datetime formatting.
What you want to do and what you are doing are two very different things,
1. You don't need php at all.
2. Here is full code for you to copy. http://www.java2s.com/Code/JavaScript/Development/UpdateTimepersecond.htm

Trying to get first Ajax program working, nothing dynamic happens

I'm basically copying this example from w3c schools and when you start typing in a name a few suggestions get added. No suggestions are getting added for me.
nameguess.html
<!DOCTYPE html>
<html lang="en-ca">
<head>
<meta charset="utf-8" />
<title>Ajaxing</title>
<script type="text/javascript">
<!--
function showHint(str)
{
var xmlhttp;
if (str.length == 0)
{
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","gethint.php?q="+str,true);
xmlhttp.send();
}
//-->
</script>
</head>
<body>
Hello.<br />
<form method="GET" action="">
Name: <input type="text" id="txt1" /><br />
Suggestions: <span id="txtHint"></span>
</body>
</html>
gethint.php
<?php
// Fill up array with names
$a[]="Anna";
//removed code to save space
$a[]="Vicky";
//get the q parameter from URL
$q=$_GET["q"];
//lookup all hints from array if length of q>0
if (strlen($q) > 0)
{
$hint="";
for($i=0; $i<count($a); $i++)
{
if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))
{
if ($hint=="")
{
$hint=$a[$i];
}
else
{
$hint=$hint." , ".$a[$i];
}
}
}
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response="no suggestion";
}
else
{
$response=$hint;
}
//output the response
echo $response;
?>
I have both files located in the www folder of WAMP and have the virtual server running.
I can see that others have already answered what you are trying to do but I would suggest not making your ajax requests like that example.
Instead try using the jQuery library to make your ajax requests. I was able to shorten up the code above into this.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$.get(
'gethint.php', //Code behind
{q : $("#txt1").val()}, //json string of variables to post
function(data){$("#txtHint").html(data);}, // What to do with return data
'json'); //Specify json
</script>
It will make life much easier in the long run, because it stinks to have to go through that whole mess and have to worry about cross-browser compatibility.
You can find more information here JQuery
You have missed the key press event binding:
<input type="text" id="txt1" onkeyup="showHint(this.value)">
Also, your PHP could be simplified as
<?php
if(!isset($_GET['q']) exit;
// Fill up array with names
$names = array("Anna", "Vicky");
//get the q parameter from URL
$q=$_GET["q"];
$hints = array();
foreach($names as $name) {
if (stripos($name, $q) !== -1) $hints[] = $name;
}
if(count($hints) == 0) die("no suggestion");
echo implode(', ', $hints);
?>
change this
<input type="text" id="txt1" />
to
<input type="text" id="txt1" onkeypress="showHint(this.value)"/>
and see if this helps

Appending the contents of a UNIX command to a div tag

I'm making a UNIX web-based terminal for learning purposes. So far I have made a text box and the output is being displayed. Sort of like this.
<?php
$output = shell_exec('ls');
echo "<pre>$output</pre>";
?>
Form
<html>
<head>
<link href="/css/webterminal.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
function shell_execute(str)
{
if (str.length==0)
{
document.getElementById("txtOut").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("txtOut").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","exec.php?q="+str,true);
xmlhttp.send();
}
</script>
</head
<body onLoad="setUser();">
<div class="container">
<h2>UNIX Web Based Terminal 1.0</h2>
<br />
<p><b>output</b></p>
<form>
<span id="User"></span>< <input type="text" class="textbox" onkeyup="shell_execute(this.value)" size="20" />
</form>
<div class="output">
<p><span id="txtOut"></span></p>
</div>
</div>
</body>
</html>
But I want it to look as if the page was really a terminal. When I type a command, it should store the result of the shell command, and then append it to a div tag. So as I am typing in commands, it will keep on showing the output. Just like in the UNIX terminal.
How can I append the output of the commands to a div tag?
change:
document.getElementById("txtOut").innerHTML=xmlhttp.responseText;
to:
document.getElementById("txtOut").innerHTML += xmlhttp.responseText;
On a sidenote, why are you not using any of the well established javascript frameworks?
With jQuery for example you could reduce your code to maybe 4 lines.
Edit - using jQuery:
http://api.jquery.com/jQuery.ajax/
<html>
<head>
<link href="/css/webterminal.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="http://code.jquery.com/jquery-1.5.2.min.js"></script>
<script type="text/javascript">
$(function () {
$('#cmd').bind('keydown', function (evt) {
if (evt.keyCode === 13) { // enter key
var cmdStr = $(this).val();
$.ajax({
url: 'exec.php',
dataType: 'text',
data: {
q: cmdStr
},
success: function (response) {
$('#txtOut').append(response);
}
});
}
});
});
</script>
</head>
<body>
<div class="container">
<h2>UNIX Web Based Terminal 1.0</h2>
<br />
<p><b>output</b></p>
<span id="User"></span>
<input id="cmd" type="text" class="textbox" size="20" />
<div class="output">
<p><span id="txtOut"></span></p>
</div>
</div>
</body>
</html>

Categories