To keep it simple, I'm just wanting to know how I'd go about and if else statement against my ajax to print new data out once if it finds it and not the same data over and over again. Amd how can I possibly store the last id as a variable to reuse it when searching for more new records?
Someone mentioned to me also I could save the new notification idea as a return so when the ajax restarts it uses this to find the next new set of results.
Has anybody got any ideas how to achieve these?
<script type="text/javascript">
setInterval(function(){
var time = new Date().getTime();
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
}
});
},20000);
</script>
Regarding to store the last id, you could use:
window.localStorage.setItem('key', 'value');
Then when you want to get it again you'll should use:
var lastId = window.localStorage.getItem ('key');
And regarding the duplicates issue, well, you should have a internal storage in order to handle the recieved data. May be an array can help as storage, also you can also store this array in local storage.
Once you handle this data storage, you could apply something like this to verify that your data has no duplicates:
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
UPDATE
var notification_id = window.localStorage.getItem ('lastId');
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id+"&time="+time ,
dataType:"json",
cache: false,
success: function(response){
if(response){
dataHandler(response);
if(response.num){
window.localStorage.setItem('lastId', response.num);
}
});
},20000);
Related
This is my first exposure with using Mootools; I have not used Jquery much, and I am having troubles implementing a new change to the scripting.
We used a flash uploader, FancyUpload2 and I have been tasked with replacing it with a non-flash version. I am attempting to use the existing coding for the rest of the project, but I have not been able to get this to work now.
<script type="text/javascript">
$('#demo-browse').change(function(){
//on change event
formdata = new FormData();
if($(this).prop('files').length > 0)
{
file =$(this).prop('files')[0];
formdata.append("Filedata", file);
}
jQuery.ajax({
url: '../control/image_upload/gallery_script.php',
type: "POST",
data: formdata,
processData: false,
contentType: false,
success: function(response) {
var json = new Hash(JSON.decode(response, true) || {});
// alert(response);
iDependOnMyParameter(response);
}
});
function iDependOnMyParameter(param) {
// You should do your work here that depends on the result of the request!
var json = new Hash(JSON.decode(param, true) || {});
var req = new Request({
url: '../control/image_upload/gallery_script_ajax.php',
onSuccess: function(response){
var feedback = response.split('|');
var thumb = feedback[0];
var new_id = feedback[1];
var li = new Element('li', {id: 'item_'+new_id, 'class':'sort_me', 'alt':new_id});//create new list item
alert(new_id);
///// CODING WORKS UP TO HERE
sb.addItems(li);//add to sortables
var first_item = $('content_list_images').firstChild; // get current first li
$('content_list_images').insertBefore(li, first_item);// insert into list
li.set('tween',{duration: 2000});
li.tween('opacity', 0, 1);
},
onFailure: function(){
}
});
var data = 'file='+json.get('filename')+'&extension='+json.get('extension')+'&date='+json.get('date')+'&width='+json.get('width')+'&height='+json.get('height')+'&mime='+json.get('mime')+'&page_id=<?=$id?>&new=<?=$unix?>';
req.send(data);
////////////////////////////////////////////////
}
});
</script>
I have been able to hack some things together to have it work how I need, but then I get to a certain point and I am not sure how to continue. All the posts get the responses that I need, but then I am at a loss. I would greatly appreciate some assistance as to how I am able to make this work.
Everything up to alert(new_id); works.
I am fully aware that I need to review more with Jquery and Mootools, and I will do so. I am on a tight deadline and I do appreciate any and all help!
The previous tools that they used to upload files was using FancyUpload.
I have a JS script doing multiple AJAX requests. First I'm requesting a product by ID and then I'm requesting every single variant of this product. I can't do any form of backend coding since the environment I'm working in is closed.
My requests works fine, but right now I'm appending every single variant to a div, and my client don't really like this, so I was thinking is it possible to load all data into a variable and then fade in the parent div of all variants at the very end?
My script looks like this:
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
variants.find('.variant').fadeIn(300);
}
});
});
}
});
Some fast and dirty solution, but idea and concept of solution is clear. It is bad solution, but works for you in your case when you have no access to backend code.
var all_load_interval;
var is_all_data_ready = false;
var all_data_count = 0;
var variants = $('.single_product-variant-images');
$.ajax({
url: productMasterURL,
success: function (data) {
var data_count = $(data).find('Combinations Combination').length;
$(data).find('Combinations Combination').each(function () {
var variantID = $(this).attr('ProductNumber');
$.ajax({
url: "/api.asp?id=" + escape(variantID),
dataType: "json",
async: true,
cache: true,
success: function (data) {
// make div with class variant hidden
variants.append('<div class="variant"><img src="' + data.pictureLink + '" alt=""/></div>');
// count every variant
all_data_count += 1
if (all_data_count == data_count) {
// when all data got and created, lets trigger our interval - all_load_interval
is_all_data_ready = true;
}
}
});
});
}
all_load_interval = setInterval(function() {
// Check does all data load every second
if (is_all_data_ready) {
// show all div.variant
variants.find('.variant').fadeIn(300);
clearInterval(all_load_interval);
}
}, 1000);
});
I have an AJAX.
var id = "some_text";
$.ajax({
type : "GET",
dataType : "json",
url : "<?php echo site_url('con_atk/get_outlet'); ?>",
async : false,
success : function(outlet){
$.map(outlet, function (v) {
if(v.NamaOutlet == id){
window.location.href = "page_a.php";
}
else{
window.location.href = "page_b.php";
}
})
}
})
I'd like to check if the value of id is exist in the AJAX success call (JSON object type). If it exists, redirect to page A and if not redirect to page B. When I use alert on v.NamaOutlet the value is exist. But why am I not redirected to page_a.php?
edit
when I use alert(JSON.stringify(outlet));
[{"KodeOutlet_iBSM":"ACG","NamaOutlet":"Accounting"},{"KodeOutlet_iBSM":"BBG","NamaOutlet":"Business Banking"},{"KodeOutlet_iBSM":"CB I","NamaOutlet":"Corporate Banking I"},{"KodeOutlet_iBSM":"CB II","NamaOutlet":"Corporate Banking II"},{"KodeOutlet_iBSM":"CBT","NamaOutlet":"Corporate & Branch Transformation"},{"KodeOutlet_iBSM":"CCG","NamaOutlet":"Culture & Customer Care"},{"KodeOutlet_iBSM":"CHG","NamaOutlet":"Consumer Finance & Hajj"},{"KodeOutlet_iBSM":"CMG","NamaOutlet":"Commercial Banking"}
Setting window.location.href doesn't immediately terminate the current script - I'm not sure how reliable this is cross browser, but in my testing in Chrome if you set window.location.href more than once in the same script the browser navigates to the last value set before the JS function ends.
So in your case it would navigate to the result of testing the last item in your array, because your $.map() loop runs the if/else for every item in the array.
You could instead use your loop to set a flag to indicate whether the item was found anywhere in the array:
success : function(outlet){
var idFound = false;
$.each(outlet, function (v) {
if(v.NamaOutlet == id){
idFound = true;
}
});
window.location.href = idFound ? "page_a.php" : "page_b.php";
}
Note that I've used $.each(), because although $.map() would achieve the same result it doesn't really make sense because you're not really doing any mapping.
You can tidy this up and remove the need for a flag variable by using the array .some() method rather than $.each():
success : function(outlet){
if (outlet.some(function(v) { return v.NamaOutlet == id; })) {
window.location.href = "page_a.php";
else {
window.location.href = "page_b.php";
}
}
The only possible reason I could find here is that you might be using Internet Explorer and internet explorer does not really accept relative URLs as mentioned in one of the answers here
window.location.href not working on IE
Rest all seems good. Hope this helps.
if else condition is not suitable for your situation , let your id is Commercial Banking ,the last array value of your given json response .So mapping json will be check first index with id ,so if not equal it redirected to page_b .But you have id that exist in json response so that condition is not true for your condition . You wanna check id is exist in outlet so that map json array and if it found redirected page , if not found write the redirect other page in next execute line....
var id = "Commercial Banking"; // eg value
$.ajax({
type : "GET",
dataType : "json",
url : "<?php echo site_url('con_atk/get_outlet'); ?>",
async : false,
success : function(outlet){
$.map(outlet, function (v) {
if(v.NamaOutlet == id){
window.location.href = "page_a.php";
}
});
window.location.href = "page_b.php";
}
});
TRY IT:
var id = "Business Banking";
$.ajax({
type: "GET",
dataType: "json",
url: "<?php echo site_url('con_atk/get_outlet'); ?>",
async: false,
success: function (outlet) {
//[{"KodeOutlet_iBSM":"ACG","NamaOutlet":"Accounting"},{"KodeOutlet_iBSM":"BBG","NamaOutlet":"Business Banking"},{"KodeOutlet_iBSM":"CB I","NamaOutlet":"Corporate Banking I"},{"KodeOutlet_iBSM":"CB II","NamaOutlet":"Corporate Banking II"},{"KodeOutlet_iBSM":"CBT","NamaOutlet":"Corporate & Branch Transformation"},{"KodeOutlet_iBSM":"CCG","NamaOutlet":"Culture & Customer Care"},{"KodeOutlet_iBSM":"CHG","NamaOutlet":"Consumer Finance & Hajj"},{"KodeOutlet_iBSM":"CMG","NamaOutlet":"Commercial Banking"}]
var exist = false;
for (var i = 0; i < outlet.length; i++) {
if (outlet[i].NamaOutlet === id) {
exist = true;
break;
}
}
if (exist) {
window.location.href = "page_a.php";
} else {
window.location.href = "page_b.php";
}
}
});
$('#btn').click(function () {
$.ajax({
type: "GET",
url: '/Contrller/Action Name',
data: {},
contentType: "application/json;",
dataType: "json",
success: function (r) {
console.log(r);
if (r == true) {
$.ajax({
type: "GET",
url: '/Contrller/Action',
data: { },
contentType: "application/json;",
dataType: "json",
success: function (r) {
$("#btnclosem").trigger("click")
var select = $("#Div");
select.empty();
select.append($('<option/>', {value: 0,text: "" })); $.each(r.list, function (index, itemData) {
}
});
return false;
}
else {
alert("")
return false;
}
}
});
I have made a booking system that utilizes FullCalendar; though that part should be irrelevant. My problem is that upon saving an appointment, a 'notes' field I have created very occasionally has this strange string inserted into it, generally at a random point in the string. Here is the latest example:
Has this been changedjQuery1112010047650896012783_1444929292744 with Rich- finishing sleeve off.bringing deposit in on saturday. told him space isnt secure.
As you can see, there is a totally out of place "jQuery1112010047650896012783_1444929292744" placed in the middle of the note. I can't find anything about this online (mainly because I have no idea what terms I'd use to find it). It must be related to jQuery, considering the string.
I am using jQuery v1.11.2 - obviously the string looks like a long version number.
Why is my ajax request seemingly succeeding, but placing this message in the middle of the sent string? I cannot replicate this issue at all, especially this time since it was another user who managed to cause it.
The function that fetches/prepares/sends data looks like this:
function postForm(content, action, update) {
loader('show');
var popup = content.parent();
var children = content.find(".input");
var data = {}
var elements = [];
data['elements'];
$( children ).each(function() {
var child = {};
child['name'] = $(this).attr('data-name');
if ($(this).is(':checkbox')) {
child['value'] = $(this).is(":checked");
} else {
child['value'] = $(this).val();
}
elements.push(child);
});
data.elements = elements;
data.request = action;
dataPost = JSON.stringify(data);
console.log(dataPost);
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
return false;
}
The note section is just a textarea with the class 'input' (which is looped through and fetched).
I don't think there will be a solution for the exact problem, however, I'm looking for an explanation for the modification of the string. The application works perfectly, except for this very rare case.
Question marks (??) are replaced with a jQuery time stamp. To fix, I had to add jsonp: false to the parameters. Final ajax:
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
jsonp: false,
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
I have some FormData that are going to be sent into another PHP file using Ajax Post.
var formElement = document.getElementById("form-id");
var form_data = new FormData(formElement);
var csrf_arr = csrf.split("=");
form_data.append(csrf_arr[0],csrf_arr[1]);
$.ajax({
type: "POST",
url: "your-url",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function(data) {
alert(data.message);
},
complete: function(data) {
location.reload();
}
})
What I'm trying to do here is to append a new single data inside the form_data
From my assumption, I could make it just by doing this
form_data.append("key","value");
But it is not sent through the ajax post or even not appended to the form_data as part of the FormData.
Am I making any mistake here or even there is certain rule for that?
Please give any help.
Thanks in advance!
Dear all of my friend,
I'm sorry. Actually it is just a mistake from myself.
I have fix this myself and found the mistake right inside my code.
-- The javascript code --
$( '#submitYours' ).on('click', function(){
var formElement = document.getElementById("form-id");
// Value of formElement consist of pair of data like:
// qst_additional_name_for_the_key=value_of_the_key
var form_data = new FormData(formElement);
form_data.append('break','break');
// to prevent confusion, i'm putting the csrf variable value here
// but i'm not using this as printed variable later, just for security check
var csrf = "your_csrf_token_name=bb6ff34c26ff938822dd339c1682bbcc";
var csrf_arr = csrf.split("=");
var x = 0;
for(x = 0; x < elementId.length; x++){
form_data.append(elementId[x], elementVal[x]);
// Appended data above is just an additional data from some array of data
// and the format is the same with formElement
// qst_additional_name_for_the_key=value_of_the_key
}
form_data.append("master_id",master_id);
form_data.append(csrf_arr[0],csrf_arr[1]);
addLoader("overlay-loader");
runInAnimate("overlay-loader", "bounceInUp");
$.ajax({
type: "POST",
url: "url.php",
data: form_data,
processData: false,
contentType: false,
dataType: "json",
success: function(data) {
alert(data.message);
},
complete: function(data) {
runOutAnimate("overlay-loader", "overlay-loader", "bounceOutDown");
location.reload();
}
})
});
-- The url.php code --
$temp = '';
$arr_in = '';
foreach($_POST as $key => $value){
if(!#$value) continue;
if(substr($key, 0, 4) == 'qst_'){ // This is the real problem.
// The only data taken from the form_data
// are the data containing string "qst_" in it
if(is_array(#$value)){
foreach(#$value as $val){
$this->yourmodel->saveAnswer(substr($key, 4), strtolower(trim(#$val)));
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}else{
$this->yourmodel->saveAnswer(substr($key, 4), strtolower(trim(#$value)));
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}else if($key == 'break'){ // remember my additional data? The string "break"
// i just have to chek it here and put into my $arr_in variable,
// so that I can use it now, because the previous conditional allow
// only data containing string "qst_"
$temp = #$_POST[$key];
$arr_in .= #$temp;
}
}
print json_encode(array('status' => 'success', 'message' => #$arr_in));
The conclusion is, nothing wrong if we just append the form_data manually
form_data.append('your_key','your_value');
Everything just the matter of how you access the data after it sent to another file.
My Mistake, everyone!
I'm sorry and thanks a lot for your help. :)