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.
Related
so I am loading a portion of a page using jquery/ajax.
On the page the user sees, there is a "menu" where they select the date of the signup form they want to see. All the forms are hosted on another page, each one inside a div id'd with the respective date of the form. When the user clicks and item on the menu, there is an ajax call that displays the correct form on the user's page, pulling it from the other page by it's parent div and id.
The plugin I am using for the signup forms (it is a Wordpress site) has the page reload when you click Sign up, which then takes you to a form to fill out. I have it so that the user's page does not reload, but via ajax shows the form. This all works great - the only problem now is when the user clicks to submit the form. This should be a normal form submit not using ajax, as I am not sure how to modify the plugin code to utilize it. For some reason, the form is never actually submitted although the user's page does reload.
*NOTE: I am currently using the same exact signup form for each date, but once it is functional it will be a different signup form for each. This should not effect any functionality.
link to page user sees: summitsharks.net/volunteer-signup-page
link to page forms are hosted on: summitsharks.net/formhost
jquery/ajax code:
;(function($){
var ahref1;
$(document).ready(function(){
$(document).on('click', '.entry-content li a', function(e){
e.preventDefault();
ahref1 = $(this).attr('href');
$('#formloader').load('/formhost ' + ahref1);
return false;
});
});
$(document).ready(function(){
$(document).on('click', '.entry-content #formloader a', function(e){
e.preventDefault();
var ahref2 = $(this).attr('href');
$('#formloader').load(ahref2 + ' ' + ahref1);
return false;
});
});
})(jQuery);
PHP code of file that (I think) handles form submit:
http://pastebin.com/PeXB4Afi
I am looking for a solution that successfully signs the user up. If somebody knows how to alter the plugin code to accept ajax submission, or normal submission that actually works, either one is perfectly fine with me.
Thanks a lot for looking through and thanks in advance for your help!
The form is expected to be posted from it's original URL, including the HTTP GET parameters ?sheet_id=1&task_id=1&date=2016-06-30. Updating the form's action attribute to make it post to the proper URL can be done by changing
$('#formloader').load(ahref2 + ' ' + ahref1);
to
$('#formloader').load(ahref2 + ' ' + ahref1, function() {
$('#formloader form').attr("action", ahref2 + ' ' + ahref1 );
});
However, using AJAX to post the form, this can be skipped:
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
})
The utility method formdata (see code snippet below) converts jQuery's serializeArray() result to a proper hash.
In the working example below, I've moved the installation of form click handlers into the .load completion handler, rather than relying on jQuery to fire a second document ready event after injecting the form.
;jQuery(function($) {
$('.entry-content li a').off('click').on('click', function(e) {
var ahref1 = $(this).attr('href');
$('#formloader').load( "/formhost " + ahref1, function() {
$('.entry-content #formloader a').off('click').on('click', function(e) {
e.preventDefault();
var ahref = $(this).attr('href') + ' ' + ahref1;
$('#formloader').load( ahref, function() {
$("#formloader form").on('submit', function(e) {
e.preventDefault();
$.ajax( {
url: ahref,
type: 'POST',
data: $.param( formdata( $(this) ) ),
success:function(data,status,jqXHR) { $("#formloader").html( data ) }
});
return false;
})
});
return false;
});
});
return false;
});
});
function formdata(form) {
var data = {};
for ( var i in d = form.serializeArray() )
data[d[i].name] = d[i].value;
return data;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
UPDATE: Here is a code snippet that can be pasted in the browser's Javascript console:
$ = jQuery;
$('.menu-volunteermenu-container li a').off('click').on('click', function (e) {
loadFormSelector($(this).attr('href'));
return false;
});
$('#formloader').on('load', function(){console.log("FORMLOADER UPDATD")});
function loadFormSelector(ahref1)
{
console.log("Loading form selector");
$('#formloader').load('/formhost ' + ahref1, function ()
{
console.log('form selector loaded');
$('.entry-content #formloader a').off('click').on('click', function (e)
{
e.preventDefault();
loadForm(ahref1, $(this).attr('href') );
return false;
});
});
}
function loadForm(ahref1, ahref2)
{
var ahref = ahref2 + ' ' + ahref1;
console.log('Loading form', ahref);
$('#formloader').load(ahref, function () {
console.log('form loaded', arguments);
$('#formloader form').on('submit', function (e) {
e.preventDefault();
$.ajax({
url: ahref,
type: 'POST',
data: $.param(formdata($(this))),
success: function (data, status, jqXHR) {
$('#formloader').html( $(data).find( ahref1 ) )
}
});
return false;
});
$('#formloader a').on('click', function () {
loadFormSelector(ahref1);
});
return false;
});
}
function formdata(form) {
var data = {
};
for (var i in d = form.serializeArray())
data[d[i].name] = d[i].value;
return data;
}
It is refactored to show the 2-layer approach more clearly.
I have created a button on my website when it is clicked, I sent data on some php file using ajax and return the results. The code I am using is below,
My Goal :
When that button is clicked for the first time. I want to send the data on some php file using ajax and return the results, and
When it is clicked for the second time, I just want to hide the content, and
When it is clicked for the third time, I just want to show the container without calling the ajax again.
jQuery:
$(function() {
$('#click_me').click(function(){
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
});
});
Html :
<input type="button" id="click_me" value="Click Me"/>
<div id="container"></div>
The jQuery way would be like this:
$(function() {
$('#click_me').one('click', function() {
$.ajax({
// ... other params ...,
success: function(result) {
$('#container').html(result).show('fast');
$('#click_me').click(function() {
$('#container').toggle('fast');
});
});
});
});
});
http://api.jquery.com/one/
http://api.jquery.com/toggle/
You can use the counter
http://forum.jquery.com/topic/making-a-number-counter
(function () {
var count = 0;
$('table').click(function () {
count += 1;
if (count == 2) {
// come code
}
});
})();
JQuery Mouse Click counter
Working Example of your code :-
http://jsfiddle.net/2aQ2g/68/
Something like this should do the trick...
$("#click_me").click(function(){
var $btn = $(this);
var count = ($btn.data("click_count") || 0) + 1;
$btn.data("click_count", count);
if ( count == 1 ) {
$.ajax({
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php"
})
}
else if ( count == 2 ) {
$('#container').hide('fast');
}
else {
$('#container').show('fast');
$btn.unbind("click");
}
return false;
});
One way to do it would be to add a class call count using jQuery every time the user clicks on the button (http://api.jquery.com/addClass/) and you can get the count value in the handler and based on that you can handle the click appropriately.
You can do this by defining a simple variable counting the clicks.
$(function() {
var clickCount = 1; //Start with first click
$('#click_me').click(function(){
switch(clickCount) {
case 1: //Code for the first click
// I am just pasting your code, if may have to change this
var container = $('#container').css('display');
var id = $('#id').html();
if(container == 'none'){
$.ajax({
type: 'POST',
data: {id: id},
url: "ajax/get_items.php",
}).done(function(data) {
$('#container').html(data);
}).success(function(){
$('#container').show('fast');
});
}else if(container == 'block'){
$('#container').hide('fast');
}
break;
case 2:
//code for second click
break;
case 3:
//Code for the third click
break;
});
clickCount++; //Add to the click.
});
i use this script
<script type="text/javascript">
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var boxval = $("#content").val();
var dataString = 'content=' + boxval;
if (boxval == '') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value = '';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click", function () {
var ID = $(this).attr("id");
var dataString = 'msg_id=' + ID;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete_data.php",
data: dataString,
cache: false,
success: function (html) {
$(".bar" + ID).slideUp('slow', function () {
$(this).remove();
});
}
});
}
return false;
});
});
</script>
this script combine live update and delete record using jquery and ajax
the problem is when I refresh the page, the record will disappear .. how to keep records that show up are not dissapear when the page is reloaded?
First Check the comment list. Did you put any limit in query, if so then use Order by Primary ID desc.So it would display latest records first.
When you delete any record, check whether it is actually deleted from database or not. Because you are not checking whether record actually deleted or not as per the code you given.
Assuming you are using update_data.php and delete_data.php to manipulate some database, you could use PHP to render the page initially using the data that is currently on the database.
If that is not the case, and you don't have access to that database (it could be a third party web service, right?), or you don't want to do that for any reason, you could use cookie like Saeed answered.
I have an Jquery submit textarea, now I want to set textarea submit without button submit. Just using enter key.
<textarea id="ctextarea"></textarea>
Here it's the JS :
$('.comment_button').live("click",function()
{
var ID = $(this).attr("id");
var uid = $("#uid").val();
var comment= $("#ctextarea"+ID).val();
var dataString = 'comment='+ comment + '&msg_id=' + ID + '&uid=' + uid;
if(comment=='')
{
$('#ctextarea').html("").fadeIn('slow');
$("#ctextarea"+ID).focus();
}
else if (!$.trim($("#ctextarea"+ID).val()))
{
$("#ctextarea"+ID).focus();
}
else
{
$.ajax({
type: "POST",
url: "comment_ajax.php",
data: dataString,
cache: false,
success: function(html){
$("#commentload"+ID).append(html);
$("#ctextarea"+ID).val('');
$("#ctextarea"+ID).focus();
}
});
}
return false;
});
I already search the tutorials and found, but I confused where can I put the code in My JS code.
Someone can give the idea ?
Thanks for helps.
$('#ctextarea').on('keyup', function(e){
if(e.which == 13 || e.keyCode == 13){
//enter key pressed..
}
});
You can subscribe to a keydown/keyup event and submit the form inside the event handler:
var KEY_ENTER = 13;
$('#ctextarea').keyup(function (event) {
if (event.keyCode === KEY_ENTER) {
$('form').submit();
// Or perform any necessary ajax calls here
}
});
still looking for a solution but not find yet, I have a function to manage different forms on same/differents pages
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
after loaded the page and form with an input type="button" named SEND
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
$('form.standard').submit();
});
all the values reach a php page via POST that made all the things (validating, insert in db, update log...) and answer with 'OK' if all OK (so the form in the modal window is substituted with custom message and fade out) or... if there is an error, php answer with some text that js popups with an alert keeping the modal window open with the form.
It's all ok BUT, if php answer with an error, with second click of button SEND the post is sent 2 times.
And if I make another error on second send, and click again the send button, the post values is sent three time... and so on.
What can I do? Where is my error?
thanks.
Try excluding submit block:
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
//$('form.standard').submit(function(event){
// event.preventDefault();
//change 'this' to form.standard
var modalWin = $('form.standard').parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
// }
and after loaded page:
$('form.standard [name="SEND"]').click(function(){
var str = $('#sortableTo').serializelist();
formStantardAction('New train inserted.',str);
//excluding submit event
// $('form.standard').submit();
});
Because $.ajax {} with type:"Post" is already a submit process and then when script call submit then it re-submit.
Hope this right and help
Is it possbile that somewhere in your code you bind the submit event to the form everytime you get the data back from the ajax-request?
I can't check this in the code you submitted here.
Create a global variable as flag
var flag = 0;
and check this flag while posting and reset it after completed
function formStantardAction(correctAnswer,addCustomData){
**if(flag == 1){
return false;
}
flag = 1;**
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
**flag = 0;**
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}
I put some custom code at the beginning of your submit function - basically if a submit is in progress nothing should be done, but otherwise return an error message as usual.
var submitting = false; //initialise the variable, this needs to be out of the function!
function formStantardAction(correctAnswer,addCustomData){
addCustomData = (typeof addCustomData == "undefined")?'':addCustomData;
correctAnswer = (typeof correctAnswer == "undefined")?'Saved.':correctAnswer;
$('form.standard').submit(function(event){
if (submitting) {
return false; //if a submit is in progress, prevent further clicks from doing anything
} else {
submitting = true; //no submit in progress, but let's make one now
}
event.preventDefault();
var modalWin = $(this).parent();
var values = $('form.standard').serialize() + addCustomData;
$.ajax({
url: "inc/gateway.php",
data: values,
type: "POST",
success: function(data){
if (data == "OK"){
$(modalWin).html(correctAnswer).delay(500).fadeOut(500);
setTimeout(function() {
mw_close();
}, 1000);
}else{
alert(data);
}
}
});
});
}