Jquery UI Sortable Update Not Firing - php

I have been unable to get the Jquery Sortable to trigger an update when the sortable objects are moved. As a prefix - I have spent hours combing this site and the JQuery site trying to fix this problem and have yet to find a successful solution. For whatever reason the update: option does not work.
I am creating a CMS for a site, and have several AJAX scripts to dynamically update my form, as well as a TinyMCE integration. One of the AJAX calls a php script which generates the content for the Jquery Sortable to use. The Jquery Sortable is used to rearrange the positions of various pages. When it is updated it is supposed to use AJAX to run a php function that separates out the data and returns hidden fields for my form validation scripts to use. For testing purposes, right now it also returns visible text. Thank you in advance for your help
I have tried both methods in the Jquery API docs for determining when an update takes place. Here is my Jquery script.
$( function() {
$( "#sortable" ).sortable({
update: function(event, ui){
var list = new Array();
$('#sortable').find('.ui-state-default').each(function(){
var id=$(this).attr('data-id');
list.push(id);
});
var data=JSON.stringify(list);
$.ajax({
url: 'http://localhost/bpta/public2/ajax/np_order_ajax.php', // server url
type: 'POST', //POST or GET
data: {token:'reorder',data:data}, // data to send in ajax format or querystring format
datatype: 'json',
success: function(data){
$("#notes").html(data);
}
})
}
});
$( "#sortable" ).disableSelection();});
Here is a snippet of the html:
<h2>Create Page</h2>
<form action="newpage.php" method="post">
<p>Menu name:
<input type="text" onChange="" name="menu_name" value="" />
</p>
<p>Category:
<select id="category" onClick="getParents(this.value)" name="category">
<?php
$output = " ";
$cat_set = find_all_categories(false);
while ($cat = mysqli_fetch_assoc($cat_set)){
$output .= "<option value=\"";
$output .= htmlentities($cat["cat_id"]);
$output .= "\">";
$output .= htmlentities ($cat["cat_name"]);
$output .= "</option>";
}
echo $output;
?>
</select>
</p>
<div id="parent_page">
</div>
<div class ="position">
</div>
<div id = "notes">
</div>
<p>Visible:
<input type="radio" name="visible" value="0" /> No
<input type="radio" name="visible" value="1" /> Yes
</p>
<p>Content:<br />
<textarea id="editable" name="content" rows="20" cols="80">This is a Test!</textarea>
</p>
<input type="submit" id="submit" name="submit" value="Create Page" />
</form> <br />
np_order_ajax.php
if(isset($_POST['token'])){
$data=json_decode($_POST['data']);
$position =0;
$counter=1;
$query ="";
foreach($data as $key=>$val)
{
if ($val == "new"){
$position = $key;
}else if ($val != "new"){
$query.="UPDATE table_name SET position=".$counter." WHERE page_id=".$val."; ";
//save_record($val,$counter);
}
echo "Key: $key; Value: $val \n";
$counter++;}
echo "<p>Reorder working!</p>";
echo "<input type=\"hidden\" name=\"update\" id=\"update\" value=\"".$query."\">";
echo "<input type=\"hidden\" name=\"position\" id=\"position\" value=\"".$position."\">"; }
And here is how I am loading in Jquery:
<script type="text/javascript" src="../includes/jquery-3.2.1.min.js"></script>
<script type="text/javascript" src="../includes/jquery-ui.js"></script>
EDIT: #Sortable generation
<?php
echo '
<ul id="sortable">';
global $connection;
$query = "SELECT * ";
$query .= "FROM table_name ";
$query .= "WHERE category=".$_REQUEST['category'];
if ($_REQUEST['parent'] != "null" && $_REQUEST['parent'] !=null){
$query .= " AND parent_page=".$_REQUEST['parent'];
}
$query .= " ORDER BY position ASC ";
$page_set = mysqli_query($connection, $query) or die(mysqli_error($connection));
while($result = mysqli_fetch_assoc($page_set)){
$result_pg_name = $result['page_name'];
$result_id = $result['page_id'];
echo "<li class=\"ui-state-default\" data-id=\"".htmlentities($result_id)."\">".htmlentities($result_pg_name)."</li>";
//echo "<li class=\"ui-state-default\">".htmlentities($result_pg_name)."</li>";
}
echo "<li class=\"ui-state-default\" data-id=\""."new"."\">"."New Page"."</li>";
//echo ' <input type="hidden" name="pos" id="activities-input" />';
echo ' </ul>';
?>

For manually triggering events in jquery-ui sortable, instead of specifying the handler in options object, you need to bind the event handler after sortable initialization.
For example the following won't work.
$('#sortable').sortable({
update: function () {
console.log('update called');
}
});
$('#sortable').trigger('sortupdate'); // doesn't work
Following works.
$('#sortable').sortable();
$('#sortable').on('sortupdate',function(){
console.log('update called');
});
$('#sortable').trigger('sortupdate'); // logs update called.

Related

jquery ajax request no displaying php result

I have a two-part ajax form that submits data to a php file to process the request on the server-side and return the results.
Here is the HTML form:
<div id="new_loc">
<form id="loc_form" method="post" action="">
<p><b>Country Name</b><br />
<select id="country" name="country" tabindex="1">
<option value="">Choose One</option>
<?php
$cq = mysql_query("SELECT * FROM crm_countries WHERE country_status = '1' ORDER BY country_name ASC");
while($rowc = mysql_fetch_assoc($cq)) {
echo '<option value="' . $rowc['country_code'] . '">' . ucwords(strtolower($rowc['country_name'])) . '</option>';
}
?>
</select></p>
<p id="state_list"><b>State Name</b><br />
<select id="state" name="state" tabindex="2">
<option value="">Choose One</option>
</select></p>
<p><b>City Name</b><br />
<input type="text" id="city" name="city" size="30" tabindex="3" /></p>
<p><b>Zip Code</b><br />
<input type="text" id="zip" name="zip" size="7" tabindex="4" /></p>
<p><input type="submit" id="save_zip" name="save_zip" value="Save" tabindex="5" /></p>
</form>
</div>
Then here is my jquery code to send the data to the PHP file and receive the response:
$(function(){
// THE AJAX QUERY TO GET THE LIST OF STATES BASED ON THE COUNTRY SELECTION
$('#country').change(function(){
// DISPLAYS THE LOADING IMAGE
$("#state_list").html('<img src="images/Processing.gif" />');
var ctry = $('#country').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {c:ctry}
}).done(function(result) {
$("#state_list").html("<b>State Name</b><br />" + result);
});
});
// THE AJAX QUERY TO SAVE THE NEW ZIP CODE TO THE DATABASE
$('#loc_form').submit(function(){
// DISPLAYS THE LOADING IMAGE
$("#new_loc").html('<img src="images/Processing.gif" />');
var sz = $('#save_zip').val();
var ct = $('#country').val();
var st = $('#state').val();
var ci = $('#city').val();
var zc = $('#zip').val();
$.ajax({
type: "POST",
url: "ajax.php",
datatype: "text",
data: {save_zip:sz,country:ct,state:st,city:ci,zip:zc}
}).done(function(result) {
$("#new_loc").html(result);
}).fail(function() {
$("#new_loc").html('<div class="failure">An error occurred. The form could not be submitted.</div>');
});
});
});
And lastly here is the PHP code (in one file called ajax.php) that processes the code:
<?php
session_start();
require ROOT_PATH . '/config.php';
require LAN_PATH . 'english.php';
// GETS THE STATE LIST BASED ON THE COUNTRY SELECTED
if($_POST['c']) {
$sq = mysql_query("SELECT * FROM crm_states WHERE state_country = '{$_POST['c']}' ORDER BY state_name ASC");
$sRows = mysql_num_rows($sq);
if($sRows < '1') {
$result = '<i>Error: No states found!</i>';
}
else {
$result .= '<select id="state" name="state" tabindex="2">';
while($rows = mysql_fetch_assoc($sq)) {
$result .= '<option value="' . $rows['state_abbr'] . '">' . $rows['state_name'] . '</option>';
}
$result .= '</select>';
}
echo $result;
}
// SAVES THE NEW ZIP CODE TO THE DATABASE
if($_POST['save_zip']) {
$zcq = mysql_query("SELECT * FROM crm_zip_codes WHERE zip_code = '{$_POST['zip']}' AND zip_state = '{$_POST['state']}' AND zip_country = '{$_POST['country']}'");
$zcRows = mysql_num_rows($zcq);
if($zcRows == '1') {
$result = '<div class="failure">' . ZIP_EXISTS . '</div>';
}
else {
$azq = mysql_query("INSERT INTO crm_zip_codes VALUES('{$_POST['zip']}','{$_POST['city']}','{$_POST['state']}','{$_POST['country']}','','1')");
$azRows = mysql_affected_rows();
if($azRows != '1') {
$result = '<div class="failure">' . ZIP_ERROR . '</div>';
}
else {
$result = '<div class="success">' . ZIP_ADDED . '</div>';
}
}
echo $result;
}
?>
The first AJAX call seems to work just fine. The data is submitted to the PHP file and a result is returned -> Either the values for the state select form, or the text error message.
The second AJAX call is giving me problems. The information appears to be submitted, but no result (positive or negative) is retunred from the PHP file. I have tested the PHP file through direct $_GET and $_POST requests and it works fine.
I am very new to jQuery, so I don't know where I'm getting stuck. Any help is greatly appreciated.
Thanks!
You need:
$('#loc_form').submit(function(e){
e.preventDefault();
...
});
preventDefault() is needed to prevent the default submission of the form from occurring after the handler runs. The normal submission was reloading the page.
The submit event is being called and your <form> is directing the browser to nowhere action=""
Either don't use a submit button (aka use <input type="button"> or <button>) which would also require changing .submit() to .click() or use the submit button but cancel the default action.
$('#loc_form').submit(function(evt) {
var e = evt || window.event;
e.preventDefault();
...
});
Cheers

I don't have access to the HTML's id that generate from php

I using AJAX and generate html code with PHP after I get answer from the DATABASE.
first part work greate, I am laoding data from the Data base and and create table of forms.
the issue is that I can't edit the use the IDs that create I tried to change TD size or call specific IDs with JQuery but nothing happen.
HTML
<html>
<head>
<title>תמונה במתנה</title>
<meta charset="utf-8">
<link href="admin-style.css" rel="stylesheet" type="text/css">
<script src="jquery.js"></script>
<script src="admin.js"></script>
</head>
<body>
<div id="container">
<div id="customer-list">
</div>
<button type="button" id="loadbtn">טען</button>
<div id="search">
<form id="searchForm" action="admin.php" method="post">
שם פרטי:<input type="text" name="fname" id="fname">שם:
שם משפחה:<input type="text" name="lname" id="lname">
טלפון:<input type="text" name="phone" id="phone">
אימייל:<input type="text" name="email" id="email">
<input id="searchForm" type="submit" name="searchbtn" value="חפש" />
</form>
</div>
<div id="serchList">
</div>
<div id="editCustomer">
</div>
</div>
</body>
</html>
JQuery:
$(document).ready(function() {
$.ajax({
url: 'loadClient.php?submit=load',
success: function(data){
$('#customer-list').html(data);
}
}).error(function(){
alert('an alert occored');
}).success(function(){
// alert('success');
}).complete(function(){
// alert('complete');
});
$
$("#savebtn").click(function(){
alert ('hi)';
var lfname=document.getElementById('lfname').value;
var llname=document.getElementById('llname').value;;
var lemail=document.getElementById('lemail').value;;
var lcity=document.getElementById('lcity').value;;
var lphotos=document.getElementById('lphotos').value;;
var lid=document.getElementById('lid').value;;
$.ajax({
type:'POST',
url: 'loadClient.php ',
data: 'submit=save&lfname='+lfname+'&llname='+llname+'&lemail='+lemail+'&lcity='+lcity+'&lphotos='+lphotos+'&lid='+lid,
success: function(data){
$('#customer-list').html(data);
}
}).error(function(){
alert('an alert occored');
}).success(function(){
// alert('success');
}).complete(function(){
// alert('complete');
});
$.ajax({
url: 'loadClient.php?submit=load',
success: function(data){
$('#customer-list').html(data);
}
}).error(function(){
alert('an alert occored');
}).success(function(){
// alert('success');
}).complete(function(){
// alert('complete');
});
});
PHP
echo '<table border=1 cellspacing="0" cellpadding="0">';
echo '<tr>';
echo '<td width="80px">שם פרטי</td>';
echo '<td>שם משפחה</td>';
echo '<td>טלפון</td>';
echo '<td>אימייל</td>';
echo '<td>עיר</td>';
echo '<td width="150px">שעת רישום</td>';
echo '<td>מספרי תמונות</td>';
echo '<td>שמור</td>';
echo '</tr>';
$loadQuery="SELECT * FROM `claients` WHERE `eventreg_pictures` is null
OR `eventreg_pictures` like ''";
$result=mysql_query($loadQuery);
while($row= mysql_fetch_array($result)){
$client= $row;
$clients[]=$client;
echo '<tr>';
echo '<form id="loadForm" method="post" action="admin1.php">';
echo '<input type="hidden" name="lid" value="'.$client[0].'">';
echo '<td><input type="text" id="lfname" name="lfname" value="'.$client[1].'"></td>';
echo '<td><input type="text" id="llname" name="llname" value="'.$client[2].'"></td>';
echo '<td><input type="text" id="lphone" name="lphone" value="'.$client[3].'"></td>';
echo '<td><input type="text" id="lemail" name="lemail" value="'.$client[4].'"></td>';
echo '<td><input type="text" id="lcity" name="lcity" value="'.$client[5].'"></td>';
echo '<td>'.$client[7].'</td>';
echo '<td><input type="text" id="lphotos" name="lphotos"></td>';
echo '<td><input type="submit" id="savebtn" name="savebtn" value="שמור"></td>';
echo '</form>';
echo '</tr>';
}
echo '</table>';
}else echo'error';
If I'm right, the problem is that Your #savebtn doesn't exist when You define the $("#savebtn").click handler.
Try this instead:
$("#savebtn").ready(function(){
$("#savebtn").click(function() //...Continue Your code...
});
A few things:
'1. You're mixing up jQuery and javascript, when jQuery is simpler and shorter to type. This line:
`var lfname=document.getElementById('lfname').value;`
can be replaced with this line:
var lfname=$('#lfname').val();
'2. Your PHP is looping through results returned by a mysql search, but you are using the same ID for all returned rows. This is a no-no. Each ID must be unique. Edit your PHP code to add a unique number to each id name, based on row.
Try Something like:
$counter = 0;
$loadQuery="SELECT * FROM `claients` WHERE `eventreg_pictures` is null
OR `eventreg_pictures` like ''";
$result=mysql_query($loadQuery);
while($row= mysql_fetch_array($result)){
$client= $row;
$clients[]=$client;
echo '<tr>';
echo '<form id="loadForm-' .$counter. '" method="post" action="admin1.php">';
echo '<input type="hidden" name="lid" value="'.$client[0].'">';
echo '<td><input type="text" id="lfname-' .$counter. '" name="lfname" value="'.$client[1].'"></td>';
That way, in your jQuery, you can check to see - for example - which field was just completed:
$('[id^=lfname]').blur(function() {
var xx = $(this).attr('id');
alert('You edited input: ' + xx);
var arrYY = xx.split('-'); //turn xx into an array, separated at each hyphen
var yy = arrYY[1]; //The number part of the array
alert('The number part of this element is: [' +yy+ ']');
});
'3. Note that you can also select elements by class, so you could add a class to your lfname input fields, catch the blur (or focus, or etc) event on any element with that class, and determine exactly which input it was:
echo '<td><input type="text" id="lfname-' .$counter. '" name="lfname" value="'.$client[1].'"></td>';
$('.lfname').blur(function() {
var xx = $(this).attr('id');
alert('You edited input: ' + xx);
});
'4. To be clear, the reason nothing happens when you reference specific IDs on your page is because you have more than one element with that same ID. IDs must be unique. See #2 above to make the IDs unique, or just use the class attribute.
שלם

Select form with javascript

I would like to get select form with variable amount of fields. To achive this first I connect to db and converting data from php to javascript. Then i got array (wynik) with values, but when i try to print it i get empty select form and all values shown next to it. There is my javascript function:
<script language="javascript">
function addInput() {
document.getElementById('text').innerHTML += "<select name='add' /><br />";
for (i=0;i<wynik.length;i++)
{
document.getElementById('text').innerHTML += "<option value=" + "wynik[i]" + " />" + wynik[i] + "</option />";
}
document.getElementById('text').innerHTML += "</select />";
}
</script>
And HTML code:
<form name="add" action="add_form.php" method="post">
<div id="text">
</div>
<br>
<input type="submit" value="Submit" />
</form>
<input type="button" onclick="addInput()" name="add" value="Add value" />
Please help me to put that into form.
The browser will attempt to fix the DOM each time you write HTML to it, consequently you cannot write just a start tag to innerHTML.
Build all your HTML up in a string and then insert it in one go.
Better yet, use createElement, appendChild and friends instead.
Perhaps you need to remove <br /> after <select name='add' /> . Also </select /> does not need a / in the end (it has it in the begining) - </select>.
Another approach you can try with ajax:
<!-- Script -->
<script type="text/javascript">
$(function(){
$("#add").on('click', function(){
$.ajax({
url : 'ajax.php',
type : 'POST',
success : function(resp){
$("#backend").html(resp);
},
error : function(resp){
}
});
});
});
</script>
<!-- HTML -->
<div id="text"><select id="backend" name=""></select></div>
<input type="button" id="add" value="Add value" />
<!-- Backend ajax.php -->
<?php
#your query here to fetch $wynik
$str = "";
foreach($wynik as $value){
$str .= '<option value="'.$value.'">'.$value.'</option>';
}
return $str;

Display records on load page using jquery ajax in php

I want to load data when page is loaded but if i try doing that then delete function doesn't work and whenever I insert the effect should be seen in table without refreshing page Please check my code what changes to be done in this
index.php
<script src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(e) {
$("#Submit").click(function(e) {
var name = $('#name').val();
var message=$('#message').val();
if($(":text").val().length==0)
{
$(":text").after('<span class="error">Field cannot be empty</span>');
$('#name').addClass('error');
$('#message').addClass('error');
return;
}
else{
$('#name').removeClass('error');
$('#message').removeClass('error');
//$('#propspectDiv').removeClass('error');
$('#propspectDiv').html('Submitting your Request.<img src="ajax.gif" />');
$.ajax({
url : 'data.php',
data:{
"name" : name,
"message" : message
},
success : function(data){
window.setTimeout(function(){
$('#propspectDiv').html('Your Name is added to our records');
$('#data').css("display","block");
$('#data').html(data);
}, 2000);
},
complete:function(){
$('#myform').each(function(){
this.reset();
});
}
});
}
});
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
});
</script>
</head>
<body>
<form id="myform">
<div id="wrapper">
Name : <input type="text" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
<input type="button" value="Submit" id="Submit" />
<div id="propspectDiv"></div>
<table id="data" border="1" style="display:none;"></table>
</div>
</form>
</body>
data.php
<?php
$name = $_REQUEST['name'];
$message = $_REQUEST['message'];
include('connection.php');
$sql = "INSERT INTO login (username,message) VALUES ('$name','$message')";
if (!mysql_query($sql,$con))
{
die('Error: ' . mysql_error());
}
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td id=td1>
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
echo '</tr>';
$i++;
}
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: index.php");
}
?>
Looks like your grabbing the ID attribute of the link, but not setting it...
$("a").click(function() {
$.post('delete.php',{ id: $(this).attr("id")});
});
There is no ID attribute on your existing delete link:
<a href=delete.php?id=".$row['id']."&type=Delete>Delete</a></td>";
Also - you probably don't need to have the link href pointing to delete.php as its irrelevant when the jquery click event does all the work.
Also, because you are inserting the html (including the delete method) via jquery you may need to use the "on" event
I'm doing this off the cuff so the code may have some minor bugs but I believe this is the path you want to take...
Revised it might look like this:
JQUERY
$("a").on("click", function(e) {
e.preventDefault();
$.post('delete.php',{ id: $(this).attr("id")});
return false;
});
LINK
echo"<td id=td1>
<a id='".$row['id']."' href='#'>Delete</a>";
echo '</tr>';
couple things to note...
1 - above i'm not actually VERIFYING the record was deleted before I remove the appropriate table row - you may want to implement something to check this
2 - an alternative to removing the table row would be to just update the table in general by repulling the data and outputting it - if you know what i mean

Beginning jQuery help

I'm trying to make a simple MySQL Admin thing with php and jQuery. I've never used jQuery so my code is probably quite lol-worthy. The problem I'm having with the code is that when I click the button, nothing happens. I know the even fires because if I open the html file in firefox (not going to the url, using the file:/// thing) and click it, it shows my php code in the box I want the returned content to go into. The first thing i'm trying to do is connect to the database specified and return a list of the tables. Heres my code
index.html
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
var Server = 'None';
var Username = 'None';
var Password = 'None';
var Database = 'None';
$("#connect").click(function() {
Server = $('#server').val();
Username = $('#username').val();
Password = $('#password').val();
Database = $('#database').val();
loadTables();
});
function loadTables() {
$.get("display.php", { server: Server, username: Username, password: Password, database: Database, content: "tables" },
function(data){
html = "<ul>";
$(data).find("table").each(function() {
html = html + "<li>" + $(this).text() + "</li>";
});
html = html + "</ul>";
$('#content').html(html);
}
);
}
</script>
</head>
<body>
<center>
<div class='connection'>
<form name='connectForm'>
Server: <input type='text' size='30' id='server' />
Username: <input type='text' id='username' />
Password: <input type='password' id='password' />
Database: <input type='text' id='database' />
<input type='button' id='connect' value='Connect' />
</form>
</div>
<div id='content'>
</div>
</center>
</body>
</html>
display.php
<?
mysql_connect($_GET['server'], $_GET['username'], $_GET['password'])
or die("Error: Could not connect to database!<br />" . mysql_error());
mysql_select_db($_GET['database']);
$content = $_GET['content'];
if ($content == "tables") {
$result = mysql_query("show tables");
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$xml .= "<tables>";
while ($row = mysql_fetch_assoc($result)) {
$xml .= "<table>" . $row['Tables_in_blog'] . "</table>";
}
$xml .= "</tables>";
header('Content-type: text/xml');
echo $xml;
}
?>
EDIT:
I have updated the code according to a mix of a few answers, but I'm still having the same problem.
Ok, firstly don't do that and by "that" I mean:
Don't put DB connection details in Javascript; and
Don't use input from the user without sanitizing it. You're just asking to be hacked.
That being said, your main problem seems to be that $(#content) should be $("#content"). Also putting an onclick on the button isn't really the jQuery way. Try:
<body>
<div class='connection'>
<form name='connectForm'>
Server: <input type='text' id="server" size='30' name='server' />
Username: <input type='text' id="username" name='username' />
Password: <input type='password' id="password" name='password' />
Database: <input type='text' id="database" name='database' />
<input type='button' id="connect" value='Connect' />
</form>
</div>
<div id='content'></div>
<script type="text/javascript" src="/jquery-1.3.1.js"></script>
<script type="text/javascript">
$(function() {
$("#connect").click(function() {
$.get(
"display.php",
{
server: $("#server").val(),
username: $("#username").val(),
password: $("#password").val(),
database: $("#database").val(),
content: "tables"
},
function(data) {
$("#content").html("<ul></ul>");
$(data).find("table").each(function() {
$("#content ul").append("<li>" + $(this).text() + "</li>");
});
}
);
});
});
</script>
</body>
Edit: minor corrections to the above and tested with this script:
<?
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<root>
<?
$tables = array('one', 'two', 'three', 'four');
foreach ($tables as $table) {
echo " <table>$table</table>\n";
}
?>
</root>
I hope this helps. I noticed three things about your code:
1) display.php doesn't close the tag.
2) You refer to the 'content' div using $(#content), which throws a Javascript error. Make sure to encapsulate this selector in quotes, like $('#content').
3) I'm not sure about "$("table", xml).text()". Instead, used the very cool find('tag').each() syntax to walk through the XML response. This worked for me as a replacement for your function(data) statement:
function(data) {
htmlTable = '<ul>';
$(data).find('table').each(function(){
htmlTable = htmlTable + '<li>' + $(this).text() + '</li>'; });
htmlTable = htmlTable + '</ul>'
$('#content').html(htmlTable);
});
Here is a working piece of code:
<script type='text/javascript'>
function connect() {
$.ajax({
url:'display.php',
type: 'POST',
dataType:'xml',
success: {
server: $('#server').val()||'None',
username: $('#username').val()||'None',
password: $('#password').val()||'None',
database: $('#database').val()||'None',
content: "tables"
},
function(data){
$('#content').html('<ul></ul>');
var contentUL = $('#content>ul');
$(data).find('table').each(function(){
$('<li></li>').html($(this).html()).appendTo(contentUL);
});
},
'xml'
});
}
</script>
</head>
<body>
<center>
<div class='connection'>
<form id="connectForm" name='connectForm'>
Server: <input id="server" type='text' size='30' name='server' />
Username: <input id="username" type='text' name='username' />
Password: <input id="password" type='password' name='password' />
Database: <input id="database" type='text' name='database' />
<input type='button' onclick='connect();' value='Connect' />
</form>
</div>
<div id='content'>
</div>
</center>
</body>
But in my opinion it's better and easier to use JSON instead of xml, it's more easier to work with it (last lines of get function):
function(data){
$('#content').html('<ul></ul>');
var contentUL = $('#content>ul');
$.each(data.tables, function(){
$('<li></li>').html(this).appendTo(contentUL);
});
},
'json');
Also you can use jquery.form plugin to submit a form. It also can update specified elements using response, example:
$(document).ready(function() {
$('#connectForm').ajaxForm({
target: '#content'
});
});
I'm not sure exactly what the question is. But you don't need the $(function() {}) inside your $.get callback - passing a function to $() actually binds an event handler to the "ready" event which only gets called when your page is first loading. You just provide a function that takes your XML as a parameter (here you have it as "data" but reference it as "xml"?) and use it. I'd start by reading http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype, and http://docs.jquery.com/Events/ready#fn. Also, install Firebug and check out the error console to see where your JavaScript is having problems - you can go to the "Script" tab and set breakpoints to see how your code is executing to get a feeling for where things are going wrong.
You should use the jQuery.forms.js plugin.
http://malsup.com/jquery/form/
$(#content) // This is definitely a problem.
Selectors must be strings, so $("#content") would be correct.

Categories