Hey Developers i'm building a application form where the user input data into the different fields. One part of the application is a dynamic form from https://github.com/wbraganca/yii2-dynamicform. Now inside the dynamic form i have a dependent drop down but when i click the [+] sign the dependent drop down change data on the first row and not the second.
Here's my code.
in my controller
public function actionLists($name)
{
$countHs= Hs::find()
->where(['hscode'=> $name])
->count();
$Hs = Hs::find()
->where(['hscode'=> $name])
->all();
if($countHs > 0)
{
foreach ($Hs as $H)
{
echo "<option value='".$H->hsproduct."'> ".$H->hsproduct."</option>";
}
}else{
echo "<option> - </option>";
}
}
and my form
<div class="col-sm-6" style="width: 135px">
<?= $form->field($modelsItems, "[{$i}]hscode")->dropDownList(
ArrayHelper::map(Hs::find()->all(),'hscode','hsproduct'),
[
'prompt'=>'',
'onchange'=>
'$.get( "'.Url::toRoute('/hs/lists').'", { name: $(this).val() })
.done(function( data ) { $( "#'.Html::getInputId($modelsItems, "[{$i}]hsproduct").'" ).html( data ); } );'
])->label('HS.Code');
?>
</div>
<div class="col-sm-6" style="width: 135px">
<?= $form->field($modelsItems, "[{$i}]hsproduct")->dropDownList(
ArrayHelper::map(Hs::find()->all(),'hsproduct','hsproduct'),
[
'prompt'=>'',
])->label('HS.Product');
?>
</div>
Im a newbie sorry for my english
Updated for your case.
What I did was I declared global variable in JS file var i and assigned 0. After the first event is fired, I increase variable i by one. Now it contains 1 in memory. Next time it will take 1 and add 1 again. And so on:
var i = 0;
$(document).on('change', 'select', function(e) {
i++;
})
Note that this will only work if you choose in each row just once and you will not come back to specific row. If you want to do something like that, you should instead get element ID's number, parse to float (instead of string) and use that number to your event script.
parseFloat($('#hs-0-hscode')[0].id.split('-')[1])
Leaving below one additional solution (but not according to yours). Just in case.
Use Inspect source and find how your input fields are named (name or ID). Let's say, we have name="hs-0-hscode". This is for just Then your jQuery:
$(document).on('change', 'select', function(e) {
if ($(this)[0].id.indexOf('hscode') > 0) {
// Now you can use Ajax to get a list of items you want to show.
// Element itself can be reached: $(this).parent().parent().parent().children().eq(1);
// For example:
// var data = $.parseJSON(results);
// $.each(data, function(key, value) {
// $('#client-company_size')
// .append($("<option></option>")
// .attr("value", key)
// .text(value));
// });
}
});
Related
I've got really ambitious problem today as I want to achieve something ridiculously stupid but satisfying.
Basically, I do have a database with data for gym exercises
CREATE TABLE IF NOT EXISTS `gp_progs` (
`prog_id` int(3) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(20) NOT NULL,
`exer` varchar(250) NOT NULL,
`pic` varchar(15) NOT NULL,
PRIMARY KEY (`prog_id`),
UNIQUE KEY `prog_id` (`prog_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=9 ;
--
-- Dumping data for table `gp_progs`
--
INSERT INTO `gp_progs` (`prog_id`, `name`, `exer`, `pic`) VALUES
(1, 'ABS', 'TO DO ABS YOU NEED TO DO THIS AND THAT', 'abs.jpg'),
(3, 'Arms2', 'this is what we want', 'abs.jpg'),
(7, 'Biceps', 'curls', 'abs.jpg');
I have treated it after digging the code for many hours with this code in PHP
$jsondb = "data/prog.json";
$q = "SELECT * FROM gp_progs";
$r = #mysqli_query ($dbc, $q);
/*$json = array();
while ($row = mysqli_fetch_assoc($r)){
$json[] = $row;
}
$jsondata = json_encode($json, JSON_PRETTY_PRINT);
if(file_put_contents($jsondb, $jsondata)) {
echo 'Data successfully saved';
}
It gave me a json file from which I realy want to build AJAX functional app like this one.
JS:
$(function() { // When the DOM is ready
var times; // Declare global variable
$.ajax({
beforeSend: function(xhr) { // Before requesting data
if (xhr.overrideMimeType) { // If supported
xhr.overrideMimeType("application/json"); // set MIME to prevent errors
}
}
});
// FUNCTION THAT COLLECTS DATA FROM THE JSON FILE
function loadTimetable() { // Declare function
$.getJSON('data/events.json') // Try to collect JSON data
.done( function(data){ // If successful
times = data; // Store it in a variable
}).fail( function() { // If a problem: show message
$('#event').html('Sorry! We could not load the timetable at the moment');
});
}
loadTimetable(); // Call the function
// CLICK ON THE EVENT TO LOAD A TIMETABLE
$('#content').on('click', '#event a', function(e) { // User clicks on event
e.preventDefault(); // Prevent loading page
var loc = this.id.toUpperCase(); // Get value of id attr
var newContent = ''; // Build up timetable by
for (var i = 0; i < times[loc].length; i++) { // looping through events
newContent += '<li><span class="time">' + times[loc][i].time + '</span>';
newContent += '<a href="data/descriptions.html#';
newContent += times[loc][i].title.replace(/ /g, '-') + '">';
newContent += times[loc][i].title + '</a></li>';
}
$('#sessions').html('<ul>' + newContent + '</ul>'); // Display times on page
$('#event a.current').removeClass('current'); // Update selected item
$(this).addClass('current');
$('#details').text(''); // Clear third column
});
// CLICK ON A SESSION TO LOAD THE DESCRIPTION
$('#content').on('click', '#sessions li a', function(e) { // Click on session
e.preventDefault(); // Prevent loading
var fragment = this.href; // Title is in href
fragment = fragment.replace('#', ' #'); // Add space after#
$('#details').load(fragment); // To load info
$('#sessions a.current').removeClass('current'); // Update selected
$(this).addClass('current');
});
// CLICK ON PRIMARY NAVIGATION
$('nav a').on('click', function(e) { // Click on nav
e.preventDefault(); // Prevent loading
var url = this.href; // Get URL to load
$('nav a.current').removeClass('current'); // Update nav
$(this).addClass('current');
$('#container').remove(); // Remove old part
$('#content').load(url + ' #container').hide().fadeIn('slow'); // Add new
});
});
HTML:
<section id="content">
<div id="container">
<h2>Upcoming Events in Yorkshire</h2>
<div class="third">
<div id="event">
<a id="sh" href="sh.html"><img src="img/sheffield.fw.png" alt="Sheffield, South Yorkshire" />Sheffield</a>
<a id="hu" href="hu.html"><img src="img/hull.fw.png" alt="Hull, East Yorkshire" />Hull</a>
<a id="ls" href="ls.html"><img src="img/leeds.fw.png" alt="Leeds, West Yorkshire" />Leeds</a>
<a id="yk" href="yk.html"><img src="img/york.fw.png" alt="York, West Yorkshire" />York</a>
</div>
</div>
<div class="third">
<div id="sessions">
<p>Select an event from the left</p>
</div>
</div>
<div class="third">
<div id="details"></div>
</div>
</div><!-- #container -->
</section><!-- #content -->
<script src="js/jquery-1.11.0.min.js"></script>
<script src="js/events.js"></script>
So the result I want to see is to click on the group of exercises e.g. Arms, which will open next exercises e.g. Biceps and then onclick I want to see programme with pictures. But I cannot find out how to change JS so it will give me what I want. Spent on it already 13 hrs and still cannot find anything online.
If something is not clear please let me know as I am still learning how to use overflow.
Thanks in advance!
This is for PHP website with an use of JS, MySQL, Google API and HTML of course.
Edit:
If it was not too clear, I want to get MySQL data to JSON (which I have done already)
[
{
"prog_id": "1",
"catg": "chest",
"name": "Chest",
"exer": "Three exercises per muscle group. Chest: Bench Press (3 sets of 10), Chest cable fly(3 sets of 10) and dumbbell fly (3 sets of 10)",
"pic": "abs.jpg"
}
]
And now I want to use it in AJAX in way of: on page I want to see Groups - 'catg' which on click will open list next to group on the same page with Muscle to train 'name' which afterwards open last list next to previous also on the same page showing Descirption 'exer' and Picture/s 'pic'. Just like in the picture below:
I think your problem is that you don't know how to get data from MySQL to JSON in PHP, then get that JSON into Javascript in a form that lets you manipulate it easily.
Here's how I do it. The key here is the use of str_replace.
PHP, using my own SQL() function to retrieve the result set via fetch_all(MYSQLI_ASSOC):
$subcategorydata =
SQL("select * from subcategoryoptions order by category, subcategoryoption");
$subcategories =
str_replace('\\"','\\\\"',
str_replace("'","\'",
json_encode($subcategorydata)));
Javascript (direct rather than via ajax in my case):
var subcategories = '<?php echo $subcategories; ?>';
var jsonSubcategories = JSON.parse(subcategories);
for (var row in jsonSubcategories) { ....
EDIT: Additional code to load 2 layers, toggling the display of the lower level on/off according to user clicks. This version assumes you've pulled all the data out of MySQL in one go (I've just hard-coded it) - you would probably want to use ajax to load stuff dynamically in practice - and my code is definitely not optimal, but it should do the job.
Main div into which the data is loaded is followed by the javascript to load it. Note the hide(), show(), toggle() and set() functions and the onclick.
<div id=main></div>
<script>
function set(div, value) {
document.getElementById(div).innerHTML = value;
}
function hide(div) {
var x = document.getElementById(div);
x.style.display = "none";
}
function show(div) {
var x = document.getElementById(div);
x.style.display = "block";
}
function toggle(div) {
var x = document.getElementById(div);
if (x.style.display === "none") { show(div); } else { hide(div); }
}
var json='[{"heading":"This is the first heading","detail":"This is the first detail"},{"heading":"This is the second heading","detail":"This is the second detail"}]';
var jsonData = JSON.parse(json);
var html = '';
for (var row in jsonData)
{
html += '<div id=hdr' + row + ' onclick=toggle(\'dtl' + row + '\')>';
html += '<b>' + jsonData[row].heading + '</b></div>';
html += '<div id=dtl' + row + '>' + jsonData[row].detail + '</div>';
}
set('main','Click on the headings to toggle the detail<br>' + html);
for (var row in jsonData)
{
hide('dtl' + row);
}
</script>
you have the name of the image already in the records and you should also know, were on the server the images can be found.
You can combine this knowledge and forge a URI from path and filename
I have search results generated by a 3rd party script that I would like to add data to. I have parsed the results to get an array of id's, and queried the database for additional fields. The ajax success method receives the formatted array back, but now I'm stuck on how to get those results into the right place in the DOM.
The HTML:
<div class="ihf-results-property-info">
<div class="ihf-results-price">LIST: $2,150,000</div>
<div class="ihf-results-links"> 24 Photos
</div>
<div class="ihf-results-extra-info">
<div class="ihf-results-listingnum hidden-xs">Listing # 727938</div>
</div>
Repeat...
The last div I included in the example has the unique ID I'm using for the query. I'd like to use that to associate the ajax return with proper placement in the DOM. Here is my javascript:
jQuery(document).ready(function($) {
// grab the listings numbers so we can query the db for extra data
var listings = $('.ihf-results-listingnum').map(function() {
// grab just the digits
var listingNum = $(this).text().replace(/[^0-9]/g, '');
// add the listing number to the parent so we can target it later
$( this ).parents('.ihf-results-extra-info').parent().addClass('marketing-details-' + listingNum);
return listingNum;
// use .get to create an array of the listing numbers
}).get();
$.ajax({
type: "GET",
url: "custom/07-idx-queries.php",
data: 'mlsNums=' + listings, // looks like ?mlsNums=735383,727468,699876...
success: function(result) {
// this logic came from here: http://stackoverflow.com/questions/15311320/how-to-work-with-jquery-ajax-and-php-array-return
resultJson = $.parseJSON(result);
if (typeof resultJson == 'object') {
jsObject = eval(resultJson);
jsArray = [];
for(elem in jsObject){
jsArray.push(jsObject[elem]);
}
console.log(jsArray);
// this works as expected, except keys are 0 based
// This is where it all falls apart. I want to extract each object and stick it in the DOM in the correct place
jQuery.each(jsArray, function(key, value) {
$( this ).appendTo('.marketing-details-' + key);
});
}
else {
console.log("error occurred");
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
})
});
And the php I'm using produces the desired results from the db, with the exception that it is a numerical array. I think an associative array would work better when trying to put the results into the DOM, tha way I could use the ID's as the key and match them to the classes I added. Here is the relevant code from custom/07-idx-queries.php:
$mls_nums = explode(",",$_GET['mlsNums']);
// removed all of the conditionals to keep the question clean
$html = array();
foreach ($mls_nums as $mls_num) {
// just retreiving a single object from each row for now
$remarks = $mysqli->query("SELECT mr FROM listings WHERE ln = '$mls_num'")->fetch_object()->mr;
// format the data
$my_html = "<p class='marketing-remarks mlsnum-".$mls_num."'>$remarks</p>";
// build an array of the results - necessary?
array_push($html,$my_html);
}
// send the data back in a JSON string
echo json_encode($html);
So my goal is to query the db for up to 10 rows, and insert the results into an equal number of new divs that are children to a div with the same id number in its class. I greatly appreciate any help.
In your PHP do this:
$html[$mls_num] = $my_html;
// this isn't needed
// array_push($html,$my_html);
Now your returned data has a way to tie into the target div.
Not clear if you have control over the HTML in the first part of your example, but this would be one approach.
<div class="ihf-results-listingnum hidden-xs">Listing # 727938</div>
<div class="remarks" id="remarks_<?= $listingid; ?>"></div>
Then in the JavaScript $("#remarks_" + key).html(value);
Otherwise, you need to use jQuery to locate the div with the listing id using the :contains selector:
$("div:contains('# " + key + "')").appendTo(value);
'# " + key + "' would equate to # 1234 or whatever it is. This won't work if the same listing is on the page twice though!
Okay, here is the working success method. Thanks to LG_PDX for the cleaned up php. I eliminated the unnecessary processing as .each() appears to iterate just fine over the JSON response:
success: function(result) {
resultJson = $.parseJSON(result);
if (typeof resultJson == 'object') {
$.each(resultJson, function(key, value) {
$('.marketing-details-' + key).append( value );
});
}
},
error: function(xhr, status, error) {
console.log(xhr.responseText);
}
I want to use the jQuery UI sortable function to allow users to set an order and then on change, write it to the database and update it. Can someone write an example on how this would be done?
The jQuery UI sortable feature includes a serialize method to do this. It's quite simple, really. Here's a quick example that sends the data to the specified URL as soon as an element has changes position.
$('#element').sortable({
axis: 'y',
update: function (event, ui) {
var data = $(this).sortable('serialize');
// POST to server using $.post or $.ajax
$.ajax({
data: data,
type: 'POST',
url: '/your/url/here'
});
}
});
What this does is that it creates an array of the elements using the elements id. So, I usually do something like this:
<ul id="sortable">
<li id="item-1"></li>
<li id="item-2"></li>
...
</ul>
When you use the serialize option, it will create a POST query string like this: item[]=1&item[]=2 etc. So if you make use - for example - your database IDs in the id attribute, you can then simply iterate through the POSTed array and update the elements' positions accordingly.
For example, in PHP:
$i = 0;
foreach ($_POST['item'] as $value) {
// Execute statement:
// UPDATE [Table] SET [Position] = $i WHERE [EntityId] = $value
$i++;
}
Example on jsFiddle.
Thought this might help as well. A) it was designed to keep payload to its minimum while sending back to server, after each sort. (instead of sending all elements each time or iterating through many elements that server might chuck out) B) I needed to send back custom id without compromising the id / name of the element. This code will get the list from asp.net server and then upon sorting only 2 values will be sent back: The db id of sorted element and db id of the element next to which it was dropped. Based on those 2 values, server can easily identify the new postion.
<div id="planlist" style="width:1000px">
<ul style="width:1000px">
<li plid="listId1">List 1</li>
<li plid="listId2">List 1</li>
<li plid="listId3">List 1</li>
<li plid="listId4">List 1</li>
</ul>
<div id="pl-1"></div>
<div id="pl-2"></div>
<div id="pl-3"></div>
<div id="pl-4"></div>
</div>
<script type="text/javascript" language="javascript">
$(function () {
var tabs = $("#planlist").tabs();
tabs.find(".ui-tabs-nav").sortable({
axis: "x",
stop: function () {
tabs.tabs("refresh");
},
update: function (event, ui) {
//db id of the item sorted
alert(ui.item.attr('plid'));
//db id of the item next to which the dragged item was dropped
alert(ui.item.prev().attr('plid'));
//make ajax call
}
});
});
</script>
You're in luck, I use the exact thing in my CMS
When you want to store the order, just call the JavaScript method saveOrder(). It will make an AJAX POST request to saveorder.php, but of course you could always post it as a regular form.
<script type="text/javascript">
function saveOrder() {
var articleorder="";
$("#sortable li").each(function(i) {
if (articleorder=='')
articleorder = $(this).attr('data-article-id');
else
articleorder += "," + $(this).attr('data-article-id');
});
//articleorder now contains a comma separated list of the ID's of the articles in the correct order.
$.post('/saveorder.php', { order: articleorder })
.success(function(data) {
alert('saved');
})
.error(function(data) {
alert('Error: ' + data);
});
}
</script>
<ul id="sortable">
<?php
//my way to get all the articles, but you should of course use your own method.
$articles = Page::Articles();
foreach($articles as $article) {
?>
<li data-article-id='<?=$article->Id()?>'><?=$article->Title()?></li>
<?
}
?>
</ul>
<input type='button' value='Save order' onclick='saveOrder();'/>
In saveorder.php; Keep in mind I removed all verification and checking.
<?php
$orderlist = explode(',', $_POST['order']);
foreach ($orderlist as $k=>$order) {
echo 'Id for position ' . $k . ' = ' . $order . '<br>';
}
?>
This is my example.
https://github.com/luisnicg/jQuery-Sortable-and-PHP
You need to catch the order in the update event
$( "#sortable" ).sortable({
placeholder: "ui-state-highlight",
update: function( event, ui ) {
var sorted = $( "#sortable" ).sortable( "serialize", { key: "sort" } );
$.post( "form/order.php",{ 'choices[]': sorted});
}
});
I can change the rows by following the accepted answer and associated example on jsFiddle. But due to some unknown reasons, I couldn't get the ids after "stop or change" actions. But the example posted in the JQuery UI page works fine for me. You can check that link here.
Try with this solution: http://phppot.com/php/sorting-mysql-row-order-using-jquery/
where new order is saved in some HMTL element.
Then you submit the form with this data to some PHP script,
and iterate trough it with for loop.
Note: I had to add another db field of type INT(11) which is updated(timestamp'ed) on each iteration - it serves for script to know which row is recenty updated, or else you end up with scrambled results.
Coming from Adobe Flex I am used to having data available in an ArrayCollection and when I want to display the selected item's data I can use something like sourcedata.getItemAt(x) which gives me all the returned data from that index.
Now working in php and javascript I am looking for when a user clicks a row of data (in a table with onClick on the row, to get able to look in my data variable $results, and then populate a text input with the values from that row. My problem is I have no idea how to use javascript to look into the variable that contains all my data and just pull out one row based on either an index or a matching variable (primary key for instance).
Anyone know how to do this. Prefer not firing off a 'read' query to have to bang against the mySQL server again when I can deliver the data in the original pull.
Thanks!
I'd make a large AJAX/JSON request and modify the given data by JavaScript.
The code below is an example of an actual request. The JS is using jQuery, for easier management of JSON results. The container object may be extended with some methods for entering the result object into the table and so forth.
PHP:
$result = array();
$r = mysql_query("SELECT * FROM table WHERE quantifier = 'this_section'");
while($row = mysql_fetch_assoc($r))
$result[$row['id']] = $row;
echo json_encode($result);
JavaScript + jQuery:
container.result = {};
container.doStuff = function () {
// do something with the this.result
console.debug(this.result[0]);
}
// asynchronus request
$.ajax({
url: url,
dataType: 'json',
data: data,
success: function(result){
container.result = result;
}
});
This is a good question! AJAXy stuff is so simple in concept but when you're working with vanilla code there are so many holes that seem impossible to fill.
The first thing you need to do is identify each row in the table in your HTML. Here's a simple way to do it:
<tr class="tablerow" id="row-<?= $row->id ">
<td><input type="text" class="rowinput" /></td>
</tr>
I also gave the row a non-unique class of tablerow. Now to give them some actions! I'm using jQuery here, which will do all of the heavy lifting for us.
<script type="text/javascript">
$(function(){
$('.tablerow').click(function(){
var row_id = $(this).attr('id').replace('row-','');
$.getJSON('script.php', {id: row_id}, function(rs){
if (rs.id && rs.data) {
$('#row-' + rs.id).find('.rowinput').val(rs.data);
}
});
});
});
</script>
Then in script.php you'll want to do something like this:
$id = (int) $_GET['id'];
$rs = mysql_query("SELECT data FROM table WHERE id = '$id' LIMIT 1");
if ($rs && mysql_num_rows($rs)) {
print json_encode(mysql_fetch_array($rs, MYSQL_ASSOC));
}
Maybe you can give each row a radio button. You can use JavaScript to trigger an action on selections in the radio button group. Later, when everything is working, you can hide the actual radio button using CSS and make the entire row a label which means that a click on the row will effectively click the radio button. This way, it will also be accessible, since there is an action input element, you are just hiding it.
I'd simply store the DB field name in the td element (well... a slightly different field name as there's no reason to expose production DB field names to anyone to cares to view the page source) and then extract it with using the dataset properties.
Alternatively, you could just set a class attribute instead.
Your PHP would look something like:
<tr>
<td data-name="<?=echo "FavoriteColor"?>"></td>
</tr>
or
<tr>
<td class="<?=echo "FavoriteColor"?>"></td>
</tr>
The javascript would look a little like:
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trClick = function (e) {
var tdCollection,
i,
field = 'FavoriteColor',
div = document.createElement('div');
tdCollection = this.getElementsByTagName('td');
div.innerText = function () {
var data;
for (i = 0; i < tdCollection.length; i += 1) {
if (tdCollection[i].dataset['name'] === field) { // or tdCollection[i].className.indexOf(field) > -1
data = tdCollection[i].innerText;
return data;
}
}
}();
document.body.appendChild(div);
};
Test.addClicker = function () {
var table = document.getElementById('myQueryRenderedAsTable'),
i;
for (i = 0; i < table.tBodies[0].children.length; i += 1) {
table.tBodies[0].children[i].onclick = Test.trClick;
}
};
Test.addClicker();
}());
Working fiddle with dataset: http://jsfiddle.net/R5eVa/1/
Working fiddle with class: http://jsfiddle.net/R5eVa/2/
I am doing an AJAX request with Jquery and PHP what I am doing is looping through an array and producing a table, each loop a new is created and an id is given to it, when they click the read me link the ajax and some more content is returned, on clicking read more I want the associated table row to be removed from the table is this possible, you can see my attempt so far below.
<div id="new" class="tabdiv">
<table>
<?php
$colours = array("#f9f9f9", "#f3f3f3"); $count = 0;
if(isset($newSuggestions)) {
foreach($newSuggestions as $row) {
if($row['commentRead'] == 0) {
?>
<tr id="<?=$row['thoughtId'];?>" bgcolor="<?php echo $colours[$count++ % count($colours)];?>">
<?php
echo "<td>".substr($row['thought'], 0,50)."...</td>";
echo "<td class='read'><a href='".base_url()."thought/readSuggestion/".$row['thoughtId']."' class='readMore'>Read More</a>";
echo "</tr>";
}
}
} else {
echo "You have no new suggestions";
}
?>
</table>
$('a.readMore').click(function(){
$('#readMore').fadeIn(500);
var url = $('a.readMore').attr('href');
$.ajax({
url : url,
type : "POST",
success : function(html) {
$('#readMore').html(html)
},
complete : function() {
$('tr').remove()
}
});
return false;
});
You can get the id of the row like this:
$(this).parent().parent().attr("id")
$(this) wraps the a element, the first parent gets the td and the next one the tr. Call this inside the click callback. Make sure that the id starts with a letter; it is not allowed to start a number. To delete it, define a variable:
var row = $(this).parent().parent();
You can then delete it at the callbacks:
row.delete();
As kgiannakakis points out you'll need a reference to the element that was clicked.
To find out what went wrong, consider the following lines of your code:
$('a.readMore').click(function(){
var url = $('a.readMore').attr('href');
...
return false;
});
What you do here is add an event handler to all a elements with a readMore class.
When the link is clicked you again select all a elements with a readMore class and retreive the href attribute from the first matched element.
What you want to do is get the attribute from the element that was clicked.
$('a.readMore').click(function(){
var url = $(this).attr('href');
...
return false;
});
The same problem occurs in the success and complete handlers of your ajax request, note that you can't use this in the success/complete handlers because it will probably point to another object so you need to store it in a var before calling the ajax function.