I have method who populate menu, it be like:
function MenuPopulate(url, listname, target) {
var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
lang = "English";
}
$(function () {
$.ajax({
url: "https://myapi.company.com/api/myapi/getmenu?idioma=" + lang ,
async: false,
type: 'GET',
dataType: "json",
success: function (data) {
console.log(data);
completeMenu(data, target)
//localStorage.setItem('data', JSON.stringify(data))
},
error: function (response) {
failureMenu(response, target)
}
});
});
}
function completeMenu(data, target) {
var prefix = "<ul class='nav navbar-nav navbar-right'>";
var sufix = "</ul>";
var items = data;
var menu = "";
for (item in items) {
if(items[item].Titile == "JOIN US" ){
menu += "<li><a href='#mymodal' data-toggle='modal' data-target='#mymodal'>" + items[item].Titile + "</a></li><li class='divider-vertical'></li>"
}
else if(items[item].Titile == "CONTACT US"){
menu += "<li><a href='#mymodal2' data-toggle='modal' data-target='#mymodal2'>" + items[item].Titile + "</a></li><li class='divider-vertical'></li>"
}
else{
menu += "<li>" + items[item].Titile + "</li><li class='divider-vertical'></li>";
}
}
$(target).html(prefix + menu + sufix);
}
function failureMenu(data, target) {
console.log(data);
$(target).text("Ocurrió un error en la carga del menú. Por favor revise la consola para más información");
}
And it runs perfectly except for the time to load page, so now I store methods in cache with localStorage , so I made this class:
$(document).ready(function() {
GetGlobal();
});
function GetGlobal() {
var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
lang = "English";
}
var page = window.location.pathname.replace("/SitePages/", "");
if (localStorage.getItem("Menu") == null) {
$.ajax({
url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
async: false,
type: 'GET',
dataType: "json",
success: function(data) {
CompleteGlobal(data);
//alert("Cargo con exito");
},
error: function(data) {
//failureGlobal(data);
alert("No cargo");
}
})
} else {
// alert("la cookie esta cargada");
CargaGlobal();
//localStorage.getItem("Menu")
}
}
function CargaMenu() {
$.ajax({
url: "https://myapi.company.com/api/myapi/getmenu?idioma=" + lang,
async: false,
cache:true,
type: 'GET',
dataType: "json",
success: function(data) {
console.log(data);
completeMenu(data, target)
},
error: function(response) {
failureMenu(response, target)
}
});
}
function CompleteGlobal(data) {
data.Menu //lista de menus
data.Pie // lista pie de pagina
data.Mapa
data.Ligas
localStorage.setItem("Menu", JSON.stringify(data.Menu));
localStorage.setItem("Pie", JSON.stringify(data.Pie));
localStorage.setItem("Mapa", JSON.stringify(data.Mapa));
localStorage.setItem("Ligas", JSON.stringify(data.Ligas));
localStorage.setItem("Enlace", JSON.stringify(data.Enlace));
CargaGlobal();
}
function CargaGlobal() {
completeMenu(JSON.parse(localStorage.getItem("Menu")), "#BarraNavegacion");
completeSiteMap(JSON.parse(localStorage.getItem("Mapa")), "#MapaSitio");
completeImgLinks(JSON.parse(localStorage.getItem("Enlace")), "#EnlacesImagen");
completeFooter(JSON.parse(localStorage.getItem("Pie")), "#Footer");
}
function completeBanner3(target) {
var items = localStorage.getItem("Menu");
var menu = "";
for (var item in items) {
menu += "<div class='col-md-4 text-center'><div><a href='" + items[item].Enlace + "'><img src='" + items[item].Imagen + "' class='img-responsive img-center' /></a></div><div class='t02 text-center'>" + items[item].Titulo + "</div><div class='t03 text-center'>" + items[item].Descripcion + "</div></div>";
}
$(target).html(menu);
}
But when I change language of my site it just no load the other language menu, and I think to load cookie again if language is different to "Espanol" so I think I can do something like
if (localStorage.getItem("Menu") == null && lang == "Espanol") {
$.ajax({
url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
async: false,
type: 'GET',
dataType: "json",
success: function(data) {
CompleteGlobal(data);
//alert("Cargo con exito");
}else if(localStorage.getItem("Menu") == null && lang == "English"){
$.ajax({
url: "https://myapi.company.com/api/myapi/getglobalresources?idioma=" + lang + "&pagina=" + page,
async: false,
type: 'GET',
dataType: "json",
success: function(data) {
CompleteGlobal(data);
},
error: function(data) {
alert("No cargo");
}
})
} else {
CargaGlobal();
}
}
But it doesn´t works, any idea what I need to do in this case? Regards
Instead of saving individual parts to the localStorage, sometimes it's easier just to get and fetch an object by using JSON.parse and JSON.stringify.
This is a rather long example, but I commented it a lot to try to make it easier to follow. It's an illustration of various concepts so it doesn't exactly solve your problem, but I believe it will get you closer to a solution.
EDIT: The StackOverflow script runner does not like localStorage. Here's a JSFiddle to see it in action: https://jsfiddle.net/subterrane/9prr5ks6/
EDIT, EDIT: Also, I don't speak Spanish, so blame Google Translate for the silly menu button labels.
var lang = "Espanol";
if ((window.location.href.indexOf("lang=en") > 0)) {
lang = "English";
}
// function to getMenuData
function getMenuData() {
// get the saved data from localStorage
var menuData = JSON.parse(localStorage.getItem('menuData'));
// if it doesn't exist, or if our language is missing, fetch the data from the server
if (menuData == null || menuData[lang] == null) {
// this is a stub function. Pretend it's doing an ajax request
// the second argument here is a callback function. It would be
// the ajax success function.
fetchMenuData(lang, function(data) {
// if we did have some of the data, use it, or start with an empty object
menuData = menuData || {};
// set the server response to the menuData object
menuData[lang] = data;
// stringify the object and stash it in localStorage
localStorage.setItem('menuData', JSON.stringify(menuData));
// display the menu
displayMenu(menuData);
});
} else {
// we go the data from the cache, so display the menu
displayMenu(menuData);
}
}
// this is a fake function that pretends to get menuData from a server
function fetchMenuData(lang, callback) {
// wait 2 seconds, then call the response function
setTimeout(response, 2000);
// response function sends some data back to the callback depending on the requested language
function response() {
callback(lang == "Espanol" ? [{
name: 'Casa',
link: 'something.html'
}, {
name: 'Lejos',
link: 'somethingelse.html'
}] : [{
name: 'Home',
link: 'something.html'
}, {
name: 'Away',
link: 'somethingelse.html'
}]);
}
}
// function to display the menu
function displayMenu(data) {
// update the text in some of the buttons
document.getElementById('home').innerHTML = data[lang][0].name;
document.getElementById('away').innerHTML = data[lang][1].name;
// looks kinda funny, but this just puts the opposite of the current language
// on the button to make it feel like a toggle button
document.getElementById('toggle').innerHTML = lang == "Espanol" ? "English" : "Espanol";
// show the menu now that it's filled in
document.getElementById('menu').classList.remove('hide');
}
// set up a click handler on the language toggle button
document.getElementById('toggle').addEventListener('click', function() {
// hide the menu while we mess with it. Could take a while to get the menu
// data back from our 'server'
document.getElementById('menu').classList.add('hide');
// set the language to the opposite of whatever it was before
lang = lang == "Espanol" ? "English" : "Espanol";
// get the menu data from the cache or server
getMenuData();
});
// kick it all off by getting the menu data from the server
getMenuData();
.hide {
display: none;
}
<link href="//cdnjs.cloudflare.com/ajax/libs/skeleton/2.0.4/skeleton.min.css" rel="stylesheet" />
<div class="container">
<div id="menu" class="hide">
<button id="home"></button>
<button id="away"></button>
<button id="toggle"></button>
</div>
</div>
Related
I want to make the option I selected fix to after AJAX POST.
Currently I am doing the work manually.
I put the value at OnChange in the HiddenField,
and after doing AJAX POST, re-insert the value selected in "ddlUserCont".
<select id="ddlUserCont" onchange="ddlUserCont_Onchange(this);"></select>
function ddlUserCont_Onchange(obj) {
document.getElementById("<%=hidSelddlUserCont.ClientID %>").value = obj.value;
}
-> After AJAX POST action..
function btnTest_Click() {
// ... Some logic
$.ajax({
type: "POST",
cache: false,
url: "../../WebServices/WebService.asmx/GetTest",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
OnSuccess_GetTest(data, sTestVal);
},
error: function (request, status, error) {
console.log("code:" + request.status + "\n" + "message:" + request.responseText + "\n" + "error:" + error);
}
});
}
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value;
document.getElementById("ddlUserCont_" + sSelPageName).selected = "true";
}
Do I use UpdatePanel ?
Why is it getting reset? is the page reloading? or is some other script resetting it?
function OnSuccess_GetTest(response, sTestVal) {
var items = response.d;
// ... Some logic
var sSelPageName = document.getElementById("<%=hidSelddlUserCont.ClientID %>").value; // get the value from the hidden field
document.getElementById("ddlUserCont).value = sSelPageName; // set it on the select options element
}
Just make sure that select has an option child element with value=<sSelPageName> at the time.
My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
I have a connection with my DB and my DB sends me some integer value like "1","2" or something like that.For example if my DB send me "3" I display the third page,it's working but my problem is when it displays the third page it's not hide my current page.I think my code is wrong in somewhere.Please help me
<script>
function show(shown, hidden) {
console.log(shown,hidden)
$("#"+shown).show();
$("#"+hidden).hide();
}
$(".content-form").submit(function(){
var intRowCount = $(this).data('introwcount');
var exec = 'show("Page"+data.result,"Page' + intRowCount + '")';
ajaxSubmit("/post.php", $(this).serialize(), "", exec,"json");
return false;
})
function ajaxSubmit(urlx, datax, loadingAppendToDiv, resultEval, dataTypex, completeEval) {
if (typeof dataTypex == "undefined") {
dataTypex = "html";
}
request = $.ajax({
type: 'POST',
url: urlx,
dataType: dataTypex,
data: datax,
async: true,
beforeSend: function() {
$(".modalOverlay").show();
},
success: function(data, textStatus, jqXHR) {
//$("div#loader2").remove();
loadingAppendToDiv !== "" ? $(loadingAppendToDiv).html(data) : "";
if (typeof resultEval !== "undefined") {
eval(resultEval);
} else {
//do nothing.
}
},
error: function() {
alert('An error occurred. Data does not retrieve.');
},
complete: function() {
if (typeof completeEval !== "undefined") {
eval(completeEval);
} else {
//do nothing.
}
$(".modalOverlay").hide();
}
});
}
</script>
Thanks for your helping my code working fine now.The problem is occured because of the cache. When I clear cache and cookies on Google Chrome it fixed.
The second parameter passed into the show() method is a bit wrong:
"Page' + intRowCount + '"
Perhaps you meant:
'Page' + intRowCount
Edit: wait wait you pass in a string of code to ajaxSubmit? What happens inside it?
If ajaxSubmit can use a callback, try this:
var exec = function(data) {
show('Page' + data.result, 'Page' + intRowCount);
};
Assuming your html is:
<div id='Page1'>..</div>
<div id='Page2'>..</div>
<div id='Page3'>..</div>
add a class to each of these div (use a sensible name, mypage just an example)
<div id='Page1' class='mypage'>..</div>
<div id='Page2' class='mypage'>..</div>
<div id='Page3' class='mypage'>..</div>
pass the page number you want to show and hide all the others, ie:
function showmypage(pageselector) {
$(".mypage").hide();
$(pageselector).show();
}
then change your 'exec' to:
var exec = 'showmypage("#Page"+data.result)';
It would be remiss of my not to recommend you remove the eval, so instead of:
var exec = "..."
use a function:
var onsuccess = function() { showmypage("#Page"+data.result); };
function ajaxSubmit(..., onsuccess, ...)
{
...
success: function(data) {
onsuccess();
}
}
I have an ajax request, whereby I am installing a magento shop automatically, and when the process is done, it would redirect the user to the newly created shop. Here are my codes:
function postSuccessFormData() {
var targetUrl = '/index.php/install/wizard/successPost';
jQuery('.form-button').addClass('loading');
setInterval(installStatus(),4000);
jQuery.ajax({
url: targetUrl,
global: false,
type: 'POST',
data: ({
finish: 1,
password_key: jQuery('#password_key').val()
}),
async: true,
dataType: 'json',
error: function() {
alert("An error has occurred. Please try again.");
},
success: function(data) {
window.location.href = '/';
}
});
function installStatus() {
var installerUpdatesUrl = '/index.php/install/wizard/installerStatus';
//showProgressBar();
jQuery.ajax({
url: installerUpdatesUrl,
// global: false,
type: 'GET',
async: true,
dataType: 'json',
error: function (data) {
// alert(data.result);
},
success: function (data) {
handle data.result
var dataKeys = Object.keys(data);
var lastElementKey = dataKeys[dataKeys.length - 1];
var lastMessage = data[lastElementKey]['message'];
if(data[lastElementKey]['progress'] == '') {
updateProgressBar(data[dataKeys[dataKeys.length - 2]]['progress'],100);
}
setting message
jQuery("#message").html(lastMessage);
if (data[lastElementKey]['state'] == 'Failure') {
var stepStr = lastElementKey.split('_');
var stepString = stepStr[0].toUpperCase() + ' ' + stepStr[1] + ':';
alert(stepString + "\n" + data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
return false;
} else if (data[lastElementKey]['state'] == 'Finish') {
alert(data[lastElementKey]['message']);
//hideProgressBar();
jQuery('.form-button').removeClass('loading');
//window.location.href = '/';
} else {
// installStatus();
}
},
complete: function () {
installStatus();
jQuery('.form-button').removeClass('loading');
}
});
}
The way this is done:
After every 4 seconds the function installStatus is run, which will output the current progress in JSON format. My problem is, this function needs to be executed simultaneously with the function post().
This is not happening, the installStatus is only run after the first function has been completed.
What is wrong?
You are executing installStatus when you define it. So this:
setInterval(installStatus(),4000);
needs to be
setInterval(installStatus, 4000);
The new XMLHttpRequest has a nice progress event you can listen to show the user the upload progress.
Here's the spec with a nice demo: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress
Initially you should call installStatus() only once and then inside the method inside ajax success you should update the procent in the progress bar and call it recursively the same method. On the server side you can save the current procent in a cookie and with every recursive call you can update the cookie and return the procent.
I am trying to craft an AJAX form to display a success/failure/share message via a Fancybox once a user submits their email address on a form. Currently, the code throws the response up to the top of the page.
I have attempted a few variations from other answers provided here here, and here on Stack Overflow, but to no avail, as upon insertion the entire form ceases to load.
My current init.js is as follows:
$("#form").submit(function(e){
e.preventDefault();
leSubmitLoader();
dataString = $("#form").serialize();
var templateURL = $('#templateURL').attr('value');
var blogURL = $('#blogURL').attr('value');
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json",
success:
function(data) {
$.fancybox(
'<p>Content of the box in HTML</p>',
{
padding:15,
closeBtn:true
}
);
function leSubmit(returning){
$.fancybox(
);
$('#form, #error, #presignup-content').hide();
$('#success').fadeIn(function(){
var successScroll = $('#signup-body').offset().top - 20;
$('html,body').animate({scrollTop:successScroll}, 300);
});
if (returning == true) {
$('#returninguser, #returninguserurl').show();
var refCode = data.returncode;
$('#returninguser span.user').text(data.email);
$('#returninguser span.clicks').text(data.clicks);
$('#returninguser span.conversions').text(data.conversions);
$('#returninguserurl input#returningcode').attr('value', blogURL + '/?ref=' + refCode);
} else {
$('#success-content, #newuser').show();
var refCode = data.code;
$('#newuser input#successcode').attr('value', blogURL + '/?ref=' + refCode);
if(data.pass_thru_error == "blocked"){
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html('AWeber Sync Error: Email Blocked.');
} else if (data.pass_thru_error.AWeberAPIException != undefined){
err = data.pass_thru_error.AWeberAPIException;
$('#pass_thru_error').fadeIn();
$('#pass_thru_error').html(err.type+': '+err.msg);
}
}
// Referral URL
var refUrl = blogURL + '/?ref=' + refCode;
// Twitter (note: refUrl might not show up in share box on localhost)
var tweetUrl = 'http://twitter.com/intent?url=' + encodeURIComponent(refUrl);
var tweetMessage = $('input#twitterMessage').attr('value');
$('#tweetblock').html('Tweet<script>!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0];if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src="//platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");</script>');
// Facebook (note: won't work on localhost)
$("#fblikeblock").html('<div class="fb-like" data-ref="'+refCode+'" data-href="'+refUrl+'" data-send="false" data-width="75" data-show-faces="false" data-font="arial" data-layout="button_count"></div>');
// Google +
function renderPlusone() {
gapi.plusone.render('plusoneblock', {'href':refUrl, 'size':'tall', 'annotation':'none'});
}
renderPlusone();
// Tumblr
var tumblr_button = document.createElement("a");
tumblr_button.setAttribute("href", "http://www.tumblr.com/share/link?url=" + encodeURIComponent(refUrl) + "&name=" + encodeURIComponent(tumblr_link_name) + "&description=" + encodeURIComponent(tumblr_link_description));
tumblr_button.setAttribute("title", "Share on Tumblr");
tumblr_button.setAttribute("onclick", "window.open(this.href, 'tumblr', 'width=460,height=400'); return false;");
tumblr_button.setAttribute("style", "display:inline-block; text-indent:-9999px; overflow:hidden; width:81px; height:20px; background:url('http://platform.tumblr.com/v1/share_1.png') top left no-repeat transparent;");
tumblr_button.innerHTML = "Share on Tumblr";
document.getElementById("tumblrblock").appendChild(tumblr_button);
// RinkedIn
$('#linkinblock').html('<script src="http://platform.linkedin.com/in.js" type="text/javascript"></script><script type="IN/Share" data-url="'+refUrl+'"></script>');
}
if(data.email_check == "invalid") {
leSubmitLoaderStop();
$('#error').html('This email address is invalid.').fadeIn();
}
else if(data.required.length) {
leSubmitLoaderStop();
$('.error').hide();
$d = String(data.required).split(",");
$.each($d, function(k, v){
$("#" + v + ".error").fadeIn();
});
}
else {
if(data.reuser == "true") {
leSubmit(true);
FB.XFBML.parse(document.getElementById('fblikeblock'));
} else {
leSubmit(false);
FB.XFBML.parse(document.getElementById('fblikeblock'));
}
$('body').addClass('submission-success');
}
}
});
});
I am not trying to fix your code but why you don't use this ajax format to handle success/failure ?
$.ajax({
type: "POST",
url: templateURL + "/post.php",
data: dataString,
dataType: "json"
}).done(function () {
//success
$.fancybox("success", {
// options
});
}).fail(function () {
//error
$.fancybox("failure", {
// options
});
}).always(function () {
// optional after ajax is completed
$.fancybox("else", {
// options
});
});