Jquery autocomplete getting id cha - php

I made this code with jquery autocomplete its just like facebook search function now the problem is i am getting userid and i am storing it in textfield hidden but if some user presses backspace the id remains same of old user that was searched before as i am storing id on select .. plust i want to restrict the user not to go ahead other than selecing any user from database ..
here is my code
$(document).ready(function(){
$("#searchbox").autocomplete("search.php", {
width: 258,
highlight: false,
scroll: true,
scrollHeight: 350,
dataType: 'json',
parse: function(data) {
var array = new Array();
for(var i=0;i<data.length;i++)
{
array[array.length] = { data: data[i], value: data[i].name, result: data[i].name};
}
return array;
},
formatItem: function(row) {
var output = "<img class=img src='user_img/" + row.img + "'/> ";
output += "<span class=name>"+row.name+"</span><br/>";
output += "<span class=small>"+row.country+"</span><br/>";
return output;
}
}).result(function(event,item)
{
$('#temp').val(item.uid);
});
});

Used this method and it worked thanks all for not helping me :(
select: function (event, ui) {
var v = ui.item.value;
$('#MessageTo').html("Something here" + v);
$('#Hidden1').html("Something else here" + v);
// update what is displayed in the textbox
this.value = v;
return false;
}

Related

AJAX works in localhost but doesnt work in live web [duplicate]

Below code works on localhost, but not on live server.
MAIN EDIT:
Only 1 thing remains which is not working:
On AJAX success this will being executed:
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
How ever, the label(for example) is not being updated. The label needs to be updated by the score which is given (data.score_result).
Ajax code:
$('.rating').on('rating.change', function () {
var rating_id = $(this).attr('id');
var res = rating_id.split("_");
var comment = $("#comments_" + res[2]).val();
var score = $("#item_score_" + res[2]).val();
var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
+ <?php echo $query['monitor_id']; ?>
+ '&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
}
});
});
When I put alert('test'); above the $.ajax({ code it shows 'test'. When I put the alert INSIDE (just below) the $.ajax({ code, it does not show the alert.
saveScore function:
function saveScore() {
var docHeight = $(document).height();
$("body").append("<div id='overlay'></div>");
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
}
Results/info:
alert(post); gives me the correct data result.
saveScore is executed, but won't close afterwards (setTimeout).
#label and #monitoring_score are not being updated like it has to do.
using jquery-3.1.1.
I'm distraught on how to solve this. Anyone has an idea on how to fix?
Extra:
#Teemu:
Add an error handler to the AJAX call too, most likely it's the
server-side which passes an error instead of data. Or open Network tab
from the DevTools, and see if you're actually getting 200 OK message
and the data.
Edit 1: (Whole javascript code):
<script>
$(document).ready(function () {
$(".nav-tabs a").click(function () {
$(this).tab('show');
});
});
$(document).ready(function () {
$('.summernote').summernote({
height: 450, //set editable area's height
toolbar: [
['view', ['fullscreen']],
['help', ['help']]
],
codemirror: { // codemirror options
theme: 'monokai'
}
});
});
jQuery(document).ready(function () {
$('.nvt').on('click', function () {
// get the id:
var id = $(this).attr('id');
var res = id.split("_");
// Reset rating:
var rating_input = "item_score_" + res[1];
$('#' + rating_input).rating('update', 0);
var comment = $("#comments_" + res[1]).val();
var score = 0;
var post = 'controller=QualityMonitoring&task=setScore&monitor_id=' + <?php echo $query['monitor_id']; ?> +'&q=' + res[1] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(closediv, 500);
$("#label_" + res[1]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
},
error: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(closediv, 500);
$("#label_" + res[1]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
}
});
});
$('.rating').on('rating.change', function () {
var rating_id = $(this).attr('id');
var res = rating_id.split("_");
var comment = $("#comments_" + res[2]).val();
var score = $("#item_score_" + res[2]).val();
var post = 'controller=QualityMonitoring&task=setScore&monitor_id=' + <?php echo $query['monitor_id']; ?> +'&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: 'json',
beforeSend: function (data) {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(closediv, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
},
error: function(data) {
console.log("ERROR: ", data);
}
});
});
$('.savecomment').on('blur', function () {
var comment_id = $(this).attr('id');
var res = comment_id.split("_");
var commentraw = $("#comments_" + res[1]).val();
var comment = encodeURIComponent(commentraw);
var post = 'controller=QualityMonitoring&task=setComment&monitor_id=' + <?php echo $query['monitor_id']; ?> +'&q=' + res[1] + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
success: function (data) {
if (data.result == 666) {
$("#comments_" + res[1]).css("background-color", "#ffcccc");
}
}
});
});
});
$(document).on('change', '.btn-file :file', function () {
var input = $(this),
numFiles = input.get(0).files ? input.get(0).files.length : 1,
label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
input.trigger('fileselect', [numFiles, label]);
});
$(document).ready(function () {
$('.btn-file :file').on('fileselect', function (event, numFiles, label) {
var input = $(this).parents('.input-group').find(':text'),
log = numFiles > 1 ? numFiles + ' files selected' : label;
if (input.length) {
input.val(log);
} else {
if (log) alert(log);
}
});
});
function closediv() {
$(document).unbind("keyup");
$("#overlay").fadeOut("slow", function () {
$("#overlay").remove();
$(".FixedDiv").removeClass("panel-danger");
});
}
function saveScore() {
var docHeight = $(document).height();
$("body").append("<div id='overlay'></div>");
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
}
$(document).ready(function () {
var $sidebar = $(".FixedDiv"),
$window = $(window),
offset = $sidebar.offset(),
topPadding = 55;
$window.scroll(function () {
if ($window.scrollTop() > offset.top) {
$sidebar.stop().animate({
marginTop: $window.scrollTop() - offset.top + topPadding
});
} else {
$sidebar.stop().animate({
marginTop: 24
});
}
});
});
</script>
Is your PHP code valid and not throwing extra code which is messing up your JSON object. When there is a notice the JSON object becomes a string instead of a JSON string and then javascript can't parse it anymore.
Please make a new clean controller without any other code, post the data again and then check what is happening. Never return data but echo data with an exit.
Javascript and Code looks valid but somewhere else in your MVC may throw HTML code in the exit statement or generating it before you enter the controller which is required to return the data.
after function saveScore() add:
var close = function() { $('#overlay').remove(); };
after success: function (data) {} remove last comma
I think a few of the other posters are on to something about the invalid JSON,
I would add however, this is something I like to do for JSON
<?php
ob_start(); //turn on output buffering
//...other code
$debug = ob_get_clean();
$response['debug'] = $debug; //comment this when live in production
header('Content-type: application/json');
echo json_encode($response);
What this does is turn on output buffering. Which traps any output and buffers it. This includes warnings, notices, echo, and print stuff. Then it stuffs it into the response as debug and forwards it to the client.
Obviously you would not want to do this on live production server, but you can easily comment it out. It can be a security issue to include some errors and stack trace information to the client. But for debugging purposes it works great.
The problem with JSON is if you are checking the value of something somewhere (printing it) or have any notices it will muck up your JSON. For example
printed content
{"foo":"bar"}
So this takes away that problem entirely (assuming you output buffer before printing anything) like so:
{"foo":"bar", "debug":"printed content"}
And now you have valid JSON, and as a side bonus you can print out your debug info by simply doing
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
if(data.debug) console.log(data.debug);
}
});
It's simple and effective.
Hope it helps.
Try adding an error handler to your Ajax function and see what it returns:
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
},
error: function(data) {
console.log("ERROR: ", data);
}
});
Share the result with us so we can trouble shoot your issue and help you.
Are you wrapping your js code in $(document).ready() ?
A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute.
Try enclosing everything in
$(function(){
//your code here
})
Like this:
$(function(){
$('.rating').on('rating.change', function () {
var rating_id = $(this).attr('id');
var res = rating_id.split("_");
var comment = $("#comments_" + res[2]).val();
var score = $("#item_score_" + res[2]).val();
var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
+ <?php echo $query['monitor_id']; ?>
+ '&q=' + res[2] + '&item_score=' + score + '&comment=' + comment;
$.ajax({
url: "controller.php",
type: "POST",
data: post,
cache: false,
dataType: "json",
beforeSend: function () {
saveScore();
},
success: function (data) {
$(".FixedDiv").addClass("panel-danger");
setTimeout(close, 500);
$("#label_" + res[2]).html(data.score_result);
$("#monitoring_score").html(data.calculated_score);
}
});
});
function saveScore() {
var docHeight = $(document).height();
$("body").append("<div id='overlay'></div>");
$("#overlay")
.height(docHeight)
.css({
'opacity': 0.4,
'position': 'absolute',
'top': 0,
'left': 0,
'background-color': 'black',
'width': '100%',
'z-index': 5000
});
}
});
From the code you posted, the comments below and the discussion ( actually was very helpful to jump to this conclusion ) .. i can point a couple of things, but first :
adding error_reporting(0); in the begining of the controller right after <?php should solve your problem. ( if my guess is correct and it's just a notice, not an actual error)
i'm guessing that you already have this in your localhost 's php.ini and on the live server you have the default error_reporting = E_ALL, due to two different installations of php.
there's probably somewhere in the controller a notice of an undefined index or something, and php is trying to let you know by outputting this :
<br />
<b>Notice</b>: Undefined index: ...
{"calculated_score":10,"score_result":"1.75 pts"}
it starts with a < and that's where this comes from
SyntaxError: Unexpected token < in JSON at position 0
the $.ajax is unable to parse this because you have dataType="json" and this means that it is expecting a valid json back from the server, so you get the 200 status because the request was successful with no errors and console.log(data) will be empty because it was unable to parse it.
a simple way to reproduce this is creating a test php file and send the request to it instead of controller.php like :
<?php
error_reporting(0); // try with and without this line.
$data = [
'city' => 'Montreal',
'Country' => 'Canada'
];
echo $_GET['something']; // this will trigger a notice of undefined index something
echo json_encode($data);
?>
you can remove dataType:"json" and put console.log(data) in the success function and look in the console to see what the server is really telling you.
but here's something that bugs me ..
var post = 'controller=QualityMonitoring&task=setScore&monitor_id='
this looks like a query string you use for GET requests but you have type:"POST" in your ajax request ..
i don't know how you're handling this in the controller but it should be type:"GET" to send data like this, but if you want to send the data with POST then var post should be an object, ( this could be the problem as it defaults to GET when not set and in the controller there's a $_GET['task'] instead of $_POST['task'] or vise-versa ) so here's a snippet to convert the query string to a json :
function QueryStringToJSON(str) {
var pairs = str.split('&');
var result = {};
pairs.forEach(function (pair) {
pair = pair.split('=');
var name = pair[0]
var value = pair[1]
if (name.length)
if (result[name] !== undefined) {
if (!result[name].push) {
result[name] = [result[name]];
}
result[name].push(value || '');
} else {
result[name] = value || '';
}
});
return (result);
}
var string = 'controller=QualityMonitoring&task=setScore&monitor_id=5&q=blah&item_score=99&comment=hello';
var obj = QueryStringToJSON(string);
console.log(obj);
i hope this helps or at least gives you an idea, and Good Luck.

Select2 in a complex form as abstract class

I need to use the select2 object in my form. This is my form
http://i.stack.imgur.com/jVILq.jpg
There are many select html objects.
For instance If I would like to change the Customers select box into a Select2 object I have written this little snipped of code posted at jsfiddle.net but I cannot create a copy of this function for each select because it too difficult to maintain.
How have I to abstract it?
I have posted a sample here: http://jsfiddle.net/GcJgU/7/
I have already found a potential solution from the user Flip but it is not complete because I need to apply this JQuery object to all the input hidden html objects in the page.
This is an example:
$(".select2").select2({
ajax: {
url: $(this).attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = $(this).attr("field-id");
var fieldname = $(this).attr("fields-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
formatResult: function (object, container, query) {
console.log(object);
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = $(element).attr("field-id");
var fieldname = $(element).attr("fields-data");
$.ajax($(element).attr("url-searchid") + "/term/" + id, {
dataType: "json"
}).done(function (items) {
var data = {
id: items[0][fieldid],
text: items[0][fieldname]
};
callback(data);
});
}
});
Seems that $(this).attr("url-search") is not read and the search process doesn't start. I don't understand why.
Thanks guys
function select2Factory(select2) {
return {
minimumInputLength: 3,
ajax: {
url: select2.attr("callback-url"),
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var $this = $(this);
var id = select2.attr("field-id");
var fieldname = select2.attr("field-data");
results.push({
id: item[id],
text: item[fieldname]
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var fieldname = select2.attr("field-data");
$.ajax("/admin/customers/searchbyid/term/" + id, {
dataType: "json"}).done(function(items) {
var data = {id: items[0][fieldid], text: items[0][fieldname] };
callback(data);
});
}
}
}
$el = $("#customer_id");
$el.select2(select2Factory($el));
I have solved in this way thanks to Flip:
http://jsfiddle.net/GcJgU/10/
HTML:
<input type="hidden" id="customer_id" title="" required="1" class="form-control select2 select2-offscreen" url-searchid="/admin/customers/searchbyid" url-search="/admin/customers/search" fields-data="lastname firstname ( company )" field-id="customer_id" value="12" name="customer_id" tabindex="-1">
JQUERY:
function select2Factory(select2) {
return {
ajax: {
url: select2.attr("url-search") + "/term/",
dataType: 'json',
cache: true,
data: function (term, page) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function (index, item) {
var id = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = item[mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
results.push({
id: item[id],
text: output
});
});
return {
results: results
};
},
},
initSelection: function (element, callback) {
var id = $(element).val();
var fieldid = select2.attr("field-id");
var field_data = select2.attr("fields-data");
var i;
mask = field_data.split(' ');
mask_length = mask.length;
$.ajax(select2.attr("url-searchid") + "/term/" + id, {
dataType: "json"}).done(function(items) {
output = '';
for (i = 0; i < mask_length; i++) {
if (i > 0) output += ' ';
field = items[0][mask[i]];
if (typeof field === 'undefined') {
output += mask[i];
} else {
output += field;
}
}
var data = {id: items[0][fieldid], text: output };
callback(data);
});
}
};

Jquery Mockjax X-editable

I am trying to use X-editable select2 to allow users to insert tags under images. I have got it to create the tags, you can click and box pops up to edit. It will also append the new tag to the page. But, the problem is, it will not fire the mockjax/ajax call at all.
I have included the mockjax.js file in my header, jquery file is linked. I do not get any response in my browser console. I have tested mockjax on other parts of my site and they all fire correctly, just this one doesn't seem to work.
If I use something like this it works and sends the data to the console:
Working HTML code:
<p class="text-center itemName">click to edit this text</p>
Working jQuery code:
$('.itemName').editable({
type: 'text',
pk: 1,
url: 'update.php',
send: 'always'
});
Non-working jQuery:
$.fn.editable.defaults.mode = 'popover';
$('.tags').editable({
placement: 'right',
select2: {
tags: ['cake', 'cookies'],
tokenSeparators: [",", " "]
},
display: function(value) {
$.each(value,function(i){
// value[i] needs to have its HTML stripped, as every time it's read, it contains
// the HTML markup. If we don't strip it first, markup will recursively be added
// every time we open the edit widget and submit new values.
value[i] = "<span class='label'>" + $('<p>' + value[i] + '</p>').text() + "</span>";
});
$(this).html(value.join(" "));
}
});
$('.tags').on('shown', function() {
var editable = $(this).data('editable');
value = editable.value
$.each(value,function(i){
value[i] = $('<p>' + value[i] + '</p>').text()
});
});
$('[id^="tags-edit-"]').click(function(e) {
e.stopPropagation();
e.preventDefault();
$('#' + $(this).data('editable') ).editable('toggle');
});
$.mockjax({
type: 'text',
pk: 1,
url: 'update.php',
send: 'always'
});
update.php:
<?php
/*
Script for update record from X-editable.
*/
//delay (for debug only)
sleep(1);
/*
You will get 'pk', 'name' and 'value' in $_POST array.
*/
$pk = $_POST['pk'];
$name = $_POST['name'];
$value = $_POST['value'];
/*
Check submitted value
*/
if(!empty($value)) {
/*
If value is correct you process it (for example, save to db).
In case of success your script should not return anything, standard HTTP response '200 OK' is enough.
for example:
$result = mysql_query('update users set '.mysql_escape_string($name).'="'.mysql_escape_string($value).'" where user_id = "'.mysql_escape_string($pk).'"');
*/
//here, for debug reason we just return dump of $_POST, you will see result in browser console
print_r($_POST);
} else {
/*
In case of incorrect value or error you should return HTTP status != 200.
Response body will be shown as error message in editable form.
*/
//header('HTTP 400 Bad Request', true, 400);
echo "This field is required!";
}
?>
OP Found solution, here it is.
$.fn.editable.defaults.mode = 'popover';
$('.tags').editable({
placement: 'top',
select2: {
tags: ['cookies', 'pie','cake'],
tokenSeparators: [","]
},
display: function(value) {
$.each(value,function(i){
value[i] = "<span class='tagBox'>" + $('<p>' + value[i] + '</p>').text() + "</span>";
});
$(this).html(value.join(" "));
}
});
$('.tags').on('shown', function() {
var editable = $(this).data('editable');
value = editable.value
$.each(value,function(i){
value[i] = $('<p>' + value[i] + '</p>').text()
});
});
$("#content").on("click", '[id^="tags-edit-"]', function(e) {
e.stopPropagation();
e.preventDefault();
$('#' + $(this).data('editable') ).editable('toggle');
});
$('.tags').on('save', function(e, params) {
var itemId = $(this).attr('data-pk');
var dataString = 'value='+ params.newValue +'&id='+ itemId;
$.ajax({
type: 'POST',
data: dataString,
url: 'update.php',
send: 'always'
});
});

I need an expample of jQuery Autocomplete returning id and name using ajax

I need an example of how to code a jQuery autocomplete to populate product_id while showing the product_name calling an ajax page "remote.php"
<input name="product_name" id="product_name" type="text" value="" />
<input name="product_id" id="product_id" type="hidden" value="" />
remote.php:
$partial = addslashes($_POST['partial_search']);
$myDataRows = array();
$result = mysql_query ("SELECT product_id, product_name FROM products
WHERE product_name like "%$partial%");
while ($row = mysql_fetch_row($result)) {
array_push($myDataRows, $row);
}
$ret = json_encode ($myDataRows);
echo $ret;
I'm not sure how to code the jQuery autocomplete and if I need to change remote.php
thanks
ADDED LATER:
I worked out another solution:
<script type="text/javascript">
function nqi_search (type, id_name, text_name)
{
$( "#"+text_name ).autocomplete({
source: "remote.php?&t="+type,
minLength: 1,
select: function( event, ui ) {
$( "#"+id_name ).val(ui.item.id );
}
});
}
</script>
<script type="text/javascript">
jQuery(document).ready(function() {
nqi_search ("product_search", "product_id", "product_name");
// also you can have many on one page with:
nqi_search ("vendor_search", "vendor_id", "vendor_name");
});
</script>
There's one problem. it doesn't seem to work if the nqi_search function is put into a .js file. I have no idea why?
This is how I do it:
Note, I've coded a special feature where the json can flag an item as a message instead and in this way you can put messages in the list (eg I put a "Addition X items not shown" for long lists). To use the message feature, but the text in the label field and a true boolean for the message field.
To use this on the page I just have
setupAutocomplete(<id of textbox>,<path to service>);
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data) {
var msg;
if (typeof (JSON) !== 'undefined' && typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
},
error: function(msg) {
$('#error').html(msg.responseText)
}
});
// remove this to get rid of custom message handling
$.widget("custom.redcomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var self = this;
$.each(items, function(index, item) {
if (item.message)
ul.append("<li class='ui-menu-item special-red'> " + item.label + "</li>");
else
self._renderItem(ul, item)
});
}
function setupAutocomplete(inID, inURL) {
var myTB = $("[id$='_" + inID + "']");
// change redcomplete to autocomplete to get rid of message handling
myTB.redcomplete({
source: function(request, response) {
$.ajax({
url: inURL,
data: "{'filter': '" + request.term + "'}",
success: function(data) {
response($.map(data, function(item) {
return {
label: item.text,
value: item.id,
// remove this line and the , above to get rid of message handling
message: item.message
};
}));
}
})
},
delay: 500,
minLength: 3,
focus: function(event, ui) {
myTB.val(ui.item.label);
return false;
},
select: function(event, ui) {
// action for the select here.
return false;
},
open: function() {
$(this).removeClass("ui-corner-all").addClass("ui-corner-top");
},
close: function() {
$(this).removeClass("ui-corner-top").addClass("ui-corner-all");
}
});

something wrong with this jquery?

i have these two jquery scripts on my html page, one of them loads more results(like pagination), and the other one replies to users messages, just like twitter!
the replies works(inserts username into textbox), when the page is on default, but when i load more results, the loaded results wnt insert the username into the textbox!! these are the two scripts,
the replies jquery:
function insertParamIntoField(anchor, param, field) {
var query = anchor.search.substring(1, anchor.search.length).split('&');
for(var i = 0, kv; i < query.length; i++) {
kv = query[i].split('=', 2);
if (kv[0] == param) {
field.val(kv[1]);
return;
}
}
}
$(function () {
$("a.reply").click(function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").focus()
$("#inputField").val($("#inputField").val() + ' ');
e.preventDefault();
return false; // prevent default action
});
});
the loadmore jquery script:
$(function() {
//More Button
$('.more').live("click",function()
{
var ID = $(this).attr("id");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("ul.statuses").append(html);
$("#more" + ID).remove();
}
});
}
else
{
$(".morebox").html('The End');
}
return false;
});
});
EDIT: when i load more posts, and i click reply the page is refershed, so that ends up with loaded data being hidden again!!
If the reply button is being replaced by the ajax, this might be a workaround.
$(function () {
$("a.reply").live(click, function (e) {
insertParamIntoField(this,"status_id",$("#status_id"));
insertParamIntoField(this,"reply_name",$("#reply_name"));
insertParamIntoField(this, "replyto", $("#inputField"));
$("#inputField").val($("#inputField").val() + ' ').focus();
e.preventDefault();
});
});
Also... If the status_id, reply_name , replyto info is contained within your reply button, make sure these data exists for each reply button after the more button is clicked.

Categories