making a ajax live load - javascript

can anyone know how can I make this as an ajax live load?
unfortunately, I have limited acknowledge about javascript/jquery/ajax
simply I want to load the search result on ajax live load
This is my javascript code to load the data but it will refresh the page
I want to not refresh the page and load the data on live load
<script type="text/javascript">
function get_url() {
var urlPrefix = 'https://example.com/home/courses?'
var urlSuffix = "";
var slectedCategory = "";
var selectedLevel = "";
var selectedIelts = "";
var selectedCountry = "";
var selectedPtype = "";
var selectedDtype = "";
var selectedLanguage = "";
var selectedRating = "";
//Get selected category
$('.categories:checked').each(function() {
selectedCategory = $(this).attr('value');
});
// Get selected countries
if($("#country-search-value-unique").val() != 'all'){
selectedCountry = $("#country-search-value-unique").val();
};
if($("#ielts-search-value-unique").val() != 'all'){
selectedIelts = $("#ielts-search-value-unique").val();
};
if($("#ptype-search-value-unique").val() != 'all'){
selectedPtype = $("#ptype-search-value-unique").val();
};
if($("#dtype-search-value-unique").val() != 'all'){
selectedDtype = $("#dtype-search-value-unique").val();
};
if($("#level-search-value-unique").val() != 'all'){
selectedLevel = $("#level-search-value-unique").val();
};
if($("#price-search-value-unique").val() != 'all'){
selectedPrice = $("#price-search-value-unique").val();
};
// Get selected difficulty Level
$('.languages:checked').each(function() {
selectedLanguage = $(this).attr('value');
});
// Get selected rating
$('.ratings:checked').each(function() {
selectedRating = $(this).attr('value');
});
urlSuffix = "category="+selectedCategory+"&&level="+selectedLevel+"&&ielts="+selectedIelts+"&&country="+selectedCountry+"&&ptype="+selectedPtype+"&&dtype="+selectedDtype+"&&language="+selectedLanguage+"&&rating="+selectedRating;
var url = urlPrefix+urlSuffix;
return url;
}
function filter() {
var url = get_url();
window.location.replace(url);
//console.log(url);
}
function toggleLayout(layout) {
$.ajax({
type : 'POST',
url : 'https://example.com/home/set_layout_to_session',
data : {layout : layout},
success : function(response){
location.reload();
}
});
}
function showToggle(elem, selector) {
$('.'+selector).slideToggle(20);
if($(elem).text() === "show_more")
{
$(elem).text('show_less');
}
else
{
$(elem).text('show_more');
}
}
$(document).on('click', '.catparent-label', function(e) {
$(this).next('ul').fadeIn(); $('li.has').removeClass('is-active'); $('ul.tree').addClass('has-selection'); $('ul.tree').find("label").removeClass('is-seleted'); $(this).closest('li').addClass('is-active'); $(this).addClass('is-seleted'); $('ul.tree').find("input[type='checkbox']"); $(this).closest('li').find(".catparent"); $('.BackListDisciplines').show(); StudyFilter(); e.stopPropagation()
}
); $(document).on('click', '.subcat-label', function(e) {
$('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').find("input[type='checkbox']").prop('checked', !1); $(this).addClass('is-seleted'); $(this).closest('li').find(".subcat"); StudyFilter(); e.stopPropagation()
}
); $(document).on('click', '.BackListDisciplines', function(e) {
$('li.has').removeClass('is-active'); $('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').removeClass('has-selection'); $('.tree ul').hide(); $('ul.tree').find("input[type='checkbox']"); $('.BackListDisciplines').hide(); StudyFilter()
}
);
</script>

Related

AJAX upload script uncaught Reference error app not defined

I have a file upload page that uses ajax to show a progress bar and has a drag and drop feature (global.js and upload.js). But the progress bar and the drag and drop does not work. I get a Uncaught Reference error app not definded in my global.js. However, I have app defined in upload.js. Why does it complain about app not being defined? Thank you.
// global.js
(function() {
"use strict";
var dropZone = document.getElementById('drop-zone');
var barFill = document.getElementById('bar-fill');
var barFillText = document.getElementById('bar-fill-text');
var uploadsFinished = document.getElementById('uploads-finished');
var startUpload = function(files) {
app.uploader({
files: files,
progressBar: barFill,
progressText: barFillText,
processor: 'upload.php',
finished: function(data) {
var x;
var uploadedElement;
var uploadedAnchor;
var uploadedStatus;
var currFile;
for(x = 0; x < data.length; x = x + 1) {
currFile = data[x];
uploadedElement = document.createElement('div');
uploadedElement.className = 'upload-console-upload';
uploadedAnchor = document.createElement('a');
uploadedAnchor.textContent = currFile.name;
if(currFile.uploaded) {
uploadedAnchor.href = 'uploads/' + currFile.file;
}
uploadedStatus = document.createElement('span');
uploadedStatus.textContent = currFile.uploaded ? 'Uploaded' : 'Failed';
uploadedElement.appendChild(uploadedAnchor);
uploadedElement.appendChild(uploadedStatus);
uploadsFinished.appendChild(uploadedElement);
}
uploadsFinished.className = '';
},
error: function() {
console.log('There was an error');
}
});
};
// Standard form upload
document.getElementById('standard-upload').addEventListener('click', function(e) {
var standardUploadFiles = document.getElementById('standard-upload-files').files;
e.preventDefault();
startUpload(standardUploadFiles);
});
// Drop functionality
dropZone.ondrop = function(e) {
e.preventDefault();
this.className = 'upload-console-drop';
startUpload(e.dataTransfer.files);
};
dropZone.ondragover = function() {
this.className = 'upload-console-drop drop';
return false;
};
dropZone.ondragleave = function() {
this.className = 'upload-console-drop';
return false;
};
}());
// upload.js
var app = app || {};
(function(o) {
"use strict";
// Private methods
var ajax, getFormData, setProgress;
ajax = function(data) {
var xmlhttp = new XMLHttpRequest();
var uploaded;
xmlhttp.addEventListener('readystatechange', function() {
if(this.readyState === 4) {
if(this.status === 200) {
uploaded = JSON.parse(this.response);
if(typeof o.options.finished === 'function') {
o.options.finished(uploaded);
}
} else {
if(typeof o.options.error === 'function') {
o.options.error();
}
}
}
});
xmlhttp.upload.addEventListener('progress', function(e) {
var percent;
if(e.lengthComputable === true) {
percent = Math.round((event.loaded / event.total) * 100);
setProgress(percent);
}
});
xmlhttp.open('post', o.options.processor);
xmlhttp.send(data);
};
getFormData = function(source) {
var data = new FormData();
var i;
for(i = 0; i < source.length; i = i + 1) {
data.append('files[]', source[i]);
}
return data;
};
setProgress = function(value) {
if(o.options.progressBar !== undefined) {
o.options.progressBar.style.width = value ? value + '%' : 0;
}
if(o.options.progressText !== undefined) {
o.options.progressText.textContent = value ? value + '%' : '';
}
};
o.uploader = function(options) {
o.options = options;
if(o.options.files !== undefined) {
ajax(getFormData(o.options.files));
}
};
}(app));
The variable app is define inside the upload.js file. I thinks you should just load Upload.js before global.js
<script src="/javascripts/upload.js" type="text/javascript"></script>
<script src="/javascripts/global.js" type="text/javascript"></script>

JavaScript success message disappear

HTML button:
<button type="submit" class="btn btn-default" id="addBtn" onclick="addfunction();">Add</button>
addfunction() code:
var title = document.getElementById("TitleInput").value;
var ID = firebase.database().ref().child('emp').push().key;
//upload pic
var filename = selectionfile;
filename = newsID;
var storageRef = firebase.storage().ref(filename);
var uploadTask = storageRef.put(selectionfile);
if (user != null) {
userid = user.uid;
var Dataa = {
ID: ID,
title: title,
};
var updates = {};
updates['/emp/' + ID] = Dataa;
var returnUpdate = firebase.database().ref().update(updates);
if (returnUpdate) {
var mess = document.getElementById("confirm_mess");
mess.setAttribute("class", "bg-success h4");
mess.setAttribute("style", "padding: 1%; margin: 1% 9% 0 35%");
mess.innerHTML = "done";
}
}
}
and this is the validation code
$(function () {
$("#title_span").hide();
var error_title = false;
$("#TitleInput").focusout(function () {
Title_validation();
});
function Title_validation() {
var title = $("#TitleInput").val();
if (title == "") {
$("#title_span").html("wrong input");
$("#title_span").show();
error_title = true;
}
else {
$("#title_span").hide();
}
}
$("#my_form").submit(function () {
error_title = false;
Title_validation();
if (error_title == false) {
return true;
}
else {
return false;
}
});
});
my problem is, when i click the add button, "done" message disappear immediately because the refreshing, i want the message to appear for few second and then refresh the page. how can i do that? knowing that i try to use setTimeout but it does not work.
Change type="submit" to type="button"
If your button has to submit a form remove the type="submit", change the <button> tag to <a> and change your code to the following. You also have to add an ID to your form:
<script>
addfunction() {
var title = document.getElementById("TitleInput").value;
var ID = firebase.database().ref().child('emp').push().key;
if (user != null) {
userid = user.uid;
var Dataa = {
ID: ID,
title: title,
};
var updates = {};
updates['/emp/' + ID] = Dataa;
var returnUpdate = firebase.database().ref().update(updates);
if (returnUpdate) {
var mess = document.getElementById("confirm_mess");
mess.setAttribute("class", "bg-success h4");
mess.setAttribute("style", "padding: 1%; margin: 1% 9% 0 35%");
mess.innerHTML = "done";
}
setTimeout(function () { //wait 5 seconds
document.getElementById(yourForm).submit; //submit your form
}, 5000);
}
}
</script>
OR show the message after everything is send. I think you use a form to submit your data. just add to your <form> action=?done=true
Then you call the script if the variable 'done' is true:
<?php
if (isset($done)) {
echo "<script>your script</script>"; //or do whatever you want if the var is true
}
?>

How to send javascript variable to php to change the file name of the uploaded file?

How to change the filename for the upload to id+filename?
Example:
I have the id in a javascript variable item_id.
Is there a chance to add data on data.append and use this in the "upload.php"?
I want that the file name have instead of time and date the prefix id. Example id = 00002, file name = "picturewhatever.jpg".
The to be uploaded file should be "00002PictureWhatever.jpg"
<div id="mulitplefileuploader" title="">
<br>
Upload
</div>
<div id="status"></div>
<script>
$(document).ready(function() {
var settings = {
url: "upload.php",
method: "POST",
allowedTypes:"jpg,png,gif",
fileName: "myfile",
multiple: true,
onSuccess:function(files,data,xhr) {
$("#status").html("<font color='green'>Upload successful</font>");
},
onError: function(files,status,errMsg) {
$("#status").html("<font color='red'>Upload failed</font>");
}
}
$("#mulitplefileuploader").uploadFile(settings);
});
</script>
</div>
File: multifileuploader.js
function multiUploader(config){
this.config = config;
this.items = "";
this.all = []
var self = this;
multiUploader.prototype._init = function(){
if (window.File &&
window.FileReader &&
window.FileList &&
window.Blob) {
var inputId = $("#"+this.config.form).find("input[type='file']").eq(0).attr("id");
document.getElementById(inputId).addEventListener("change", this._read, false);
document.getElementById(this.config.dragArea).addEventListener("dragover", function(e){ e.stopPropagation(); e.preventDefault(); }, false);
document.getElementById(this.config.dragArea).addEventListener("drop", this._dropFiles, false);
document.getElementById(this.config.form).addEventListener("submit", this._submit, false);
} else
console.log("Browser supports failed");
}
multiUploader.prototype._submit = function(e){
e.stopPropagation(); e.preventDefault();
self._startUpload();
}
multiUploader.prototype._preview = function(data){
this.items = data;
if(this.items.length > 0){
var html = "";
var uId = "";
for(var i = 0; i<this.items.length; i++){
uId = this.items[i].name._unique();
var sampleIcon = '<img src="images/image.png" />';
var errorClass = "";
if(typeof this.items[i] != undefined){
if(self._validate(this.items[i].type) <= 0) {
sampleIcon = '<img src="images/unknown.png" />';
errorClass =" invalid";
}
html += '<div class="dfiles'+errorClass+'" rel="'+uId+'"><h5>'+sampleIcon+this.items[i].name+'</h5><div id="'+uId+'" class="progress" style="display:none;"><img src="images/ajax-loader.gif" /></div></div>';
}
}
$("#dragAndDropFiles").append(html);
}
}
multiUploader.prototype._read = function(evt){
if(evt.target.files){
self._preview(evt.target.files);
self.all.push(evt.target.files);
} else
console.log("Failed file reading");
}
multiUploader.prototype._validate = function(format){
var arr = this.config.support.split(",");
return arr.indexOf(format);
}
multiUploader.prototype._dropFiles = function(e){
e.stopPropagation(); e.preventDefault();
self._preview(e.dataTransfer.files);
self.all.push(e.dataTransfer.files);
}
multiUploader.prototype._uploader = function(file,f){
if(typeof file[f] != undefined && self._validate(file[f].type) > 0){
var data = new FormData();
var ids = file[f].name._unique();
data.append('file',file[f]);
data.append('index',ids);
$(".dfiles[rel='"+ids+"']").find(".progress").show();
$.ajax({
type:"POST",
url:this.config.uploadUrl,
data:data,
cache: false,
contentType: false,
processData: false,
success:function(rponse){
$("#"+ids).hide();
var obj = $(".dfiles").get();
$.each(obj,function(k,fle){
if($(fle).attr("rel") == rponse){
$(fle).slideUp("normal", function(){ $(this).remove(); });
}
});
if (f+1 < file.length) {
self._uploader(file,f+1);
}
}
});
} else
console.log("Invalid file format - "+file[f].name);
}
multiUploader.prototype._startUpload = function(){
if(this.all.length > 0){
for(var k=0; k<this.all.length; k++){
var file = this.all[k];
this._uploader(file,0);
}
}
}
String.prototype._unique = function(){
return this.replace(/[a-zA-Z]/g, function(c){
return String.fromCharCode((c <= "Z" ? 90 : 122) >= (c = c.charCodeAt(0) + 13) ? c : c - 26);
});
}
this._init();
}
function initMultiUploader(){
new multiUploader(config);
}
Try to modify multiUploader.prototype._uploader = function(file,f)
and add a line after data.append('index',ids); with something like:
data.append('item_id','12345'); <-- you can extract the item_id by a url param, div id....
Then in your upload.php you will catch the item_id POST data

Javascript trim whitespace on click

I have an email form field. On click, it executes this javascript ...
$(document).on('click', '#add_delegate', function() {
RegistrationHelper.added_delegate = true;
// var button = $(event.target);
var button = $(this);
var uri = button.data('url');
if (typeof uri === 'undefined') {
return false;
}
var input = $('#email_search');
var data = {email:input.val()};
data.text().replace(/ /g,'');
var spinner = $('#delegate_add_spinner');
spinner.css({display:'inline-block'});
$.ajax({type:'POST', url: uri, data:data}).success(function(card) {
var html = $(card);
var data_id = html.attr('data-id');
var existing_elem = $('.mini_addresscard[data-id=' + data_id + ']');
if (existing_elem.length < 1) {
input.popover('hide');
// this is in a seperate timeout because IE8 is so damn stupid; it crashes if run directly
setTimeout(function () {
$('#address_cards').append(html);
var last_card = $('#address_cards div.mini_addresscard').last();
//last_card.get(0).innerHTML = card;
// html.attr("id", 'sdklfjaklsdjf');
last_card.css({display:'none'}).show('blind');
}, 10);
} else {
var background = existing_elem.css('background');
existing_elem.css({'background':'#FFFFAC'});
existing_elem.animate({
'background-color':'#EBEDF1'
}, {
complete: function() {
existing_elem.css({background:background});
}
});
// var border_color = existing_elem.css('border-color');
// existing_elem.css({'border-color':'#EFF038'});
// existing_elem.animate({'border-color':border_color});
}
}).complete(function(data) {
spinner.hide();
}).error(function(data) {
var input = $('#email_search');
input.popover("destroy");
var error = 'Please try again later'; //incase something crazy happens
if(data.status == "422"){
error = 'You cannot add yourself as a supervisor.';
}
if(data.status == "404" ){
error = 'Could not find anyone with that email address.';
}
add_popover(input, error);
input.popover('show');
});
return false;
});
My goal is to trim the whitespace before the AJAX request
So as you can see in the code above I added the line
data.text().replace(/ /g,'');
... but now it renders that button useless. In other words the button does nothing when clicked.
Since you're using jQuery, why not make use of .trim():
This:
var data = {email:input.val()};
data.text().replace(/ /g,'');
Becomes:
var data = {email:$.trim(input.val())};
The trim supposed to remove the spaces at beginning and end of the input:
var input = $('#email_search').val();
input = input.replace(/^\s+/, '').replace(/\s+$/, '');

jQuery consolidate code into one function

Is it possible to consolidate the two sections of code below. If you look at each section you will notice they are almost identical. I have another 3 or 4 sections of code which are also identical. I'm wondering if there's a neater way for me to use the same code?
$("#agencies").on("click", ".applyClick", function(event) {
event.stopPropagation();
event.preventDefault();
var target = $(this);
var currentParent = $(this).closest('tr');
var id = currentParent.attr('id');
var items = $("input,select,textarea", currentParent);
var strData = items.serialize() + '&id=' + id;
$.post("agencies.php", strData, function(data) {
var data = $.parseJSON(data);
if(data.redirect_location){
window.location = data.redirect_location;
}
else{
var type = data.type;
var result = $.map(data, function(val,index) {
if(index != 'type'){
var str = val;
}
return str;
}).join("<br>");
if(type == 'error'){
alert(result);
}
else{
$("div#messages").html('<div class="'+ type +'-message">' + result + '</div>').slideDown("slow");
closeRow('quit', target);
}
}
});
});
$("#builders").on("click", ".applyClick", function(event) {
event.stopPropagation();
event.preventDefault();
var target = $(this);
var currentParent = $(this).closest('tr');
var id = currentParent.attr('id');
var items = $("input,select,textarea", currentParent);
var strData = items.serialize() + '&id=' + id;
$.post("builders.php", strData, function(data) {
var data = $.parseJSON(data);
if(data.redirect_location){
window.location = data.redirect_location;
}
else{
var type = data.type;
var result = $.map(data, function(val,index) {
if(index != 'type'){
var str = val;
}
return str;
}).join("<br>");
if(type == 'error'){
alert(result);
}
else{
$("div#messages").html('<div class="'+ type +'-message">' + result + '</div>').slideDown("slow");
closeRow('quit', target);
}
}
});
});
I will recomend to add attribute to your buttons like this
<input type="button" data-url="agencies" id="agencies" />
<input type="button" data-url="builders.php" id="builders" />
and same code like this
$("#agencies, #builders").on("click", ".applyClick", function(event) {
var url = $(this).attr('data-url');
....
$.post(url, strData, function(data) {
...
...
});
This question is in the margins of Code Review and SO.
The only difference between the two handlers appears to be the .post URL, and that appears to be derivable from the ID of the click target.
So do a little string handling to build the URL and attach your modified function as click handler to both elements :
$("#agencies, #builders").on("click", ".applyClick", function(event) {
...
$.post(this.id + '.php', strData, function(data) {
...
}

Categories

Resources