add loading text to javascript before html() - javascript

i want to add loading text before .html() load complete in my page
here is my code
$.post("<?php echo get_template_directory_uri(); ?>/template-parts/live.php", { couplername:couplername, couplercount:couplercount, couplerlathing:couplerlathing, couplerwhois:couplerwhois, couplerdetailsname:couplerdetailsname, couplerdetailsid:couplerdetailsid, couplerdetailsnumber:couplerdetailsnumber },
function(data) {
$("#order_price").html(data);
});

In order to have better control over your ajax call use the following ajax style:
$.ajax({
url: 'http://example.com',
method: 'POST',
data : {
someKey : "SOME_VAL",
anotherKey : "ANOTHE_VAL"
},
beforeSend:function(){
//HERE YOU CAN SHOW LOADING ETC.
},
success: function (response) {
//HERE YOU CAN GET THE RESPONSE of AJAX
},
error: function (e) {
//HERE YOU CAN HANDLE SITUATIONS OF ERROR
},
complete : function(){
//HERE YOU CAN REMOVE THE LOADING
}
});

Related

Ajax POST don't work after button click

My problem is lack of action after pressing the button. Under the button hook AJAX function.
Please a hint where I have a bug // errors.
My code:
Controller:
[HttpPost]
public ActionResult InsertCodesToDB(string name)
{
cl.InsertCodesToDB(name);
fl.MoveCodeFileToAccept(name);
string response = "Test";
return Content(response, "application/json");
}
View / Button:
<input type="button" class="btn btn-success sendCodesToDB" value="Umieść kody w bazie" data-value="#item.Name"/>
View / Script:
<script>
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
onBegin;
}
});
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
Thank you in advance for your help.
You seem to not be adding the on ready function for jQuery. Try adding it before your click action and closing it before your onBegin() function, like so:
<script>
// open here
$( document ).ready(function() {
$('.sendCodesToDB').on('click', function () {
var name = $(this).data("value");
$.ajax({
url: '/ActualCodes/InsertCodesToDB',
type: 'POST',
dataType: 'json',
cache: false,
data: JSON.stringify({ 'name': 'name' }),
success: function (response) {
#(ViewBag.MessageOK) = response;
},
error: function () {
// function call missing "()"
onBegin();
}
});
});
// and close here
});
function onBegin() {
$('#files').hide();
$('#insertFiles').hide();
$('#loading').show();
$('#lblSelectedProductName').text('Trwa umieszczanie kodów w bazie danych. Proszę czekać ...');
$('#ttt').show();
}
</script>
The code in Ajax must be JavaScript. You cannot use C# code there (except to print some values). What is #(ViewBag.MessageOK) doing here:
success: function (response) {
#(ViewBag.MessageOK) = response;
},
If you want to display the response in a message box, try something like:
success: function (response) {
$("#your_message_id").html(response);
},
Notes: aside from that, you have several errors in your code as others pointed out in the comments.
1- Remove the quotes from the data like this:
data: JSON.stringify({ name: name }),
2- Change the error to this:
error: function () {
onBegin(); // You need "()" here
}
Or better this:
error: onBegin // You don't need "()" here
I guess you are sending data inside the AJAX call in the wrong way.
Try it like this
data: JSON.stringify({ name: name })
Hope this will help you.

Ajax load different wordpress content based on user click

I'm trying to load different templates through $.ajax based on what buttons a user clicks. I know how to do it with one template file, but can't seem to find a way to adjust the code to load different template based on click (without repeating the code).
Here's the relevant part of the ajax call:
var $this = $('#my-data');
$('#button-foo').click(function() {
$.ajax({
url: myAjax.ajax_url,
data: {
action: 'my_ajax_action'
},
cache: true,
beforeSend: function(){
$this.empty();
$this.addClass('loading');
},
complete: function(){
$this.removeClass('loading');
},
success: function(data) {
$this.append(data);
},
error: function(MLHttpRequest, textStatus, errorThrown){
alert(errorThrown);
}
});
});
And here's my Wordpress function:
function my_ajax_action() {
include(locate_template( 'part-template-foo.php' ));
die();
}
add_action('wp_ajax_nopriv_my_ajax_action', 'my_ajax_action');
add_action('wp_ajax_my_ajax_action', 'my_ajax_action');
Now what I need would be to include 4 different templates (part-template-bar.php, part-template-foobar.php, etc) based on user click. Something like:
function my_ajax_action() {
if ($_REQUEST['template'] == 'foo') {
include(locate_template( 'part-foo.php' ));
die();
}
if ($_REQUEST['template'] == 'bar') {
include(locate_template( 'part-bar.php' ));
die();
}
...
}
Any hint on how could I do this without having to repeat the js code and wp function four times? Thank you.

Ajax call to delete and refresh list not working

I am implementing an Ajax call to the server to delete a post from a li. The delete is working fine, but I need to manually get out from the list page and when I get back the list is updated. What I am trying to achieve, is that when the button that deletes the item, also refreshes the list. I added the following code but is not refreshing :(.
function deleteThisPost() {
//alert($('#myPostIDStorage').val())
$.ajax({
type: 'GET',
data: 'myPostIDValue=' + $('#myPostIDStorage').val(),
url: 'http://wander-app.org/deletePosts.php',
timeout: 5000,
success: function (data) {
alert('Post Deleted!');
},
error: function () {
alert('Error Deleting Post');
}
});
return false;
$('#myPost').listview("refresh");
};
Your ajax call works fine as you can see there. You should take a notice that if you return anything from a function it is no longer executed. The code that you provided below $( '#myPost' ).listview( "refresh" ); will be never examined.
What you probably want to do is
function deleteThisPost() {
//alert($('#myPostIDStorage').val())
$.ajax({
type: 'GET',
data: 'myPostIDValue=' + $('#myPostIDStorage').val(),
url: 'http://wander-app.org/deletePosts.php',
timeout: 5000,
success: function (data) {
alert('Post Deleted!');
},
error: function () {
alert('Error Deleting Post');
}
});
$('#myPost').listview("refresh");
return false;
};
According to your question if you want a dialog box with cancel and confirm button you can do
if(confirm('Do you want to delete?') == true) {
alert('Deleted');
}

AJAX/ json returning null open cart

Hi Im attempting a simple ajax request but I keep getting a null value for json.
Here is my javascript...
<script>
$(document).ready( function() {
$('#donate-box-submit').on('click', function() {
var donate_code = $('#charity-campaign-code').val();
var donate_amount = $('#charity-campaign-amount').val();
$.ajax({
url: 'index.php?route=donate/donatenow',
type: 'post',
data: {
donate_code: donate_code,
donate_amount: donate_amount
},
dataType: 'json',
beforeSend: function() {
},
complete: function() {
},
success: function(json) {
console.log(json);
alert(json['test']);
},
error: function() {
}
});
});
});
</script>
and my php...
public function donatenow() {
$json = array(
'test' => 'Output this text'
);
$this->response->setOutput(json_encode($json));
}
I have also tried echo json_encode($json); just to rule out any issues with that OpenCart function, but the same issue is still there.
The problem is the route you are using to call the method. Not sure on exactly what class you are using as the controller, but there should be three parts to the route: route=aaa/bbb/donatenow where as you've got aaa/donatenow

Submit Ajax Form via php without document.ready

I am submitting a number of forms on my page via php using Ajax. The code works great in forms preloaded with the page. However, I need to submit some dynamic forms that don't load with the page, they are called via other javascript functions.
Please, I need someone to help me review the code for use for forms that don't load with the page. Also the 'failure' condition is not working.
The code is below:
<script type="text/javascript">
feedbar = document.getElementById("feedbar");
jQuery(document).ready(function() {
$('#addressform').on('submit', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
Thanks.
You need to bind event by existing html (e.g body).
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on()
see api: https://api.jquery.com/on/
Try like this:
$("body").on('submit', '#addressform',function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $('#addressform').serialize(),
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
failure: function () {
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
you can delegate to document:
$(document).on('submit', '#addressform', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----serialize with "this"
success: function () {
feedbar.innerHTML='<div class="text-success">New Addressed Saved Successfully</div>';
},
error: function () { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">Error Saving New Address</div>';
}
});
e.preventDefault();
});
});
As you have posted this line as below:
I need to submit some dynamic forms that don't load with the page
What i understand with this line is you want a common submit function for all forms which are generated dynamically, then you can do this:
$(document).on('submit', 'form', function (e) {
$.ajax({
type: 'post',
url: 'data/process.php',
data: $(this).serialize(), // <----"this" is current form context
success: function () {
//some stuff
},
error: function () { //<----use error function instead
//some stuff
}
});
e.preventDefault();
});
});
For your last comment:
You can try to get the text in ajax response like this:
success: function (data) {
feedbar.innerHTML='<div class="text-success">'+ data +'</div>';
},
error: function (xhr) { //<----use error function instead
feedbar.innerHTML='<div class="text-danger">' + xhr.responseText + '</div>';
}
if Success:
here in success function you get the response in data which is the arguement in success function, this holds the response which it requested to the serverside.
if Error:
Same way if something goes wrong at the serverside or any kind of execption has been occured then xhr which is the arguement of error function holds the responseText.
And finally i suggest you that you can place your response in feedbar selector using jQuery this way:
var $feedbar = $('#feedbar');
so in success function:
$feedbar.html('<div class="text-success">'+ data +'</div>');
so in error function:
$feedbar.html('<div class="text-success">'+ xhr.responseText +'</div>');

Categories

Resources