Why ajax reloads the page - javascript

I have an ajax + jquery script and when I execute it (click the button) it reloads the page.
script
jQuery(document).ready(function($) {
$(document).on('click', '.image-remove-btn', function (e){
var img = $(this).closest('.thumbs');
var id = img.attr('data-id');
$.ajax({
url: admin_url('admin-ajax.php'),
type: 'POST',
data: {deletedId : id},
success: function( data ) {
img.remove();
}
});
});
});
HTML of element that should be removed:
<div class="thumbs ui-droppable">
<div class="inner ui-draggable ui-draggable-handle" data-thumb="0">
<img data-id="32949" src="https://badzingerauto.com/wp-content/uploads/2021/05/NISSAN__QASHQAI__1-5_dCi_106_Acenta__inc-__inc-__2009__BC501CF-e01-350x205.jpg">
<div class="inner-hover">
<button class="image-remove-btn butterbean-remove-image"> <!-- <i class="fa fa-arrows"></i> Font Awesome fontawesome.com -->
</div>
</div>
</div>

I think #Charlieft is correct you can change your code as follows to prevent the reload
jQuery(document).ready(function($) {
$(document).on('click', '.image-remove-btn', function (e){
e.preventDefault();
var img = $(this).closest('.thumbs');
var id = img.attr('data-id');
$.ajax({
url: admin_url('admin-ajax.php'),
type: 'POST',
data: {deletedId : id},
success: function( data ) {
img.remove();
}
});
});
});

Related

Lazy for html content

I'm using lazy for my images lazySizes plugin I'm looking for a way to do html content but I couldn't do that for html is there any way to do simply ? and my html structure
$('.lazy.teaser.lazy_content').on('lazyunveilread', function (ev) {
data_url = $(this).attr("data-url");
data_id = $(this).attr("data-target-id");
$.ajax({
url: data_url,
type: "POST",
beforeSend: function () {
$(".loaderDiv").show();
$("#" + data_id).html("");
},
success: function (data) {
$(".loaderDiv").hide();
$("#" + data_id).html(data);
}
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lazysizes/3.0.0/lazysizes.min.js"></script>
<div class="trustyou-detail-box section lazy teaser lazy_content" data-url="/ajax/yorumlar/#Model.OtelBilgileri.seflink" data-expand="-210" data-target-id="ajax-content" id="yorumlar-area">
<h4 class="tur-main-baslik section-head">YORUMLAR</h4>
<div id="ajax-content"></div>
</div>
I have data-url and data-target-id to get url and my content
Yes, you can:
<!-- The ID (id="ajax-content) is redundant -->
<div class="lazyload" data-url="...">
<div class="loaderDiv"></div>
</div>
$(document).on('lazybeforeunveil', function(e) {
var $target = $(e.target);
$target.load($target.data('url'));
});
http://jsfiddle.net/80hg2ykv/4/

Add one or two more PHP variables to the javascript code

I am a decent PHP programer and recently I got stuck in a javascript code.
I have the code below:
$(function () {
$('.more').live("click", function () {
var ID = $(this).attr("id");
if (ID) {
$("#more" + ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: "lastmsg=" + ID,
cache: false,
success: function (html) {
$("div#updates").append(html);
$("#more" + ID).remove();
}
});
} else {
$(".morebox").html('The End');
}
return false;
});
});
This code submit without problems one PHP variable to the process page loadmore.php using this input
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
<a href="#" class="more" id="<?php echo $load_id; ?>">
load more
</a>
</div>
How can put more variables in the input and the javascript code to work with them on the process page?
I want to set one or two more variables.
UPDATE:
I updated the code like this:
HTML input:
<div id="more<?= $load_id ?>" class="morebox" style="margin-bottom: 200px;">
load more</div>
JAVASCRIPT CODE:
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: {"lastmsg="+ ID, "act="+ ACT},
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
I am not sure if the data lines was writed properly because the script looks like it's frozen now
SOLVED:
I just used a datastring like this
<script type="text/javascript">
$(function() {
$('.more').live("click",function()
{
var ID = $(this).attr("data-id");
var ACT = $(this).attr("data-act");
var dataString = 'lastmsg='+ ID + '&act=' + ACT;
if(ID)
{
$("#more"+ID).html('<img src="moreajax.gif" />');
$.ajax({
type: "POST",
url: "scripts/loadmore.php",
data: dataString,
//data: {"lastmsg="+ ID, "act="+ ACT },
cache: false,
success: function(html){
$("div#updates").append(html);
$("#more"+ID).remove();
}
});
}
else{
$(".morebox").html('The End');
}
return false;
});
});
</script>
Just send data as an object:
data: {
"lastmsg": "lastmsg="+ ID,
"anotherData": "someData"
}
You'll retrieve them in your PHP script as follows:
$_POST["lastmsg"];
$_POST["anotherData"];

How to Get content External link to div from Listview Jquery

[question]: I can't get content external link to div=contentlink form listview Jquery. This code is below: ( or check at: http://jsfiddle.net/z36UK/2/ )
<div id="wrap">
<ul data-role="listview" data-filter="true" data-filter-placeholder="Search..." id="ds-canho">
</ul>
</div>
<script>
$(document).ready(function() {
$.mobile.loading( "show" );
$.ajax({
type: "GET",
url: 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%27http://saigonpearl.info/home/notype/-0-trang-chu.html%27%20and%20xpath%3D%22%2F%2Fdiv%5B%40class%3D%27tindang%27%5D%22&diagnostics=true',
dataType: "xml",
success: parseXml
});
function parseXml(xml) {
$(xml).find("div.tindang").each(function() {
var url = $(this).find('a').attr("href"),
urlx= url.replace('#menutop','');
//find each instance of loc in xml file and wrap it in a link
$("ul#ds-canho").append('<li><a href='+ urlx +'>' + $(this).find('h3').text() + '</a></li>');
$('ul#ds-canho').listview('refresh');
console.log( this );
$.mobile.loading( "hide" );
});
}
});
</script></body>

event.preventDefault() with .on('click') doesn't prevent default behavior

I have the following HTML and javascript. When I click .todo and .completedmsg which have links, I am expecting event.preventDefault(). But it jumps to the link.
$("#form").on('click',".todo", function(event){...}
$("#form").on('click','.completedmsg', function(event){...}
What am I doing wrong here?
HTML all
<div id="homeright" class="adminhome">
<form method="post" id="form" action="admin/insertShoutBox">
<input type="hidden" name="user_id" id="user_id" value="1">
<input type="hidden" name="user" id="nick" value="admin">
<p class="messagelabel"><label class="messagelabel">Message</label>
<textarea id="message" name="message" rows="2" cols="80"></textarea>
</p>
<div class="buttons">
<button type="submit" class="positive" name="submit" value="submit">
<img src="http://localhost/website2014/assets/icons/disk.png" alt="disk"> Save </button>
</div>
</form>
<div id="loading" style="display: none;"><img src="../../assets/images/general/ajax-loader2.gif" alt="Loading now. Smile"></div>
<div class="clearboth"></div>
<div id="container">
<span class="clear"></span>
<div class="content">
<h1>Latest Messages or Task To Do</h1>
<ul id="message_ul" style="display: block;">
<li class="1">
<div class="listbox"><span class="user"><strong>admin</strong></span>
<span class="date">2014-03-28 17:25:50</span>
to do<span class="msg">test</span></div></li></ul>
</div>
</div>
<div id="completed">
<h1>Completed Lists</h1>
<ul id="completed_ul" style="display: block;">
<li class="2">
<span class="user"><strong>admin</strong></span>
<span class="date">2014-03-28 18:11:29</span>
completed
x<span class="msg">another test
</span>
</li></ul>
</div>
</div>
jQuery all
$(document).ready(function(){
//global vars
var inputUser = $("#nick");
var inputMessage = $("#message");
var loading = $("#loading");
var messageList = $("#message_ul");
var completedmsg = $("#completed");
var completedList = $("#completed_ul");
//Load for the first time the shoutbox data
updateShoutbox();
updateCompletedbox();
function updateShoutbox()
{
//just for the fade effect
messageList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "<?php echo site_url('messages/admin/AjaxgetShoutBox'); ?>",
complete: function(data)
{
loading.fadeOut();
messageList.html(data.responseText);
messageList.fadeIn(500);
//completedList.fadeIn(500);
}
});
}
function updateCompletedbox()
{
//just for the fade effect
completedList.hide();
loading.fadeIn();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "<?php echo site_url('messages/admin/AjaxgetCompletedBox'); ?>",
complete: function(data)
{
loading.fadeOut();
completedList.html(data.responseText);
// messageList.fadeIn(500);
completedList.fadeIn(500);
}
});
}
//check if all fields are filled
function checkForm()
{
if(inputUser.val() && inputMessage.val())
{
return true;
}
else
{
return false;
}
}
//on submit event
$("#form").submit(function(event){
event.preventDefault();
if(checkForm())
{
var nick = inputUser.attr("value");
var message = inputMessage.attr("value");
//we deactivate submit button while sending
$("#send").attr({ disabled:true, value:"Sending..." });
$("#send").blur();
//send the post to shoutbox.php
$.ajax({
type: "POST",
url: "<?php echo site_url('messages/admin/insertShoutBox'); ?>",
data: $('#form').serialize(),
complete: function(data)
{
messageList.html(data.responseText);
updateShoutbox();
$('#message').val('');
//reactivate the send button
$("#send").attr({ disabled:false, value:"SUBMIT !" });
}
});
}
else alert("Please fill all fields!");
//we prevent the refresh of the page after submitting the form
return false;
});
//on todo event. this changes the status to compeleted
$("#form").on('click',".todo", function(event){
event.preventDefault();
loading.fadeIn();
var href = $(this).attr("href");
var msgContainer = $(this).closest('li');
$.ajax({
type: "POST",
url: href,
cache: false,
complete: function()
{
msgContainer.slideUp('slow', function() {$(this).remove();});
updateShoutbox();
updateCompletedbox();
loading.fadeOut();
}
});
});
// on complete event. this changes the status to todo
$("#form").on('click','.completedmsg', function(event){
event.preventDefault();
loading.fadeIn();
var href = $(this).attr("href");
var CompMsgContainer = $(this).closest('li');
$.ajax({
type: "POST",
url: href,
cache: false,
complete: function(){
CompMsgContainer.slideUp('slow', function() {$(this).remove();});
updateShoutbox();
updateCompletedbox();
loading.fadeOut();
}
});
});
$("#form").on('click','.delete',function(event){
event.preventDefault();
// alert ('clicked');
loading.fadeIn();
var href = $(this).attr("href");
var commentContainer = $(this).parent();
var id = $(this).attr("id");
$.ajax({
type: "POST",
url: href,
cache: false,
complete: function()
{
commentContainer.slideUp('slow', function() {$(this).remove();});
updateShoutbox();
updateCompletedbox();
loading.fadeOut();
}
});
});
});
There are no links inside #form with a class of todo - so the events are not attached to your links:
The .on() method attaches event handlers to the currently selected set of elements in the jQuery object.
The links are outside of the form, so those particular events can't be firing. If the event isn't firing then it makes sense that the links are being 'jumped to' as there's nothing to trap it. If you place a link with the class of .todo inside the form, you will get the desired effect.
As a first test, you could just bind to $(document) instead of #form and check the preventDefault before re-working the HTML so that you can bind to a lower-level element in the DOM (if required...)
Cut-down example of issue: http://jsfiddle.net/YWV9A/1/
Solution: http://jsfiddle.net/YWV9A/3/

jQuery .hide() and .show() not working

I have this code generate dynamically using php code:-
<div class="mailList" id="M_6">
<div class="mailListHeader" id="H_6">
<img style="float:right; display:none;" class="loaderIMG" id="LOADER_6" src="images/preloader.gif">
Sent by <strong>Admin</strong> on <strong>Oct 03 2013 02:53 PM</strong> to <strong>Received Response</strong> for Quarter <strong>3</strong> Year <strong>2013</strong>.<br>
Subject: <strong>Test Mail</strong><br>
</div>
<div class="mailListContent" id="C_6">
<div class="closeContent" id="CC_6">Close [x]</div>
<span id="SPAN_6"></span>
</div>
<div class="mailListFooter" id="F_6">
<span class="mailContentBtn" id="MCBTN_6" style="font-size:11px; color:#09C; cursor:pointer;">
View Content
</span>
<span class="mailListBtn" id="MLBTN_6" style="float:right; font-size:11px; color:#C06; cursor:pointer;">
Successfull-[0] Failed-[4]
</span>
</div>
</div>
Then, user can click View Content or Successfull-[0] Failed-[4] that will make a ajax request than display result in div mailListContent. Below is code for the jquery ajax request:-
$(".mailContentBtn, .mailListBtn").click(function(){
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if($("#C_"+actualId).is(":visible")) {
$("#C_"+actualId).hide("slow","swing");
}
$("img#LOADER_"+actualId).show();
if(currentId[0]=="MCBTN") {
var dataString ="action=getMailContentByID&mailID="+actualId;
} else {
var dataString ="action=getMailListByID&mailID="+actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function(html) {
$("#SPAN_"+actualId).empty();
$("#SPAN_"+actualId).append(html);
$("#C_"+actualId).show("slow","swing");
$("img#LOADER_"+actualId).hide();
}
});
});
The request and the events works fine, the problem is every time user click at View Content or Successfull-[0] Failed-[4] the loading image is not display. As you can see, I give a unique ID for every loading image than only 1 loading image will display on clik. There is no error in inspect code in Google Chrome. How can I solve this?
Thank you.
In your call to $.ajax, change the "async" option to "true". Because in your case, the $.ajax is blocking the ui thread in displaying the loading image as it is executed synchronously.
You have missed:
$(document).ready(function () {
});
try this:
<script>
$(document).ready(function () {
$(".mailContentBtn, .mailListBtn").click(function () {
var currentId = $(this).attr('id');
currentId = currentId.split("_");
var actualId = currentId[1];
if ($("#C_" + actualId).is(":visible"))
$("#C_" + actualId).hide("slow", "swing");
$("img#LOADER_" + actualId).show();
if (currentId[0] == "MCBTN") {
var dataString = "action=getMailContentByID" +
"&mailID=" + actualId;
}
else {
var dataString = "action=getMailListByID" +
"&mailID=" + actualId;
}
$.ajax({
type: "POST",
url: "include/getMail.php",
data: dataString,
cache: false,
async: false,
success: function (html) {
$("#SPAN_" + actualId).empty();
$("#SPAN_" + actualId).append(html);
$("#C_" + actualId).show("slow", "swing");
$("img#LOADER_" + actualId).hide();
}
});
});
})
</script>

Categories

Resources