yii2: call controller action in sortable jquery with ajax - ajax

I am using jquery sortable plugin to drag and drop items and setting their order. But I am unable to get the response from Ajax. I want to call the controller action from the js so that when I drag the item and drop it, then a response should come. The drag and drop functionality is working fine.
I tried this:
My View:
<div class="status-index info">
<h1><?= Html::encode($this->title) ?></h1>
<?php // echo $this->render('_search', ['model' => $searchModel]); ?>
<p>
<?= Html::a('Create Status', ['create'], ['class' => 'btn btn-success']) ?>
</p>
<ul class="sortable_status">
<?php
$items = StatusType::find()->orderBy('order')->all();
//var_dump($items);exit;
//$content = array();
foreach ($items as $item) {
echo '<li class="text-items"><label for="item'.$item->order.'"><span class="items-number">'.$item->order.'</span></label>
<label id="item'.$item->order.'" />'.$item->title.'</label>
<br/>
</li>';
}
?>
</ul>
</div>
JS:
$(function () {
var LI_POSITION = 'li_position';
$("ul.sortable_status").sortable({
update: function(event, ui) {
//create the array that hold the positions...
var order = [];
//loop trought each li...
$('.sortable_status li').each( function(e) {
//add each li position to the array...
// the +1 is for make it start from 1 instead of 0
order.push( $(this).attr('id') + '=' + ( $(this).index() + 1 ) );
});
// join the array as single variable...
var positions = order.join(';')
//use the variable as you need!
alert( positions );
// $.cookie( LI_POSITION , positions , { expires: 10 });
}
/*handle : '.handle',
update : function () {
var order = $('.sortable_status').sortable('serialize');
$(".info").load("process-sortable.php?"+order);
} */
});
});
Controller:
public function actionSortable()
{
/* foreach ($_GET['text-items'] as $position => $item)
{
$sql[] = "UPDATE `status_type` SET `order` = $position WHERE `id` = $item";
}*/
if ( isset( $_COOKIE['li_position'] ) ) {
//explode the cockie by ";"...
$lis = explode( ';' , $_COOKIE['li_position'] );
// loop for each "id_#=#" ...
foreach ( $lis as $key => $val ) {
//explode each value found by "="...
$pos = explode( '=' , $val );
//format the result into li...
$li .= '<li id="'.$pos[0].'" >'.$pos[1].'</li>';
}
//display it
echo $li;
// use this for delete the cookie!
// setcookie( 'li_position' , null );
} else {
// no cookie available display default set of lis
echo '
empty
';
}
}

why don't use an ajax call on stop ?
$("ul.sortable_status").sortable({
stop: function(event, ui) {
$.ajax({
type: "POST",
url: myUrl
data: {my-data: "any-value"}
})
.success(function(data) {
//your logic here
})
.fail(function() {
//your logic here
});
}
});
I used to define in my layout on the head tag of my html my variables as following
<head>
<script>
var myUrl = "<?php echo Url::to(['controller/action']); ?>";
</script>
</head>

Related

how to create a new div of json response array from controller

I have a case of wanting to create a div element based on the element div obtained from json response I checked in the console data successfully passed to view blade, the error is to fail add new element div based on json response obtained. Can anyone help?
my code
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
foreach ($list as $row) {
$val = array();
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}
AJAX
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (data) {
alert(data);
$('#potonganku').html(data);
},
error: function (request, status, error) {}
});
});
blade
<div id="potonganku" class="form-group row"> </div>
Best way in that case is to build markup on the client side. Return raw JSON data from controller, and then build HTML via JS.
Controller:
public function getIDpotongan($id)
{
return response()->json([
'data' => PotonganPenggajianModel::where('nip', $id)
->select('jenis_potongan', 'some_field')
->get(),
]);
}
JS
$('#nama').on('change', function () {
var optionText = $("#nama option:selected").val();
var buildHTML = function (data) {
var html = '';
for (i in data) {
html += '<h3>' + data[i].jenis_potongan + '</h3>';
// someting with data[i].some_field
}
return html;
};
$.ajax({
url: "<?php echo url('/'); ?>" + "/getidpotongan/" + optionText,
type: "GET",
dataType: "JSON",
success: function (response) {
$('#potonganku').html(buildHTML(response.data));
},
error: function (request, status, error) {}
});
});
You're creating a new empty $val = array(); array for every foreach. lets put it outside.
So your Controller would be:
public function getIDpotongan($id)
{
$data = array();
$list = PotonganPenggajianModel::where('nip', $id)->get();
$val = array();
foreach ($list as $row) {
$val[] ='<h3> ' . "'" . $row['jenis_potongan'] . "'" . '</h3>';
$data[] = $val;
}
$output = array("data" => $data);
return response()->json($output);
}

How to check the 'id' values in the controller?

my javascript code values that will print the data from ajax response
<script type="text/javascript">
function getval(get) {
var id = get.value;
// alert(id);
$.ajax({
type : "POST",
url :"http://localhost/codeIgniter/index.php/admin/ajax",
data :{id:id},
success:function(data){
$('#sub_category').html(data);
//window.location = "<?php echo site_url('admin/examdetails/form'); ?>"
}
});
}
</script>
Controller Function: that will handle ajax request
function ajax()
{
$id = $_POST['id'];
echo "<script>";
echo "alert(id);";
echo "</script>";
$this->load->model('admin_model');
$query = $this->admin_model->get_sub_details($id);
echo '<select name="sub_category" id="sub_category">';
foreach($query->result_array as $row)
{
$name = $row['name'];
$id = $row['id'];
echo '<option value="'.$id.'">'$name'</option>';
}
echo '</select>';
}

Codeigniter Calendar template modification of content

I'm using the CI Calendar. The db that I've connected it with has columns for: date, hours, category, and notes. I started out with the same format as in this tutorial from net tuts+. I can get the calendar to display the notes on the appropriate day, but I'm not sure how to split up the content section into hours, category and notes. I know I have to modify the generate calendar in the system file, but not sure how to do it.
Here's my code:
Controller:
function index($year = null, $month = null)
{
if (!$year) {
$year = date('Y');
}
if (!$month) {
$month = date('m');
}
$this->load->model('calendar_model');
if ($day = $this->input->post('day')) {
$this->calendar_model->add_calendar_data(
"$year-$month-$day",
$this->input->post('hours'),
$this->input->post('category'),
$this->input->post('notes')
);
}
$data['calendar'] = $this->calendar_model->generate($year, $month);
// Load a view in the content partial
$this->template->content->view('includes/user_navigation');
$this->template->content->view('dashboard', $data);
// Display the template
$this->template->publish();
}
Model:
<?php
class Calendar_model extends CI_Model {
var $conf;
function Calendar_model()
{
parent::__construct();
}
function get_calendar_data($year, $month) {
$query = $this->db->select()->from('calendar')
->like('date', "$year-$month", 'after')->get();
$cal_data = array();
foreach ($query->result() as $row) {
$cal_data[substr($row->date,8,2)] = $row->notes;
/* Testing purposes */
echo "<p>" . $row->date . "</p>";
echo"<p>" . $row->hours . "</p>";
echo "<p>" . $row->category . "</p>";
echo "<p>" . $row->notes . "</p>";
}
return $cal_data;
}
function add_calendar_data($date, $hours, $category, $notes) {
if ($this->db->select('date')->from('calendar')
->where('date', $date)->count_all_results()) {
$this->db->where('date', $date)
->update('calendar', array(
'date' => $date,
'hours' => $hours,
'category' => $category,
'notes' => $notes
));
} else {
$this->db->insert('calendar', array(
'date' => $date,
'hours' => $hours,
'category' => $category,
'notes' => $notes
));
}
}
function generate ($year, $month) {
$this->load->library('calendar');
$cal_data = $this->get_calendar_data($year, $month);
return $this->calendar->generate($year, $month, $cal_data);
}
}
Calendar template:
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Calendar configuration
|--------------------------------------------------------------------------
| This file will contain the settings for the calendar template library.
|
*/
$config['day_type'] = 'long';
$config['show_next_prev'] = true;
$config['next_prev_url'] = base_url('index.php/calendar/display');
$config['template'] = '
{table_open}
<table class="calendar">
{/table_open}
{heading_row_start}<tr>{/heading_row_start}
{heading_previous_cell}<th><<</th>{/heading_previous_cell}
{heading_title_cell}<th colspan="{colspan}">{heading}</th>{/heading_title_cell}
{heading_next_cell}<th>>></th>{/heading_next_cell}
{heading_row_end}</tr>{/heading_row_end}
{week_day_cell}
<th class="day_header">{week_day}</th>
{/week_day_cell}
{cal_row_start}<tr class="days">{/cal_row_start}
{cal_cell_start}<td class="day">{/cal_cell_start}
{cal_cell_content}
<div class="day_num">{day}</div>
<div class="content">
<div class="category">{category}
<div class="hours">{hours}
<div class="notes">{notes}
{content}
</div>
</div>
</div>
</div>
{/cal_cell_content}
{cal_cell_content_today}
<div class="today"><div class="day_num">{day}</div>
<div class="content">{content}</div></div>
{/cal_cell_content_today}
{cal_cell_no_content}
<div class="day_num">{day}</div>
{/cal_cell_no_content}
{cal_cell_no_content_today}
<div class="today"><div class="day_num">{day}</div></div>
{/cal_cell_no_content_today}
';
js code in my view:
$(document).ready(function(){
var date;
// === Prepare calendar === //
$('.calendar .day').click(function() {
day_num = $(this).find('.day_num').html();
$("#activityModal").modal('toggle');
$('#add-event-submit').click(function(){
var hrs = document.getElementById('activityHrs').value;
var note = document.getElementById('activityNotes').value;
var cat = document.getElementById('activityCats');
var selectedCat = cat.options[cat.selectedIndex].text;
var message = "Date: " + date + "\n";
message += "hrs: " + hrs + "\n";
message += "category: " + selectedCat + "\n";
message += "note: " + note;
message += "day num: " + day_num;
//alert(message);
if (hrs != null && selectedCat !=null && note !=null) {
$.ajax({
url: window.location,
type: 'POST',
data: {
day: day_num,
hours: hrs,
category: selectedCat,
notes: note
},
success: function(msg) {
location.reload();
}
});
}
});
});
});

Need help debugging Asynchronous AJAX call from a form in a div element to update same div with processed results based on form data

I am using a Mediawiki based website. The site is http://www.DragonFallRPG.com The widget in question is the 'Orion's Dice Box' in the left column of the site.
Not sure if that has any bearing on this but here goes. I have a custom div called 'dice' with a content destination div called 'result'. Below the 'result' div is a form for selecting a number of dice, and the number of sides for those dice. There is a processing script, which is tested working to provide a randomized result as if those dice were thrown. The problem is in the calling of one or more functions, I think. I found the AJAX method for getting the user input via 'get' somewhere on the web and no longer have any idea where it came from. I will include the files below.
dice_header.php (include file for <head> portion of webpage)
<style>
<!--[if IE] -- long buttons / button width in IE fix>
<style>.button{width:1;}</style>
<![endif]-->
</style>
<?php $javafile = dirname(__FILE__).'/ajax_engine.js'; ?>
<script type="text/javascript" src= "<?php echo $javafile ?>" ></script>
<script type="text/javascript">
function submit_dice() {
// Get form values
var no_of_dice = document.getElementById('dice').value;
var no_of_sides = document.getElementById('sides').value;
// Construct URL
<?php $handlerfile = dirname(__FILE__).'/handler.php' ?>
url = '<?php echo $handlerfile; ?>' + '?no_of_dice=' + escape(no_of_dice) + '&no_of_sides=' + escape(no_of_sides);
var xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);
alert('Handlerfile URL = ' + url + '\r\n\r\n Escape URL = ' + escape(url) + '\r\n\r\n # of dice = ' + no_of_dice + '\r\n # of Sides = ' + no_of_sides);
alert('url for ajax_get = ' + url);
ajax_get (url, 'result');
}
</script>
The above code is an include in the header of the index.php
The function call for ajax_get seems to be where it breaks down in the process in the above code. I don't know if it requires the http portion of the url or not. I don't know if the escape url is required or not. I'm hesitant to monkey with the script any further without guidance.
The code that follows is the div block for the widget I'm trying to create
dice.php (include file for my widget / div block)
<div id="result" style="text-align:center;
word-wrap: break-word;
width:100px;
font-weight:bold;
font-size:large;
border:1px blue solid;
margin:0;">
<?php
//$filename = dirname(__FILE__).'/ajax_engine.js';
//$handlerfile = dirname(__FILE__).'/handler.php';
if (file_exists($handlerfile)) {
echo "Handler file path OK";
echo 'alert(\'Handler file path = "' . $handlerfile . '"\');';
die();
} else {
echo "BAD handler file path!";
}
?>
</div>
<table border="0" cellspacing="0" cellpadding="0" style="margin:0; padding:0px;" >
<tr>
<td><select name="dice" id="dice" size="1" style="margin:0px;">
<?php
for ($i = 1; ; $i++) {
if ($i > 20) {
break;
}
if ($i == 1) {
echo "<option value=$i selected>$i</option>\n";
} else {
echo "<option value=$i>$i</option>\n";
}
}
?>
</select></td>
<td><select name="sides" id="sides" size="1" style="margin:0px;">
<option value="4">d4</option>
<option value="6">d6</option>
<option value="8">d8</option>
<option value="10">d10</option>
<option value="12">d12</option>
<option value="20" selected>d20</option>
<option value="100">d100</option>
</select>
</td>
</tr><tr>
<td colspan="2">
<input type="button" onclick="submit_dice();" value="Roll Dice" style="width:100px;" />
</td></tr>
</table>
<!--
Psuedo vs. True Random Numbers
http://www.phpfive.net/pseudo-random_php_functions_and_truly_random_number_generators_article2.htm
-->
Next follows the javascript engine I'm using to begin the AJAX functionality... Mediawiki has it's own built in AJAX - but I have no familiarity with it and tried finding a less complicated working version else where that I could tweak - resulting in this headache.
Several alert popup calls made to help with debugging, but I'm lost, and none of these alerts are actually being called... I can't tell why.
// JavaScript Document "javascript_engine.js"
// Get base url
url = document.location.href;
var base_url = "http://";
alert('base_url = ' + base_url);
xend = url.lastIndexOf("/") + 1;
var base_url = url.substring(0, xend);
var ajax_get_error = false;
alert('ajax_engine.js called');
function ajax_do (url) {
// Does URL begin with http?
alert('url.substring(0, 4) = ' + url);
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
// Create new JS element
var jsel = document.createElement('SCRIPT');
jsel.type = 'text/javascript';
jsel.src = url;
// Append JS element (therefore executing the 'AJAX' call)
document.body.appendChild (jsel);
return true;
}
function ajax_get (url, el) {
// Has element been passed as object or id-string?
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
// Valid el?
if (el == null) { return false; }
alert(url.substring(0, 4));
// Does URL begin with http?
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
// Create getfile URL
getfile_url = base_url + 'getfile.php?url=' + escape(url) + '&el=' + escape(el.id);
// Do Ajax
ajax_do (getfile_url);
return true;
}
Following is getfile.php
<?php //getfile.php -- used for addressing visual part of code
// Get URL and div
if (!isset($_GET['url'])) { die(); } else { $url = $_GET['url']; }
if (!isset($_GET['el'])) { die(); } else { $el = $_GET['el']; }
// echo 'alert(\'URL in getfile.php = \'); $url';
// Make sure url starts with http
if (substr($url, 0, 4) != 'http') {
// Set error
echo 'alert(\'Security error; incorrect URL!\');';
die();
}
// Try and get contents
$data = #file_get_contents($url);
if ($data === false) {
// Set error
echo 'alert(\'Unable to retrieve "' . $url . '"\');';
die();
}
// Escape data
$data = str_replace("'", "\'", $data);
$data = str_replace('"', "'+String.fromCharCode(34)+'", $data);
$data = str_replace ("\r\n", '\n', $data);
$data = str_replace ("\r", '\n', $data);
$data = str_replace ("\n", '\n', $data);
?>
el = document.getElementById('<?php echo $el; ?>');
el.innerHTML = '<?php echo $data; ?>';
Following is the form processor, generating the random numbers result for the AJAX output/update.
<?php // handler.php
/////////////////////////////////////////////////////////////////
// Random Dice Value Generator v1.0 //
// http://www.dragonfallrpg.com //
// Orion Johnson Copyright 2007 //
// //
// This script is used to create a random number based //
// values from the user's input //
/////////////////////////////////////////////////////////////////
/* double rolldice(int, int)
* - generates a random value based on the numbers passed as an argument
* - maximum iterations = 20 (can be changed in the user form)
* - maximum number of sides per function call = 4, 6, 8, 10, 12, 20, or 100 (can be changed)
*
* Usage: To generate a random total value as if one had thrown that many dice:
* Note: Future revisions may include the ability to add additional lines to the user form
* to mix types of simulated dice being thrown.
*
* array $no_of_dice(x-1); array value "x" taken from user form
* var $no_of_sides; value taken from user form
* var $total_value; sum of values from entire array
* echo $total_value;
*/
// Check variables
if (empty($_GET['no_of_dice'])) {
die ('<span style="color:red;">Number of dice value invalid!</span>');
}
if (empty($_GET['no_of_sides'])) {
die ('<span style="color:red;">Number of sides value invalid!</span>');
}
// seed with microseconds
function make_seed()
{
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 1000003);
}
function rolldice()
{
$total_value = 0; /* sum of values from entire array */
srand(make_seed()); /* seed random number generator // 1,000,003 is a prime number */
/* start loop structure from 0 to $no_of_dice */
for($i = 0; $i < $_GET['no_of_dice']; $i++)
{
$randnum = rand(1, $_GET['no_of_sides']);
$total_value = $total_value + $randnum;
}
/* end loop */
/* print/return results to the screen */
// echo 'Total value for dice: ' + rolldice();
return $total_value;
}
// Taken from http://www.sebflipper.com/?page=code&file=password.php
// for array iteration see also: http://www.php-scripts.com/php_diary/122799.php3
?>
If there is a simpler way to perform a div update with a random result based on form input, I'm all ears. This has been a headache for too long for me. I'm no code-head, just know enough to tinker and make some things work and understand most things when explained.
I haven't read through all the code, but since MediaWiki 1.17.0 there's a feature called ResourceLoader (if you have older version you should upgrade), which you can use for this purpose.
You can make the whole code into an extension to have it organized in a directory (let's say extensions/DiceBox). The DiceBox.php file in that folder would then be along these lines:
<?php
if( !defined( 'MEDIAWIKI' ) ) {
die();
}
$wgExtensionFunctions[] = 'DiceBoxInit';
$wgHooks['SkinTemplateToolboxEnd'][] = 'DiceBoxOnSkinTemplateToolboxEnd';
$wgResourceModules['ext.DiceBox'] = array(
'localBasePath' => dirname( __FILE__ ),
'remoteExtPath' => 'DiceBox',
'scripts' => 'ext.DiceBox.js',
'dependencies' => 'jquery'
);
function DiceBoxInit() {
global $wgOut;
$wgOut->addModules( 'ext.DiceBox' );
}
?>
<?php
function DiceBoxOnSkinTemplateToolboxEnd() {
$sides = array( 4, 6, 8, 10, 12, 20, 100 );
?>
</ul>
</div>
</div>
<div class="portlet" id="p-dicebox">
<h5>Orion's Dice Box</h5>
<div class="pBody">
<div id="dice-result" style="display: none;"></div>
<form id="dice-form">
<select name="no_of_dice">
<?php
for( $i = 1; $i <= 20; $i++ ) {
echo '<option value="', $i, '">', $i, '</option>';
}
?>
</select>
<select name="no_of_sides">
<?php
foreach( $sides as $n ) {
echo '<option value="', $n, '">d', $n, '</option>';
}
?>
</select>
<input type="button" value="Roll Dice" id="dice-roll" />
</form>
<?php
return true;
}
This code outputs the code box HTML in the sidebar and registers the following JavaScript file (ext.DiceBox.js) to be available on the page:
jQuery( document ).ready( function( $ ) {
$( '#dice-roll' ).click( function() {
$.get( mw.config.get( 'wgExtensionAssetsPath' ) + '/DiceBox/handler.php',
$( '#dice-form' ).serialize(), function( data )
{
$( '#dice-result' ).html( data ).append( '<hr />' ).show();
} );
} );
} );
This code simply uses jQuery (which is bundled with MediaWiki as of 1.16.0) to send a request to the server when the button is clicked and displays the result in the box.
In the handler.php file, there's no place where the random number gets output, so you need to add echo rolldice(); before the ?>.
Finally, to make the extensions fully work, add require_once $IP . '/extensions/DiceBox/DiceBox.php'; to the bottom of LocalSettings.php.

$ajax is being send but is missing a value

Ok, so my script tries to request from php results from mysql and load them into a div. The results are based on nid value which is has to send this value is extracted from id="record-#" the record- is removed and the # is left to be used by ajax as id for the nid.
here is the ajax data function
$(document).ready(function() {
$(".note").live('click',function() {
$("#note_utm_con").show();
$("#note_utm_nt").html("<img src='http://www.ajaxload.info/images/exemples/4.gif' />");
$.ajax({
type: "GET",
url: "_class/view.php",
data: "ajax=1&nid=" + parent.attr('id'),
success: function(html){
$("#note_utm").html(html);
$("#note_utm_nt").html("");
},
error: function (XMLHttpRequest, textStatus, errorThrown) {$("#note_utm_nt").html(errorThrown);}
});
});
$("#note_utm_con_cls").click(function() {
$("#note_utm_con").hide();
});
});
and here is the rest of the page
<div id="note_utm_con" style="display: none;">
<button id="note_utm_con_cls" style="width: 20px;float: right; padding: 2px;clear: both;">X</button>
<div id="note_utm"></div>
<div id="note_utm_nt"></div>
</div>
<?php
class notes {
var $host;
var $username;
var $password;
var $table;
public function display_notes() {
$q = "SELECT * FROM `notice` ORDER BY nid ASC LIMIT 12";
$r = mysql_query($q);
if ( $r !== false && mysql_num_rows($r) > 0 ) {
while ( $a = mysql_fetch_assoc($r) ) {
$nid = stripslashes($a['nid']);
$note = stripslashes($a['note']);
$type = stripslashes($a['type']);
$private = stripslashes($a['private']);
$date = stripslashes($a['date']);
$author = stripslashes($a['author']);
if($type == 1) {
$type = "posted a comment."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/megaphone.png";
} elseif($type == 2) {
$type = "raised a support ticket."; $icon = "http://cdn1.iconfinder.com/data/icons/basicset/help_16.png";
} elseif($type == 3) {
$type = "added new photo."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/photo.png";
} elseif($type == 4) {
$type = "updated profile details."; $icon = "http://cdn1.iconfinder.com/data/icons/Basic_set2_Png/16/user_info.png";
} else { }
$entry_display .= <<<ENTRY_DISPLAY
<ul class="list">
<li id="$nid">
<a href="javascript:;" id="$nid" onClick="retun false;" class="note">
<img src="$icon" />
$author,
$type
</a>
</li>
</ul>
ENTRY_DISPLAY;
}
} else {
$entry_display = <<<ENTRY_DISPLAY
<ul class="list">
<li>
<p>
<img src="http://cdn1.iconfinder.com/data/icons/basicset/monitor_16.png" />
Nothing to display
</p>
</li>
</ul>
ENTRY_DISPLAY;
}
return $entry_display;
}
public function connect() {
mysql_connect($this->host,$this->username,$this->password) or die("Could not connect. " . mysql_error());
mysql_select_db($this->table) or die("Could not select database. " . mysql_error());
return $this;
}
private function note_type() {
if($type == 1) { $type = "posted a comment!"; } elseif($type == 2) { $type = "raised a support ticket!"; } else { }
return $type;
}
}
?>
so when a LI with a class="note" is clicked it triggers AJAX call. The call then uses the ID in the href to extract the $nid from the id="record-
In my case it seems as AJAX is sending the request since view.php returns the fields where the data should be but it does not seem to pass much needed nid so PHP is uable to select proper nid from MySQL to use.
Can some one tell me whats wrong with it and how it can be fixed to get the id?enter code here
Your quotation marks are wrong. Try this:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),
Edit: Unless you haven't posted the full code still, you don't actually set parent anywhere. This means that you will use the window.parent object, which surprisingly enough doesn't have an id. You should use this.parentNode.id instead:
data: "ajax=1&nid=" + this.parentNode.id,
From what you've written it looks as if you're passing the parent.attr("id") replace call as a string rather than extracting the variable:
data: "ajax=1&nid=" + parent.attr('id').replace('record-',''),

Resources