I am trying to set a variable $id=$_GET["categoryID"]. I cannot get it to work. I believe it has to do with the the Ajax request. But I don't know how I have to format it so that it will work in conjunction with that request. I need the variable for a mysql query. Any help is greatly appreciated. This is over my head and have been struggling with it for days. I have tried both GET and POST. Thanks.
I have distilled the page down to this...
<!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" />
<title>Test $_GET</title>
</head>
<body>
<?php
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$id = $_GET["categoryID"];
//$id=3;
}
?>
print_r($_GET) = <?php print_r($_GET); ?>
<br />
print_r($id) = <?php print_r($id); ?>
</body>
</html>
Here is the resulting page....
<!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" />
<title>Test $_GET</title>
</head>
<body>
print_r($_GET) = Array
(
[categoryID] => 1001
)
<br />
print_r($id) =
</body>
</html>
Here is the whole page....
<?php
if (#$_REQUEST['ajax']) {
$link = $nm33;
if ($link == false)
trigger_error('Connect failed - ' . mysql_error(), E_USER_ERROR);
$connected = mysql_select_db('nm', $link);
if ($connected) {
//How do I set $id = $_GET["categoryID"] It fails to set the variable.
$id =$_GET["categoryID"];
// $id=1;
// It will work as $id=1
$results = mysql_query('select * from selectMenu where categoryID= \'' . $id . '\' AND category="' . strtolower(mysql_real_escape_string(strip_tags($_REQUEST['category']))) . '"');
//////////
$json = array();
while (is_resource($results) && $row = mysql_fetch_object($results)) {
//$json[] = '{"id" : "' . $row->id . '", "label" : "' . $row->label . '"}';
$json[] = '"' . $row->label . '"';
}
echo '[' . implode(',', $json) . ']';
die(); // filthy exit, but does fine for our example.
} else {
user_error("Failed to select the database");
}
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="js/select-chain.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
<!--
$(function () {
var cat = $('#categorySelect');
var el = $('#elementSelect');
var attr = $('#attributeSelect');
el.selectChain({
target: attr,
url: 'select-menu.php',
data: { ajax: true, anotherval: "anotherAction" }
});
// note that we're assigning in reverse order
// to allow the chaining change trigger to work
cat.selectChain({
target: el,
url: 'select-menu.php',
data: { ajax: true }
}).trigger('change');
});
//-->
</script>
<link href="selectMenu.css" rel="stylesheet" type="text/css" />
<form action="performance-models.php" method="get">
<select name="category" class="dropdown" id="categorySelect">
<option selected="selected">Select Your Vehicle</option>
<?php do { ?>
<option> <?php echo $row_rsMake['make']; ?></option>
<?php } while ($row_rsMake = mysql_fetch_assoc($rsMake)); ?>
</select>
<select name="model" class="dropdown" id="elementSelect">
<option selected="selected">Select Model</option>
<option>[none selected]</option>
</select>
<select name="appYear" class="dropdown" id="attributeSelect" >
<option selected="selected"> </option>
<option>[none selected]</option>
</select>
<input type="submit" value="Go">
</form>
<p><br />
<br />
print_r($_GET) = <?php print_r($_GET); ?> <br />
print_r($_REQUEST) = <?php print_r($_REQUEST); ?><br />
echo $_REQUEST['categoryID'] <?php echo $_REQUEST['categoryID'];?>
</p>
Here is select-chain.js
(function ($) {
$.fn.selectChain = function (options) {
var defaults = {
key: "id",
value: "label"
};
var settings = $.extend({}, defaults, options);
if (!(settings.target instanceof $)) settings.target = $(settings.target);
return this.each(function () {
var $$ = $(this);
$$.change(function () {
var data = null;
if (typeof settings.data == 'string') {
data = settings.data + '&' + this.name + '=' + $$.val();
} else if (typeof settings.data == 'object') {
data = settings.data;
data['category'] = $$.val();
data['model'] = $$.val();
data['year'] = $$.val();
}
settings.target.empty();
$.ajax({
url: settings.url,
data: data,
type: (settings.type || 'get'),
dataType: 'json',
success: function (j) {
var options = [], i = 0, o = null;
for (i = 0; i < j.length; i++) {
// required to get around IE bug (http://support.microsoft.com/?scid=kb%3Ben-us%3B276228)
o = document.createElement("OPTION");
o.value = typeof j[i] == 'object' ? j[i][settings.key] : j[i];
o.text = typeof j[i] == 'object' ? j[i][settings.value] : j[i];
settings.target.get(0).options[i] = o;
}
// hand control back to browser for a moment
setTimeout(function () {
settings.target
.find('option:first')
.attr('selected', 'selected')
.parent('select')
.trigger('change');
}, 0);
},
error: function (xhr, desc, er) {
// add whatever debug you want here.
alert("an error occurred here");
}
});
});
});
};
})(jQuery);
A $_GET parameter is passed in the URL so for this;
http://www.google.com/?q=search
The parameter $_GET['q'] would be equal to 'search'
So when you perform your AJAX request you need to specify the parameters in the URL.
EDIT:
Try getting rid of your HTTP_X_REQUESTED_WITH statements. The request is probably safe enough without those kind of checks. Just simplify it to:
if ( isset( $_GET["categoryID"] ) ) {
$id = $_GET["categoryID"];
}
There is no need for:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
You can just use:
$id = isset($_GET["categoryID"]) ? intval($_GET["categoryID"]) : 0;
Which is the same as (but shorter...):
if (isset($_GET["categoryID"]))
{
$id = intval($_GET["categoryID"]);
}
else
{
$id = 0;
}
If you want to check if a request was made via ajax, you would have to rewrite your script as the whole header section would not be needed. Instead you could call this script from your page, set a variable in the page itself and if that variable is not set in the script, it's an ajax call. Obviously this is just a simple example.
Edit: The plugin does not mention what the default type of the request is, but that could very well be POST so you could try to add type: "post" to the options of selectChain.
And to make sure that your response is well-formed json (when you get there...) I would also recommend you use json_encode, so:
echo json_encode($json);
die(); // filthy exit, but does fine for our example.
Edit 2: I just noticed another problem: Nowhere is the categoryID being added to the data section in the ajax:
You are requesting / posting to (???) : select-menu.php (notice, no query string!)
The data you are sending is: { ajax: true, anotherval: "anotherAction" } or { ajax: true}
So there is no way that categoryID is ever going to show up in select-menu.php.
The most logical thing to do, would be to add the selected category to the data section:
data: { "ajax": true, "anotherval": "anotherAction", "categoryID": cat }
and:
data: { "ajax": true, "categoryID": cat }
With jQuery you can use jQuery.get() or add a type='GET' parameter to jQuery.ajax(). Some example:
jQuery(function($) {
$.ajax({
url : 'your-page.php',
type : 'GET',
data : {
'paramName' => 'paramValue',
'foo' => 'bar'
},
success : function(data) {
// do something in the callback function
}
});
});
You need to pass the value in the jQuery.get():
$.get('yourphppage.php', { categoryID : 1234 }, function(data) {
alert(data);
});
In your php just echo right back your cateogryId to see if it is working
<?php echo $_GET['categorID'] ?>
Related
as u can see below I am trying to change part o f my page without reload all page using ajax but I am not gettign any response
I am working on local host xampp and both files are in same directory
I also tired to palce files on host and nothing happen
i did not get even an error while connecting to the database in the accdata.php file when I place them on server while there is no database
I trid a lost to change the way of ponting the url part of xmlhttp.open
like file:///C:/xml/dineshkani.xml
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
</head>
<body align="left">
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
<script>
function SendForm()
{
alert("Hello! SendForm start");
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
alert("Hello! going to send ajax");
xmlhttp.open("POST","AccData.php", true);
xmlhttp.send(document.getElementById("AccNum").value); // you want to pass the Value so u need the .value at the end!!!
alert(document.getElementById("AccNum").value);
alert("Hello! SendForm end");
}
</script>
</body>
</html>
accdata.php
<?php
alert("Hello! php start processing");
echo "start";
$AccountNumber = $_POST['AccNum'];
$conn = oci_connect('admin', 'admin', 'localhost/JDT', 'AL32UTF8');
if (!$conn) {
$e = oci_error();
trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
}
alert("Hello! connected to oracle");
$sqlstr = 'SELECT CUSTOMER_ID,CUST_NAME,PHONE1 FROM customers where CUSTOMER_ID=:AccNum';
$stid = oci_parse($conn, $sqlstr); // creates the statement
oci_bind_by_name($stid, ':AccNum', $AccountNumber); // binds the parameter
oci_execute($stid); // executes the query
echo $AccountNumber;
/**
* THIS WHILE LOOP CREATES ALL OF YOUR HTML (its no good solution to echo data out like this)
*/
while ($row = oci_fetch_array($stid, OCI_ASSOC + OCI_RETURN_NULLS)) {
echo "<tr>";
foreach ($row as $item) {
echo "<td align=center>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>";
}
echo "</tr>\n";
}
echo "</table>\n";
oci_free_statement($stid); // releases the statement
oci_close($conn); // closes the conneciton
?>
The ajax function is only sending a value rather than a post variable with associated value. Try along these lines - tidied it up a little but the important bit is the name=value in the parameters send via ajax and setting the Content-Type header often helps with stubborn xhr requests.
The javascript needn't be in the body - hence I moved that to the head section of the document.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Site Title</title>
<script>
function SendForm(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("AccNum").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open( "POST", "AccData.php", true );
xmlhttp.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xmlhttp.send( 'AccNum='+document.getElementById("AccNum").value );
}
</script>
</head>
<body>
<div>
<h4 align="left">Balance Enquiry</h4>
</div>
<form>
<div>
<label>Account Number </label>
<input id="AccNum" type="text" name="AccNumInput">
<button type="button" onclick="SendForm()">Search</button>
</div>
</form>
</body>
</html>
A basic ajax function which can be re-used merely changing the parameters when it gets called.
function ajax(method,url,parameters,callback){
var xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( xhr.readyState==4 && xhr.status==200 )callback.call( this, xhr.response );
};
var params=[];
for( var n in parameters )params.push( n+'='+parameters[n] );
switch( method.toLowerCase() ){
case 'post':
var p=params.join('&');
break;
case 'get':
url+='?'+params.join('&');
var p=null;
break;
}
xhr.open( method.toUpperCase(), url, true );
xhr.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
xhr.send( p );
}
function cbaccdata(r){ document.getElementById('AccNum').innerHTML=r; }
function sendForm(){
ajax.call( this, 'post','accdata.php',{ 'AccNum':document.getElementById("AccNum").value },cbaccdata );
}
I have two drop-down lists where the second depends on the first drop-down list selection.
I've tested getSalary and getamount and it can fetch the array but cannot be loaded to try.php.
What could have gone wrong? Here are my codes.
try.php:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery-1.11.3.min.js"></script>
<script src="jquery-ui.js"></script>
<script src="script.js"></script>
</head>
<body>
Grade and Increment
<select name="salaryid" id="salaryid" ></select>
<br>
Salary Amount:
<select name="salaryamt" id="salaryamt" ></select>
</body>
</html>
script.js:
$(document).ready(function () {
$.getJSON("getSalary.php", success = function(data) {
var options = "";
for (var i = 0; i < data.length; i++)
{
options += "<options value='" + data[i].toLowerCase() + "'>" + data[i] + "</options>";
}
$("#salaryid").append(options);
$("#salaryid").change();
});
$("#salaryid").change(function(){
$.getJSON("getAmount.php?make=" + $(this).val(), success = function(data) {
var options = "";
for (var i = 0; i < data.length; i++)
{
options += "<options value='" + data[i].toLowerCase() + "'>" + data[i] + "</options>";
}
$("#salaryamt").html("");
$("#salaryamt").append(options);
});
});
});
getSalary.php
<?php
include 'pmis_conn.php';
$qrysal = mysql_query("Select grade_incre from salary_ref where year = '2012'") or die(mysql_error());
$makes = array();
while($row = mysql_fetch_array($qrysal))
{
array_push($makes, $row['grade_incre']);
}
echo json_encode($makes);
?>
getamount.php
<?php
if (isset($_GET["make"])) {
include 'pmis_conn.php';
$make = $_GET["make"];
$qrysal = mysql_query("Select amount, year from salary_ref where grade_incre like '{$make}'") or die(mysql_error());
$amount = array();
while($row = mysql_fetch_array($qrysal))
{
//$amt = $row['amount'] + "-" + $row['year']
array_push($amount, $row['amount']);
}
echo json_encode($amount);
}
?>
Check the following things:
the GET php calls are executed as expected
the javascript is triggered as expected
Debug the GET calls:
For debugging try to use in Chrome the Developer tools Ctrl+shift+I.
In there check the Network tab to see what's going on with your ajax call.
Here the manual: https://developer.chrome.com/devtools
here a tutorial: http://discover-devtools.codeschool.com/
Debug the javascript:
Alvways from the Developer tools go on Source and put some break points on script.js.
Here the manual for debug js: https://developer.chrome.com/devtools/docs/javascript-debugging
Additional issue in the javascript:
As you can see here https://jsfiddle.net/86vjfwLe/3/ your $(this).val() is null.
You should try this method instead : jQuery get value of select onChange .
Additional issues with the html and on change:
The html you are injecting is broken. You have to replace options to optionand it should work.
I have pasted the code for index.php and jsonPhp.php.I am new to JSON and learning json with ajax.Here,I am trying to get the data from the server using json.When I click on the link SERVER DATA, The data from the server must appear without re-loading the page using jQuery/json.I have written the code but I dont get it working.Please help.
Thanks.
<head>
<title>JSON WITH PHP</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.js"
type="text/javascript"></script>
<script type="text/javascript">
< ![CDATA[
$(function () {
$('#click').click(function () {
$.post('jsonPhp.php', function (data) {
//$("#content").html(data)+'<br>';
var pushedData = jQuery.parseJSON(data);
var htmlData = "";
//loop through using jQuery
$.each(pushedData, function (i, field) {
htmlData = htmlData + '-' + field.id + ',' + field.place + ',' + field.description + '<br>';
});
$('#content').html(htmlData);
});
});
});]] >
</script>
</head>
<body>Click on the link below to get the data from the Server Dynamicallly!
<br
/>
Server Data
<div id="content"></div>
</body>
<?php
$db = mysql_connect("localhost","root","")or die(mysql_error());
mysql_select_db("places",$db) or die(mysql_error());
if(isset($_POST['place']))
$place=$_POST['place'];
if(isset($_POST['description']))
$description=$_POST['description'];
$myrows = array();
$result = mysql_query("SELECT * FROM search");
while( $row = mysql_fetch_assoc($result) ) {
$myrows[] = $row;
}
echo json_encode($myrows);
?>
Try specifying parameters, that you send with POST request, resulting something like this:
$.post('jsonPhp.php', { place:'myplace', /* other params */ }, function (data) { ...
Your jQuery post doesn't post the necessary items.
Be careful using this code.
I have this script, which is supposed to delete a row in my datagrid, from the mysql database.
Here is the code on the main page:
<?php
include('../classes/class.check.php');
$check = new Check(array(1,2));
// Open the DB connection and select the DB - creates the function getCreativePagerLyte()
include_once('configurations.php');
// Gets the data
$id=isset($_POST['id']) ? $_POST['id'] : '';
$search=isset($_POST['search']) ? $_POST['search'] : '';
$multiple_search=isset($_POST['multiple_search']) ? $_POST['multiple_search'] : array();
$items_per_page=isset($_POST['items_per_page']) ? $_POST['items_per_page'] : '';
$sort=isset($_POST['sort']) ? $_POST['sort'] : '';
$page=isset($_POST['page']) ? $_POST['page'] : 1;
$total_items=(isset($_POST['total_items']) and $_POST['total_items']>=0) ? $_POST['total_items'] : '';
$extra_cols=isset($_POST['extra_cols']) ? $_POST['extra_cols'] : array();
// Uses the creativeTable to build the table
include_once('creativeTable.php');
$ct=new CreativeTable();
// Data Gathering
$params['sql_query'] = "SELECT id, businessName, address, address2, city, state, zipCode, contactPerson, phone, email, url, page_show FROM com_listing order by id desc";
$params['search'] = $search;
$params['multiple_search'] = $multiple_search;
$params['items_per_page'] = $items_per_page;
$params['sort'] = $sort;
$params['page'] = $page;
$params['total_items'] = $total_items;
$params['items_per_page_init'] = '100';
// Layout Configurations
$params['header'] = 'ID, Business Name, Address 1, Address 2, City, State, Zip , Contact Person, Phone, Email, Website, Approved'; // If you need to use the comma use , instead of ,
$params['width'] = '';
// ***********************************************************************************
// UNCOMMENT TO TEST THE DIFFERENTS OPTIONS AND SEE THE RESULTS AND TEST SOME YOURSELF
// extra columns - array(array(col,header,width,html),array(...),...) - default: array();
$arr_extra_cols[0] = array(1,'<input type="checkbox" id="ct_check_all" name="ct_check_all" onclick="checkAll();" />','','<input type="checkbox" id="ct_check" name="ct_check[]" value="#COL3#" onclick="check();" />');
$arr_extra_cols[1] = array(2,'Edit / Delete','','<img src="images/icon-edit.gif" title="EDIT" style="margin: 0px 5px;" />
<img src="images/icon-delete.gif" class="delete" title="DELETE" />');
$params['extra_cols'] = $arr_extra_cols;
// actions select box - array(array(value,text)) - default: array();
$arr_actions[0] = array('','-- Actions --');
$arr_actions[1] = array('publish','Publish');
$arr_actions[2] = array('duplicate','Duplicate');
$arr_actions[3] = array('delete','Delete');
$params['actions'] = $arr_actions;
// url when actions changed - default: 'ctActions(\'#ID#\')'
$params['actions_url'] = 'ctActions(\'#ID#\')'; // javascript code triggered when actions is changed (you may use tags) - default
//$params['actions_url'] = 'alert(\'Actions changed\')'; // javascript code triggered when actions is changed (you may use tags)
// ***********************************************************************************
$ct->table($params);
$ct->pager = getCreativePagerLite('ct',$page,$ct->total_items,$ct->items_per_page);
// If its an ajax call
if($_POST['ajax_option']!=''){
echo json_encode($ct->display($_POST['ajax_option'],true));
exit;
}else{
$out=$ct->display();
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Lawn Care Business Directory Adminix</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<link rel="stylesheet" type="text/css" href="css/style.css">
<link rel="stylesheet" type="text/css" href="css/creative.css">
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
<script type="text/javascript" src="js/creative_table_ajax-1.3.js"></script>
<script type="text/javascript" src="js/my_javascript.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$('table#ct td .delete').click(function()
{
if (confirm("Are you sure you want to delete this row ?"))
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "deleteEntry.php",
data: data,
cache: false,
success: function()
{
parent.fadeOut('slow', function() {$(this).remove();});
}
});
}
});
// style the table with alternate colors
// sets specified color for every odd row
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
</script>
</head>
<body>
<br />
<br />
<div id="container">
<br />
<h1>Lawn Care Business Directory</h1>
<h2>Lawn Care Businesses</h2>
<?php echo $out;?>
</div>
</body>
</html>
Here is the code on for the mysql delete:
<?php
$id = $_POST['id'];
$mysql = new mysqli('localhost','*********','*********','com_listing') or die('There was a problem connecting to the database');
$stmt = $mysql->prepare('DELETE FROM data WHERE id=?');
$stmt->bind_param('i', $id);
$stmt->execute();
$stmt->close();
echo "done";
?>
(I edited out my db and password...)
Right now it just deletes the edit and delete button.
In your jQuery ajax() function, you have to actually pass it real data. You currently have data: data, which won't work. Check out the jQuery.ajax() API page for more information and look at this example from there to get an idea of what I mean:
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston"
})
The following code will not do what I hoped, that is run the Ajax function when the div ="dist" li
created by the PHP code's is clicked.
Guidance please.
<?php
// ...
$result = mysql_query($sql);
echo "<div class=\"dist\">";
echo "<ul>";
while ($row = mysql_fetch_array($result)) {
echo "<li><a href=\"devplan.php?search-n=" . $row['NAME'] .
"&" . rawurlencode($row['PLAN']) . "\"" . ">" .
$row['PLAN'] . "</a></li>";
};
echo "</ul>";
echo "</div>";
?>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
});
});
</script>
Here is a starter for ten - I've corrected some additional braces and added error handling. If you still get an error, at least you#ll be able to tell us what it is.
$.ajax({
url: 'php/dpdetails.php?q='+urlplan,
success: function (data) {
$('#Pinfo').html(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
I'd add a console.log(urlplan) right after the click event handler. make sure that returned value works if you manually enter
php/dpdetails.php?q=test&anotherVar=5
into the address bar.
What does console.log(urlplan) return?
Here is a sample piece of code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>What</title>
</head>
<body>
<?php
$anchorList = "";
$rows = array(
array(
'NAME' => 'me1'
, 'PLAN' => 'thePlan1'
)
, array(
'NAME' => 'me2'
, 'PLAN' => 'thePlan2'
)
);
$anchorList .= "<div class=\"dist\">";
$anchorList .= "<ul>";
foreach ($rows as $row) {
$anchorList .= "<li>";
$anchorList .= createAnchorTag($row['NAME'], $row['PLAN']);
$anchorList .= "</li>";
}
$anchorList .= "</ul>";
$anchorList .= "</div>";
echo $anchorList;
function createAnchorTag($name, $plan) {
return "" . $plan . "";
}
?>
</body>
</html>
<script type="text/javascript" src="../scripts/jquery-1.4.2.modified.js"></script>
<script type="text/javascript">
// Code to fill center panels with data
urlquery = location.search;
urlparts = urlquery.split('&');
urlplan = urlparts[1];
$(document).ready(function() {
$('.dist a').click(function() {
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>
In your click function you need to return false in order to override the anchor tags wanting to redirect.
[EDIT]
I believe your actually looking to parse the href attribute of the anchor tag and pass it to the Ajax, right? If so use this script:
<script type="text/javascript">
$(document).ready(function() {
$('.dist a').click(function() {
var urlquery = $(this).attr('href').val();
// regex would be better than split, could create a more generic function
var urlparts = urlquery.split('&');
var urlplan = urlparts[1];
$.ajax({
url: 'php/dpdetails.php?q=' + urlplan,
success: function (data) {
$('#Pinfo').html(data);
}
});
return false;
});
});
</script>