Ajax load different wordpress content based on user click - javascript

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.

Related

add loading text to javascript before html()

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
}
});

How do I go back in controller?

I have forms with id's formularregister and formularadresa and one button to submit with id comanda.
I want to submit both forms with one button (<a type="submit" id="comanda" class="btn btn-default" onclick="submitForms()">Finalizare comanda</a>) and go back to controller action (zend framework 2) to validate the values from post.
My JS function is this:
function submitForms() {
$(document).ready(function() {
$("#comanda").click(function() {
$.post($("#formularregister").attr("afisarecos.phtml"), $("#formularregister").serialize() + $("#formularadresa").serialize(), function() {
});
});
});
}
You need to make an AJAX request to your controller action. You'll find a lot of examples on the Web, but the most important parts to know for using Ajax in ZF2 are:
Enable ViewJsonStrategy in your /module/Application/config/module.config.php
'view_manager' => array(
// ....
'strategies' => array(
'ViewJsonStrategy',
),
),
Ajax request in your view
$.ajax({
url : 'url/to/yourController/action',
type: 'POST',
dataType: 'json',
data : fromData,
async: true,
success:function(data, textStatus, jqXHR)
{
//success function
}
error : function(xhr, textStatus, errorThrown)
{
// error function
}
});
In your controller action
if ($request->isXmlHttpRequest()) { //ajax call
// your logic here
$jsonModel = new JsonModel(
//...
);
return $jsonModel;
}
Please see this simple example (Code + Demo) for more details.

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');
}

Play framework JavaScript function as scala template parameter

I want to reuse a javascript function using a scala template so I would only have to pass a different success/failure function, but I don't seem to be able to able to pass a javascript function to a scala template.
Please note I'm veeeeerry new to this and don't even know if what I am doing is possible.
This is kind of what I'm trying to achieve:
#(formId: String, success: JavaScript, fail: JavaScript)
<script type="text/javascript">
$("#formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#success()
/*console.log("save succesfull, progress!")
alert('Save successfull, now move on!');*/
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
//if fails
#fail()
/*console.log(jqXHR.responseText);
var errors = JSON.parse(jqXHR.responseText);
console.log(errors);
alert('Woops, something went wrong: ' + jqXHR.responseText);*/
}
});
e.preventDefault();
});
</script>
How it would be used:
#snippets.ajaxFormSubmit("#form",
function()
{
alert("Save successfull, now move on!");
},
function()
{
alert("Save failed!");
}
)
You can pass any content to a template via Html type.
#(formId: String, success: Html, fail: Html)
<script type="text/javascript">
$("#formId").submit(function(e)
{
var data = $(this).serializeArray();
var action = $(this).attr("action");
$.ajax(
{
url : action,
type: "POST",
data : data,
success:function(data, textStatus, jqXHR) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#success
},
error: function(jqXHR, textStatus, errorThrown) // Change contents to dynamic parameter for scala??? perhaps a javascript function to execute???
{
#fail
}
});
e.preventDefault();
});
</script>
In a client view you can user it as follows:
#successFunc = {
alert("Save successfull, now move on!");
}
#failureFunc = {
alert("Save failed!");
}
#snippets.ajaxFormSubmit("#form", successFunc, failureFunc)

Sending email via AJAX - showing progress/status

I'm using jQuery 1.11.1 and jQuery validation plugin
I have added the following script to my contact form to validate it and send via AJAX ({{hash_tag}} in code is Twig variable):
<script>
$("#contactform").validate({
rules: {
content_{{ hash_tag }}: {
required: true,
minlength: 20
},
name_{{ hash_tag }}: {
required: true,
minlength: 2
},
subject_{{ hash_tag }}: {
required: true,
minlength: 10
},
email_{{ hash_tag }}: {
required: true,
email: true
}
},
submitHandler: function(form) {
var postData = $(form).serializeArray();
var formURL = $(form).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
$('#articlecontent').html(data.content);
$("html, body").animate({ scrollTop: 0 });
},
error: function(jqXHR, exception)
{
$(form).submit();
}
});
}
});
</script>
The script (after small testing) seems to work. But the problem is - when user have filled in form correctly and when PHP is sending email it may take a few seconds. User after clicking submit button of course doesn't have to know that form is send via AJAX and may think that something is not working ok and may for example click again or do something else.
The question is - how to show user that after clicking something is happening and email will be send in a few seconds? I don't know what's the best practice to do that. Please give me some nice solution. Progress bar is not necessary I think (it's probably hard to determine how long it would take) but maybe some other effect would be fine.
EDIT
After changing submitHandler I have now:
submitHandler: function(form) {
var postData = $(form).serializeArray();
var formURL = $(form).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
beforeSend: function (){
$(form).hide();
$("#formsending").show();
},
success:function(data, textStatus, jqXHR)
{
$('#articlecontent').html(data.content);
$("html, body").animate({ scrollTop: 0 });
},
error: function(jqXHR, exception)
{
$(form).submit();
},
complete: function (){
$("#formsending").hide();
$(form).show();
}
});
}
It works somehow but still not exactly 100% I wanted. When I click send, form is being hidden and info that email is sending is being displayed but on server-site I have also data validation. Let's assume some complex validation cannot be done by jQuery/HTML5 and it must be done in PHP. When user clicks submit even form is invalid for a small time info that email is being sent is displayed. Is it possible somehow to launch beforeSend (or maybe some similar action) for example after second or 0.5 second to make sure that email is in fact being sent?
There is a nice plug in to show a progress wheel whenever an ajax request is in progress.
jQuery BlockUI
This is especially nice since it will automatically show a progress wheel for any ajax request, so you don't have to specifically set it up everywhere you make ajax calls.
Using this plug in the only code you need to write is
$(document).ajaxStart($.blockUI).ajaxStop($.unblockUI);
EDIT (from question update)
If you want to only show the progress spinner when the validation is successful and the email is actually being sent then you could have a separate ajax call that just performs validation and doesn't show any kind of progress (it should not take too long just to validate) and then if that call is successful make a separate ajax call that actually sends the email and does show the spinner.
Example:
submitHandler: function(form) {
var postData = $(form).serializeArray();
var formURL = $(form).attr("action");
var validateURL = "something else";
$.ajax({
url : validateURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
if(data.MyFieldThatIndicatesSuccess) {
$.ajax({
url : formURL,
type: "POST",
data : postData,
beforeSend: function (){
$(form).hide();
$("#formsending").show();
},
success: function(data, textStatus, jqXHR) {
$('#articlecontent').html(data.content);
$("html, body").animate({ scrollTop: 0 });
},
error: function(jqXHR, exception) {
//handle error
}
complete: function (){
$("#formsending").hide();
$(form).show();
}
});
}
},
error: function(jqXHR, exception)
{
//handle error
}
});
}
If I understand your problem correctly, what you would like is some message or animation to show when the user presses submit and it to go away again once the php has done its thing?
If so you would just have to add some code at the commented areas to show/hide an element that shows a message or a spinner.
submitHandler: function(form) {
var postData = $(form).serializeArray();
var formURL = $(form).attr("action");
//Some code to make a div appear e.g.
//$("#contactform").append("<div class='loading'><img src='spinner.gif'></div>");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//some code to make the div disapear e.g.
//$(".loading").remove();
$('#articlecontent').html(data.content);
$("html, body").animate({ scrollTop: 0 });
},
error: function(jqXHR, exception)
{
$(form).submit();
}
});
}

Categories

Resources