replacing something else after ajax request? - javascript

i have this html:
cancel
when the user clicks cancel, i want to remove the hyperlink and i want to replace this with an image i.e.
$.ajax({
context:this,
type: "POST",
url: "actions/cancel.php",
data: "id=" + the_id,
cache: false,
success: function() {
$(this).remove;
// add image
thanks :))

Try:
success: function() {
$( "a#cancel_3" ).replaceWith( "<img...>" );
}
You'll have to fill in the HTML in the replaceWith function with whatever you want to replace the link with. is just a placeholder I used.

How about:
$(this).css('display', 'none').after('<img>');

Related

Form submitting to wrong function when changing class dynamically

I'm sure there's a simple explanation for this but I haven't been able to find the right words to use when searching for answers.
When users fill out the form .InvoiceForm it submits via Ajax. After it's submitted remove the .InvoiceForm class and add .UpdateInvoice. When a user submits a .UpdateInvoice form it explains that they are about to make a change and they have to click to say "Yes I want this to be updated".
The issue is that unless I refresh the page so that the form is loaded with the .UpdateInvoice form, I don't get the confirmation which means it's still submitting as a .InvoiceForm form. Is there anything I can do to fix this?
Edit to show code:
Code that runs if there's no record
$('.InvoiceForm').submit(function(e) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
$(this).removeClass('InvoiceForm');
$(this).addClass('UpdateInvoice');
$(this).find('.btn').val('Update');
$(this).find('.id').val(data.invoice_id);
$(this).find('.btn').removeClass('btn-default');
$(this).find('.btn').addClass('btn-danger');
$(this).find('.AddRow').removeClass('hide');
$(this).find('.invoiceDetails').html(data.returnedData);
$(this).parent().next().find('.grade').focus();
}
});
return false;
};
Code that runs if there is a record being updated
$('.UpdateInvoice').submit(function(){
var r = confirm("Are you sure you want to make this update?");
if (r == true) {
$.ajax({
url: $(this).attr('action'),
type: 'POST',
cache: false,
dataType: 'json',
context: this,
data: $(this).serialize(),
beforeSend: function() {
$(".validation-errors").hide().empty();
},
success: function(data) {
alert('This row has been updated');
$(this).find('.total').html(data);
}
});
} else {
}
return false;
});
The function for .UpdateInvoice doesn't run unless I refresh the page.
Thanks for your help.
You bind a click event on '.UpdateInvoce' before it even being created, hence it'll not work. I think you need to use .live() in order to make it works. See document here: jQuery's live()
HTML:
<button id="click_me" class="new">Click Me</button>
<div class="result" />
Script:
$(function () {
$('.new').click(function (e) {
$('.result').text("Im new !");
$(this).removeClass("new");
$(this).addClass("update");
// Bind UpdateInvoice's click event on the fly
$('.update').live(bindUpdate());
});
function bindUpdate() {
$('.update').click(function (e) {
$('.result').text("Update me !");
});
}
});
jsfiddle's demo

loading gif with ajax request

$(".content-short").click(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
success: function(response){
$(".content-full").html(response);
$('.loadingmessage').hide();
}
});
});
//collegeselect.php// is for loading data from database, //.loadingmessage// is for gif
when i am using this for the first time it displays gif,but the gif is not displayed after the 1st click as the data retrieved is already available in content-full from previous ajax request,
how to display it on every click on content short class?
That happens because you are replacing the actual content with loading GIF image with your response.
So, when you click first time it displayed and after the ajax call sucess as per the code you have replaced the content of .content-full and there is no GIF available then.
Solution : To resolve either send the same image tag with response or Move the loader image out side the .content-full.
Add beforeSend : function() before success in your request.
try
$(".content-short").live(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
beforeSend : function()
{
$('.loadingmessage').show();
},
success: function(response){
$(".content-full").html(response);
$('.loadingmessage').hide();
}
});
});
From the comments, I gather that the img is within the .content-full container. The problem is that the img is removed when ajax succeeds since you're doing $(".content-full").html(). One way to fix it is to move the img out of the container. Another way is to store a reference to the img and add it back along with the response via .append() or .prepend() as below.
$(".content-short").click(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
success: function(response) {
var $content = $(".content-full");
var $loaderImg = $content.find('.loadingmessage').hide();
$content.html(response).prepend($loaderImg);
}
});
});
Here is a demo mimicking the behaviour thru setTimeout.

Hide a div when ajax returns nothing

I have an ajax function that loads 1 news at time everytime the user clicks on "load more".
It works like a facebook pagination.
The problem is: when it reachs the end of my database, it doesn't load anything else so I would like to remove the link "load more" when it happens but I couldn't do it.
Here's my JS function:
function loadNews(pageLimit){
var dataString = 'pageLimit='+ pageLimit;
$.ajax({
type: "POST",
url: "ajaxnovidades.php",
data: dataString,
cache: false,
success: function(result){
$("#maisnews").hide();
$("#maisupdates").append(result);
}
});
}
loadNews('0');
I have tried to check if result is empty (result=="") and then hide() the #maisnews div, which is the one with the "load more" link but it doesn't work...
Any help?!
Try this:
if ( ! $.trim(result).length ) $('#maisnews').hide();
You can try something like:
function loadNews(pageLimit){
var dataString = 'pageLimit='+ pageLimit;
$.ajax({
type: "POST",
url: "ajaxnovidades.php",
data: dataString,
cache: false,
success: function(result){
if($.trim(result).length==0){
//$(element).hide()
$("#maisnews").hide();
}else{
$("#maisupdates").append(result);
}
}
});
}
loadNews('0');

Ajax (this) not working

When attempting to access the '.box' class of the $container, using (this) inside of the ajax call doesn't work.
$container.on(
"click",
".box",
function(event){
var description;
if($(this)[0].style.width == '70%'){
$(this).find(".resultData").fadeOut('slow');
$(this).css('width', '18%');
}else{
$.ajax({
url:'scripts/php/fetchResultsData.php',
data: {action:value},
type: 'post',
dataType: 'json',
success: function(data){
description = data[0];
$(this).css('width', '70%');
$(this).append("\
<div class='resultData'>\
<div class='resultName'>" + $(this).find("p").html() + "</div>\
<div class='resultDesc'>" + description +"</div>\
</div>");
/*alert($(this).find("p").html());*/
}
})
}
$container.masonry('reload');
}
);
In case it's not clear what I'm trying to do, I'm attempting to change the css of dynamic elements. But for example,
$(this).css('width','70%');
Isn't adjusting the css at all. If I move it outside the ajax,success section, it works, but then I'm unable to get 'description'.
You're close. 'this' in the context you are using it, refers to the ajax request rather than the thing that issued the event. To fix this, store a copy of this before making the ajax request:
}else{
var me = this;
$.ajax({
...
success: function(data){
description = data[0];
$(me).css('width', '70%');
Just add this to your $.ajax call...
context: this,
...and it'll work.
$.ajax({
context: this, // <-- right here
url:'scripts/php/fetchResultsData.php',
data: {action:value},
type: 'post',
dataType: 'json',
success: function(data) { // ...

Search box in a jQuery ajax success page - issues in loop

Firstly, there have some tag links in my main page. click each one, post value to b.php with jquery.ajax and turn back value in div#result.
b.php have a search box. when search something in it. the result data will still show in the div#result.
my problem is: I know if I will do jQuery ajax in the b.php, I shall write the jQuery code in the first success part. but this only can control one time, when I continue search in the search box, the jQuery not work. I think I met a loop problem. How to solve it?
a.php
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.click').click(function(){
var value1 = $(this).text();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value1,
success: function(data){
$("#result").html(data);
$('#search').click(function(){
var value = $('#search1').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data=" + value,
success: function(data){
$("#result").html(data);
}
});
});
}
});
});
});
</script>
<a rel="aa" class="click">aa</a>
<a rel="aa" class="click">bb</a>
<div id="result"></div>
b.php
<?php
echo $_POST['data'];
?>
<form name="form">
<input type="text" value="" id="search1">
<a name="nfSearch" id="search">search</a>
</form>
When a new element is introduced to the page the jQuery .click() method becomes useless because it can only see elements that were part of the original DOM. What you need to use instead is the jQuery .live() method which allows you to bind events to elements that were created after the DOM was loaded. You can read more about how to use it at the below link.
.live() – jQuery API
$('#search').live('click', function(e) {
// Prevent the default action
e.preventDefault();
// Your code here....
});
First of all i think you should attach the ajax call to the click on the link: the way you are doing right now just execute an ajax call as soon as the page is loaded.
$(document).ready(function(){
//when you click a link call b.php
$('a.yourclass').click(function(){
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data = something",
success: function(data){
$("#result").html(data);
var value = $('#search').val();
$.ajax({
url: "b.php",
dataType: "html",
type: 'POST',
data: "data =" + value,
success: function(data){
$("#result").html(data);
}
});
}
});
});
});
In this way, each time a link with the class of "yourclass" is clicked an ajax call to b.php is sent and if it succed, another call is made (always to b.php). I don't understand if this is what you are looking fo, if you post your html my answer can be better.
In b.php of course you need to echo some html that can be used in the callback
It's strange how your attempting to do two ajax requests like that, surely one is enough. If you need to support multiple text boxes then you just adjust your selectors.
Your whole code can be shortended down to something like this:
$(document).ready(function() {
$('#result').load('b.php', { data: $('#search').val() });
});
So if you wanted to search for the value when clicking on a link (for links within #container):
$('#container').delegate('a', 'click', function() {
// .text() will get what's inside the <a> tag
$('#result').load('b.php', { data: $(this).text() });
});

Categories