Hi guys i have a little problem with calling popup by id from link. It`s working on click but cannot call from url something like exaple.com/#id
(function($) {
$(document).ready(function() {
//$('a.ajax-post').off('click').on('click', function(e) {
$("a.ajax-post").on("click", function(e) {
// show popup
$(".popup.supernova").addClass("is-show");
e.preventDefault(); //Prevent Default Behaviour
var post_id = $(this).attr("id"); //Get Post ID
// Ajax Call
$.ajax({
cache: false,
timeout: 8000,
url: "/wp-admin/admin-ajax.php",
type: "POST",
data: {
action: "theme_post_example",
id: post_id
},
beforeSend: function() {
$("#ajax-response").html("Loading");
},
success: function(data, textStatus, jqXHR) {
var $ajax_response = $(data);
$("#ajax-response").html($ajax_response);
setTimeout(() => {
$("#ajax-response").addClass("show-content");
}, 100);
/* $(".popup.supernova").append(script); */
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(
"The following error occured: " + textStatus,
errorThrown
);
},
complete: function(jqXHR, textStatus) {},
});
});
});
})(jQuery);
<a href="#" id="8" class="catalog__item popup-8 ajax-post">
<span class="catalog__title">Title</span>
<img src="image.jpg" alt="" id="img_8">
</a>
Can anyone tell me how to do it? and why its not working. im new in js. Thanks in advance
As per your problem, You want to open pop up when URL containers #id like this
exaple.com/#id
You check if URL contains #id, then click anchor tag Programmatically
Related
Issue
I have a function in file add-cp-modal.js called dbInsertCostPlace(nameText) that calls another function in file wpdb-helper.js called dbInsertCostPlace(onSuccess, onError) that makes a jQuery.ajax call. However, the ajax call does not work when it's inside the seperate file wpdb-helper.js. The ajax call does only work when it is in the same file as the function calling it.
Files
add-cp-modal.js, calling ajax function in wpdb-helper.js:
<div id="add-costplace-modal" class="add-costplace-modal-background">
<div class="add-costplace-modal">
<div class="add-costplace-modal-headerr">
<div class="add-costplace-modal-headerr-left-box">
Skapa kostnadsställe
</div>
</div>
<div class="add-costplace-modal-body">
<div class="add-costplace-modal-name-form">
<div class="add-costplace-modal-name-form-label">
Namn:
</div>
<input id="add-costplace-modal-name-textfield" type="text" class="add-costplace-modal-name-textfield">
</div>
</div>
<div class="add-costplace-modal-footer">
<button id="add-costplace-modal-save-button">Spara</button>
<button id="add-costplace-modal-cancel-button">Avbryt</button>
</div>
</div>
</div>
<script>
document.addEventListener('DOMContentLoaded', function () {
addCpModal.init();
}, false);
var addCpModal = {
init: function() {
this.addButtonListeners();
},
addButtonListeners: function() {
document.getElementById("add-costplace-modal-save-button").addEventListener("click", this.savePressed);
document.getElementById("add-costplace-modal-cancel-button").addEventListener("click", this.cancelPressed);
},
savePressed: function() {
var nameText = addCpModal.getNameText();
addCpModal.dbInsertCostPlace(nameText);
addCpModal.hide();
},
dbInsertCostPlace: function(nameText) {
wpdbhelper.dbInsertCostPlace(addCpModal.onCostPlacePostSuccess, addCpModal.onCostPlacePostError);
},
onCostPlacePostSuccess: function(result) {
alert("onCostPlacePostSuccess");
addCpModal.loadCostPlaces();
},
loadCostPlaces: function(){
wpdbhelper.loadCostPlaces(addCpModal.onCostPlacesGetSuccess, addCpModal.onCostPlacesGetError);
},
onCostPlacesGetSuccess: function(result) {
alert("onCostPlacesGetSuccess");
cpTable.setData(result);
},
onCostPlacesGetError: function(jqXHR, textStatus, errorThrown) {
alert("Error occurred getting cost places.");
},
onCostPlacePostError: function(jqXHR, textStatus, errorThrown) {
alert("Error occurred posting cost place.");
},
getNameText: function() {
var nameTextfield = document.getElementById("add-costplace-modal-name-textfield");
return nameTextfield.value;
},
hide: function() {
var modal = document.getElementById("add-costplace-modal");
modal.style["visibility"] = "hidden";
},
cancelPressed: function() {
addCpModal.hide();
},
show: function() {
var modal = document.getElementById("add-costplace-modal");
modal.style["visibility"] = "visible";
}
};
</script>
wpdb-helper.js containing the ajax call function:
<script>
var wpdbhelper = {
dbInsertCostPlace: function(onSuccess, onError) {
console.log("wpdb-helper: ajaxurl: " + ajaxurl);
jQuery.ajax({
url : ajaxurl,
type: 'POST',
data: {
'action': 'insert_costplace',
'data': {
'name': nameText,
'age': 17
}
},
success: function(result) {
console.log("SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("ERROR");
}
});
console.log("wpdb-helper: After ajax call.\n");
},
loadCostPlaces: function (onSuccess, onError){
console.log("loadCostPlaces called inside wpdbhelper");
jQuery.ajax({
url : ajaxurl,
type: 'POST',
data: {
action: 'get_costplaces'
},
dataType: 'json',
success: function(result) {
console.log("SUCCESS");
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("ERROR");
}
});
}
};
</script>
Based on this short (but great) article:
Include your jQuery definition in the footer (instead of header) using wp_enqueue_script("jquery");
you can also add an anonymous scope (again, in the footer) to use $ instead of jQuery using:
(function($) {
// $ Works! You can test it with next line if you like
// console.log($);
})( jQuery );
That should make jQuery visible from all your files in project
I found the problem and it feels very silly now. The variable "nameText" was undefined. I forgot to pass it into the wpdp-helper method as an argument. Once I passed in a nameText value the ajax call worked.
I know the jQuery load syntax which is
$("#count").load("demo_test.txt #p1");
this is the code I'm using for my button's onclick function
temp_user_cart.php
function resMinus(id){
if (id) {
$.ajax({
url: "temp_cart-minus.php",
type: "post",
data: {
id_minus: id
},
success:function(response) {
var employeeTable = $("#myTables").DataTable();
employeeTable.ajax.reload(null, false);
},
error: function(jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
return false;
}
};
After this AJAX succeed/execute I want to load the contents of cart_counter.php to this page
restaurant-order.php
<span id="cart_counter"></span>
this is cart_counter.php
<?php
session_start();
echo $_SESSION['count_count'];
?>
I have a page where people can add things to their "favorites" list with this:
$(function(){
$('.doit-01234').click(function (e) {
e.preventDefault();
$.ajax({
url: "https://www.domain.com/page.php?add=01234",
type: "GET",
success: function (data) {
$(".result-01234").html('<span class="icon-favorite-green"></span>');
},
error: function (xhr, ajaxOptions, thrownError) {
$(".result-01234").html('<span class="icon-favorite-red"></span>');
},
timeout: 15000
});
});
});
The items get added with page.php?add=01234. The same page may however have 20 or 30 items that people can add to their favorites. Is there an easy way to use just one instance of this script for multiple IDs instead of the same jQuery code over and over after each item?
Meaning page.php?add=9999 would then update .result-9999 when .doit-9999 is called and page.php?add=5151 would update .result-5151 and so on...
Give your elements a common class and a custom data attribute:
<div class="ajax doit-01234" data-id="01234"></div>
And then use 1 handler:
$('.ajax').click(function (e) {
e.preventDefault();
var id = $(this).data("id");
$.ajax({
url: "https://www.domain.com/page.php?add=" + id,
type: "GET",
success: function (data) {
//Concatenate a selector based on the "id" in the data attribute
$(".result-" + id).html('<span class="icon-favorite-green"></span>');
},
error: function (xhr, ajaxOptions, thrownError) {
//Concatenate a selector based on the "id" in the data attribute
$(".result-" + id).html('<span class="icon-favorite-red"></span>');
},
timeout: 15000
});
});
Create this function like this:
function Name (e) {
var code = 01234;//extract your code like 1234 here by splitting or..
e.preventDefault();
$.ajax({
url: "https://www.domain.com/page.php?add=01234",
type: "GET",
success: function (data) {
$('.result-'+code).html('<span class="icon-favorite-green"></span>');
},
error: function (xhr, ajaxOptions, thrownError) {
$('.result-'+code).html('<span class="icon-favorite-red"></span>');
},
timeout: 15000
});
});
Now where you want to call this function , you can call like this:
HTML:
<button onclick="Name(this);">Hello</button>
I have two pieces of code, first of all I have my code which toggles open a div with an included close button:
http://jsfiddle.net/spadez/uhEgG/27/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle();
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
Then I also have my Ajax code which is designed to fire when the div has been opened:
$(function () {
$('#country_link').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
return false;
});
});
What I am stuck with now is, how do I make the ajax only execute when the div is being opened? Because I am working with a toggle and close button it seems difficult to work out what the click is doing, whether it is opening it or closing it.
I guess my options are to have some kind of flag or alternatively have some "if" code, so if class is equal to .hidden then do not execute. I haven't been able to integrate either of these solutions and I am unsure if either of them is the proper way to achieve this.
Include the check as part of your slide function:
$("#country_slide").slideToggle(function() {
if ($(this).is(":visible")) {
alert("im visible!");
}
});
Demo: http://jsfiddle.net/tymeJV/uhEgG/28/
if($("#country_slide").is(":visible"))
//call ajax
This code adds data to the element, to check if it's already loaded next time you click on it.
Currently I am not able to test it, so it may contain errors.
$(function () {
$('#country_link').on('click', function (e) {
// Prevent from following the link, if there is some sort of error in
// the code before 'return false' it would still follow the link.
e.preventDefault();
// Get $link because 'this' is something else in the ajax request.
var $link = $(this);
// Exit if the data is loaded already
if ($link.data('loaded') === true)
return false;
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend: function () {
$('.loader').show();
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
// If successful, bind 'loaded' in the data
$link.data('loaded', true)
},
error: function (xhr, textStatus, errorThrown) {
// $("#country_slide").hide('fast');
// alert('request failed');
},
complete: function () {
$('.loader').hide();
},
});
});
});
I am new to jquery and coding in general. This is what I am trying to do:
When a link is clicked, expand the #country_slide div
Show "loading" text
If ajax is successful, put the contents of an html file into the div
Otherwise alert an error and close the div
This is the code I now have:
http://jsfiddle.net/spadez/n9nVs/5/
window.onload = function () {
var a = document.getElementById("country_link");
a.onclick = function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").val('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
}
When the link is clicked, I never see the loading text in the box. Please can someone tell me where I have gone wrong here? Also if anyone can offer any words of advice about my first jquery script I would really appreciate it.
Your anchor's id is country, not country_link. So:
var a = document.getElementById("country");
or just use jQuery's id selector:
var a = $("#country");
or even better directly chain:
$(function() {
$('#country').click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
}
});
Notice that I have used the $(document).ready function instead of window.onload. Also I have replaced the onclick event subscription with jQuery's click function. If you are using jQuery it would be better to take full advantage of it.
Working jsFiddle Demo
You don't have any country_link element in your page.
Instead of using window.onload you can use DOM ready.
Attach click handler by jQuery with .on() method.
The .val() method is for <input />. For other elements, use .html() instead.
// DOM ready instead of window.onload
$(function () {
// attach click handler by jQuery instead of onclick
$('#country').on('click', function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$("#country_slide").show();
// val() method is for <input />
// use html() instead
$("#country_slide").html('<p>Loading</p>')
},
success: function (data, textStatus) {
$("#country_slide").html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$("#country_slide").hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});
References:
.html() - jQuery API Documentation
.on() - jQuery API Documentation
.val() - jQuery API Documentation
jQuery( callback ) - jQuery API Documentation
On the fiddle you have
<a href="#" id="country">
Where it should be:
<a href="#" id="country_link">
or change the JS to be
var a = document.getElementById("country");
Because there is no element with an ID country_link
document.getElementById() returns null if the element isn't found
document.getElementById('country').onclick = ...; //should work
In JavaScript, null is a special primitive and you cannot add properties to primitive types.
You have to add an element with id=country_link and the this code will work as NOX said. I have tried that in jsfiddle. try it using
$("#country").click(function(){
// your code goes here
})
that will works.
document.getElementById("country_link"); shall be replaced by document.getElementById("country"); as "country_link" is not the id of any <a> tag in the mark up.
If you are using jQuery library you may handle event like-
$(document).on("click","a",function(){
//ajax stuff
});
Updated Your jsfiddle Code. Just check. its going to failure method. In your workspace you should have the test.html returning the actual data. Thanks.
Don't use plain JS if you already have jQuery (it will be easier for you):
;$(document).ready(function(){
$(country_link).click(function () {
$.ajax({
type: 'GET',
dataType: 'html',
url: '/ajax/test.html',
timeout: 5000,
beforeSend : function() {
$(country_slide).show();
$(country_slide).val('<p>Loading</p>');
},
success: function (data, textStatus) {
$(country_slide).html(data);
alert('request successful');
},
error: function (xhr, textStatus, errorThrown) {
alert('request failed');
$(country_slide).hide();
},
complete : function() {
$('.loader').hide();
},
});
return false;
});
});