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'];
?>
Related
I want to call PHP page using AJAX but I don't want to reload PHP classes each time, for example, on first time running AJAX, PHP page load and set data, but on second time running AJAX, php get the same data from first time.
function test() {
$.ajax({
url: "./test.php",
method: "post",
success: function(data) {
$(document).find("body").append(`<p>${data}</p>`);
}
});
}
<button type="button" onclick="test()">Click Me!</button>
<script src="https://code.jquery.com/jquery-3.6.0.js"></script>
//test.php
class Test{
private $name = null;
public function setName($name){
$this->name = $name;
}
public function getName(){
return $this->name;
}
}
$class = new Test;
if( $class->getName() == null ){
echo "oops";
$class->setName("pong");
} else {
echo $class->getName();
}
// Fire off the request to /form.php
request = $.ajax({
url: "/form.php",
type: "post",
data: serializedData
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// if the request failed or succeeded
request.always(function () {
//add your logic
});
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
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.
In my Web Application, I want to get an error message on every ajax call.
I m using CodeIgniter using I preferred to use flashdata for this purpose I came to know that flashdata don't update until the refresh
here is my ajax code
$.ajax({
url: '<?php echo base_url();?>Auth/userlogin',
type: 'POST',
data: {
email: email,
password:password
},
dataType: 'text',
success: function(data) {
var error="<?php echo $this->session->flashdata('signup'); ?>"
if(data=='no'){
$('#loginerror').html('<div class="alert alert-danger">'+error+'</div>');
}else{
$('#loginerror').html(' ');
$('#login').hide();
location.reload();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
And here is my Controller Where I m setting Flashdata
$this->form_validation->set_rules('email', 'email', 'trim|required|valid_email');
$this->form_validation->set_rules('password', 'Password', 'trim|required');
if ($this->form_validation->run()==FALSE) {
$this->session->set_flashdata('signup',$this->form_validation->first_error());
echo 'no';
}
I don't see any reason whatsoever of using flash data in ajax cause you already can return any data you need in your response, in your example you can just do this:
if ($this->form_validation->run() == FALSE)
{
$this->json['signup'] = $this->form_validation->first_error();
$this->json['status'] = false;
echo json_encode($this->json);
}
else
{
$this->json['status'] = true;
// your code ....
}
and in your success:
dataType: 'JSON',
success: function(data) {
if(data.status == false) {
$('#loginerror').html('<div class="alert alert-danger">'+data.signup+'</div>');
} else {
$('#loginerror').html(' ');
$('#login').hide();
location.reload();
}
...
This is my code for Javascript Ajax Jquery send data do purchase item.
$('.reserve-button').click(function(e){
var book_id = $(this).parent().data('id');
e.preventDefault();
$.ajax({
url: "/php/insertpurchase.php",
type: "POST",//type of posting the data
data: {"bookID": book_id},
success: function (data) {
alertify.alert("This item was add to your cart.", function(){
alertify.message('OK');
});
},
error: function (result, status, err) {
console.log('error', err, status);
},
timeout : 15000//timeout of the ajax call
});
});
This is HTML code for submit.
<div class="col-md-4">
<?php $bookID = $row['id'];?>
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button class="reserve-button"><?php echo $row['price'];?></button>
In PHP dont receive POST value ->
if(isset($_POST['bookID']))
{
$idProduct = $_POST['bookID'];
I think you should to define this code:
success: function (data) {
console.log(data);
});
Replace of this code:
success: function (data) {
alertify.alert("This item was add to your cart.", function(){
alertify.message('OK');
});
Now you see what result you get in the console.