Product filter in Ajax will work in Wordpress - ajax

I have this code in Ajax but I want this to work in Wordpress. I just want to make a product filter in Ajax that will work in WordPress. I am just new to this. Any help and idea please?
<script>
$(document).ready(function(){
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var minimum_price = $('#hidden_minimum_price').val();
var maximum_price = $('#hidden_maximum_price').val();
var brand = get_filter('brand');
var ram = get_filter('ram');
var storage = get_filter('storage');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, minimum_price:minimum_price, maximum_price:maximum_price, brand:brand, ram:ram, storage:storage},
success:function(data){
$('.filter_data').html(data);
}
});
}
add_action( 'wp_ajax_action', 'filter_data' );
add_action( 'wp_ajax_action', 'filter_data' );
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
$('#price_range').slider({
range:true,
min:1000,
max:65000,
values:[1000, 65000],
step:500,
stop:function(event, ui)
{
$('#price_show').html(ui.values[0] + ' - ' + ui.values[1]);
$('#hidden_minimum_price').val(ui.values[0]);
$('#hidden_maximum_price').val(ui.values[1]);
filter_data();
}
});
});
</script>
How can I make an ajax call in wordpress without use of plugin?

Ajax code
<script type="text/javascript">
function filter_data(){
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var minimum_price = $('#hidden_minimum_price').val();
var maximum_price = $('#hidden_maximum_price').val();
var brand = get_filter('brand');
var ram = get_filter('ram');
var storage = get_filter('storage');
var data = {
action:action, minimum_price:minimum_price,
maximum_price:maximum_price, brand:brand, ram:ram,
storage:storage
};
$.post('/wp-admin/admin-ajax.php',data,function(response){
$('.filter_data').html(data);
});
}
</script>
In you function.php file
add_action('wp_ajax_fetch_data','filter_data'); // for loggedin user
add_action('wp_ajax_nopriv_fetch_data', 'filter_data'); // for non loggedin user
function filter_data()
{
$minimum_price = $_POST['minimum_price'];
$maximum_price = $_POST['maximum_price'];
$brand= $_POST['brand'];
$ram= $_POST['ram'];
$storage= $_POST['storage'];
// here your product filter code
}

Related

Ajax is not working with dimmer view

I am developing web based application in that I want to use dimmer view to add master information and as per this parent form needs to be refreshed.
In that dimmer view is working correctly but when I am trying to save values of child form in database using ajax but it doesn't work. If I removed ajax part it saves but it goes to the next page and I don't want this.
Here is my ajax code
<script type="text/javascript">
$(document).ready(function()
{
$('#enter1').click(function(e)
{
alert("In Ajax..");
e.preventDefault();
var ajaxdata = $("#v1").val();
var ajaxdata1 = $("#v2").val();
var ajaxdata2 = $("#v3").val();
var ajaxdata3 = $("#v4").val();
var ajaxdata4 = $("#v5").val();
var ajaxdata5 = $("#v6").val();
var ajaxdata6 = $("#v7").val();
var ajaxdata7 = $("#v8").val();
var ajaxdata8 = $("#v9").val();
var ajaxdata9 = $("#v10").val();
var ajaxdata10 = $("#v11").val();
var value ='v1='+ ajaxdata +'&v2='+ ajaxdata1 +'&v3='+ ajaxdata2 +'&v4='+ ajaxdata3 +'&v5='+ ajaxdata4 +'&v6='+ ajaxdata5 +'&v7='+ ajaxdata6 +'&v8='+ ajaxdata7 +'&v9='+ ajaxdata8 +'&v10='+ ajaxdata9 +'&v11='+ ajaxdata10 ;
alert(value);
$.ajax({
type:"get",
url: "MasterServlet",
data: value,
cache: false,
success: function(data)
{
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
return false;
});
});
</script>
And my jsp button
<input type="button" id="enter1" name="enter1" value="Submit">
Can any one suggest me how to save values of dimmer view form using ajax?

Knockout JS - update viewModel with AJAX Call

there are some similar questions but didn't help me to solve my issue. I can't update my results on page / view after updating my viewModel with AJAX. I am getting valid AJAX response that updates the view if I reload the page, but not when I click btnAdvancedSearch
I have simple HTML:
<div>
<input type="button" id="btnAdvancedSearch" data-bind="click: refresh" />
</div>
<div id="resultslist1" data-bind="template: { name: 'rest-template', foreach: restaurants }">
</div>
And I bind in on document load:
$(document).ready(function () {
ko.applyBindings(new RestaurantsListViewModel());
});
My viewModel is like this, and in it I call refresh that is bound with button
// Overall viewmodel for this screen, along with initial state
function RestaurantsListViewModel() {
var self = this;
self.restaurants = ko.observableArray([]);
var mappedRests = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants = mappedRests;
self.refresh = function () {
updateRestaurantsList(); //Method executes AJAX and saves result to session.
var mappedRests2 = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants= mappedRests2;
}
}
What am I missing here?
Thanks
I have tried waiting for AJAX to finish like this:
// Overall viewmodel for this screen, along with initial state
function RestaurantsListViewModel() {
var self = this;
self.restaurants = ko.observableArray([]);
var mappedRests = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants = mappedRests;
self.refresh = function () {
var latitude = sessionStorage.getItem('latitude');
var longitude = sessionStorage.getItem('longitude');
var query = '{"Accepts_Reservations":"' + $('#chkReservation').is(":checked") + '","Accepts_Cards":' + $('#chkAcceptsCards').is(":checked") + '"}';
var searchResults = getRestaurantsAdvancedSearchAJAX(query, latitude, longitude, 40);
searchResults.success(function (data) {
var information = data.d;
var mappedRests2 = $.map($.parseJSON(information), function (item) { return new Restaurant(item) });
self.restaurants = mappedRests2;
});
};
};
Edit 1
Once you have declared your observable like so:
self.restaurants = ko.observableArray([]);
When you want to update restaurants you cannot do this:
self.restaurants = mappedRests2;
Instead, you need to do this:
self.restaurants(mappedRests2);
updateRestaurantsList(); //Method executes AJAX and saves result to session.
The comment after the above line indicates that this method is making an asynchronous call. Therefore, it is likely that the line after it is executing before sessionStorage has been populated. Maybe consider having updateRestaurantsList return a promise. Then you could update your code to something like this:
updateRestaurantsList().then(function() {
var mappedRests2 = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants= mappedRests2;
});
This way the call to populate your mappedRests2 variable won't happen until after your updateRestaurantsList method has completed.
Edit 1
Be sure to never assign values to an observable using an equal sign.
// Overall viewmodel for this screen, along with initial state
function RestaurantsListViewModel() {
var self = this;
self.restaurants = ko.observableArray([]);
var mappedRests = $.map($.parseJSON(sessionStorage.getItem('searchResults')), function (item) { return new Restaurant(item) });
self.restaurants(mappedRests);
self.refresh = function () {
var latitude = sessionStorage.getItem('latitude');
var longitude = sessionStorage.getItem('longitude');
var query = '{"Accepts_Reservations":"' + $('#chkReservation').is(":checked") + '","Accepts_Cards":' + $('#chkAcceptsCards').is(":checked") + '"}';
var searchResults = getRestaurantsAdvancedSearchAJAX(query, latitude, longitude, 40);
searchResults.success(function (data) {
var information = data.d;
var mappedRests2 = $.map($.parseJSON(information), function (item) { return new Restaurant(item) });
self.restaurants(mappedRests2);
});
};
};

Issue with $(document).ready

I'v got two questions. First. How can I reduce this code?
$('#m').click(function() {
var href = $(this).attr('href');
$('#con').hide().load('inc/main.php').fadeIn('normal');
return false;
});
$('#b').click(function() {
var href = $(this).attr('href');
$('#con').hide().load('inc/blog.php').fadeIn('normal');
return false;
});
$('#p').click(function() {
var href = $(this).attr('href');
$('#con').hide().load('inc/portfolio.php').fadeIn('normal');
return false;
});
$('#l').click(function() {
var href = $(this).attr('href');
$('#con').hide().load('inc/lebenslauf.php').fadeIn('normal');
return false;
});
$('#k').click(function() {
var href = $(this).attr('href');
$('#con').hide().load('inc/kontakt.php').fadeIn('normal');
return false;
});
I'm using a lib called perfect scrollbar. It is included this way:
$(document).ready(function(a){a("#scrollbox").perfectScrollbar({wheelSpeed:20,wheelPropagation:!1})});
When main.php is loaded in with this script, the scrollbar is not there like it should be. It's because the document doesn't refresh like usual. What to I need to write to get it working when loaded in?
Write a function & pass each selector & filepath to this function
$('#m').click(some_function()
{
helperfunction($(this), 'inc/main.php');
});
function helperfunction(selector, phpfilepath) {
var href = selector.attr('href');
$('#con').hide().load(phpfilepath).fadeIn('normal');
return false;
}

upload progress div increase

function uploadToServer(){
fileField = document.getElementById("uploadedFile");
var fileToUpload = fileField.files[0];
var xhr = new XMLHttpRequest();
var uploadStatus = xhr.upload;
uploadStatus.addEventListener("progress", function (ev) {
if (ev.lengthComputable) {
$("#uploadPercentage").html((ev.loaded / ev.total) * 100 + "%");
}
}, false);
uploadStatus.addEventListener("error", function (ev) {$("#error").html(ev)}, false);
uploadStatus.addEventListener("load", function (ev) {$("#error").html("sorry!")}, false);
xhr.open(
"POST",
"serverUpload.php",
true
);
xhr.setRequestHeader("Cache-Control", "no-cache");
xhr.setRequestHeader("Content-Type", "multipart/form-data");
xhr.setRequestHeader("X-File-Name", fileToUpload.fileName);
xhr.setRequestHeader("X-File-Size", fileToUpload.fileSize);
xhr.setRequestHeader("X-File-Type", fileToUpload.type);
//xhr.setRequestHeader("Content-Type", "application/octet-stream");
xhr.send(fileToUpload);
}
$(function(){
$("#uploadButton").click(uploadToServer);
});
`
<form action="" name="uploadForm" method="post" enctype="multipart/form-data">
hi this code is working fine. but i need increase div size. but this one only showing percentage only. what i have to change to get dat one.
bellow is simple progressbar code using HTML5
<progress id="progressBar" value="0" max="100" style="width:300px;"></progress>
<span id="status"></span>
<h1 id="finalMessage"></h1>
<script type="text/javascript" language="javascript">
function progressBarSim(al) {
var bar = document.getElementById('progressBar');
var status = document.getElementById('status');
status.innerHTML = al+"%";
bar.value = al;
al++;
var sim = setTimeout("progressBarSim("+al+")",300);
if(al == 100){
status.innerHTML = "100%";
bar.value = 100;
clearTimeout(sim);
var finalMessage = document.getElementById('finalMessage');
finalMessage.innerHTML = "Process is complete";
}
}
var amountLoaded = 0;
progressBarSim(amountLoaded);
</script>
it may help you, fix this code in your coding.

MooTools - how to reload image?

Is there any way to reload the same image using mootools. I have a camera that gives me image, but I have to refresh it. I wrote this, but it doesn't work so well:
var url = "some valid url to some image.jpg";
var timer = 10;
var periodical;
var camera_container;
var refresh = (function() {
var loader = new Asset.image(url, {
onLoad : function() {
camera_container.empty();
camera_container.inject(loader);
}
});
});
window.addEvent('domready', function() {
// the periodical starts here, the * 1000 is because milliseconds required
refresh.periodical(timer * 1000, this);
camera_container = $('camera-image');
});
Any help appreciated. Thanks.
why not add a seeding bit to the url?
(function() {
var url = "some valid url to some image.jpg?";
this.timer = 10;
var counter = 0;
this.refresh = (function() {
var loader = new Asset.image(url + counter, {
onLoad: function() {
camera_container.empty();
camera_container.inject(loader);
counter++;
}
});
});
})();
window.addEvent('domready', function() {
// the periodical starts here, the * 1000 is because milliseconds required
refresh.periodical(timer * 1000, this);
this.camera_container = $('camera-image');
});
this way the url will always be path/image.jpg?n where n changes and will force the browser to re-fetch it.
I think something like this also can work:
<div id="image-holder">
<img src="http://www.image.com/image.jpg"/>
</div>
var srcImage = 'http://www.image.com/image.jpg';
var reloadTime = 4000;
var holder = document.id('image-holder');
var imageReload = function(){
holder.empty();
var newImage = new Element('img',{
id:'image',
src:srcImage ,
alt:'image new'
}).inject(holder);
}
var start = function() {
interval = imageReload.periodical(reloadTime);
};
start();

Resources