AJAX Calling Issue - php

I downloaded the script from here
http://www.webresourcesdepot.com/fly-to-basket-effect-with-jquery/
its good but some bugs like
Double Click => 3 Items add to basket
Tripple Click => 7 Items add to basket
i was trying to fix it but still cant get something .. then i see this link Disable Link while animated Basket
but i can understand where i place this code.. anybody help me to fix it please ...
$(document).ready(function(){
$("#basketItemsWrap li:first").hide();
$(".productPriceWrapRight a img").click(function() {
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
var productX = $("#productImageWrapID_" + productIDVal).offset().left;
var productY = $("#productImageWrapID_" + productIDVal).offset().top;
if( $("#productID_" + productIDVal).length > 0){
var basketX = $("#productID_" + productIDVal).offset().left;
var basketY = $("#productID_" + productIDVal).offset().top;
} else {
var basketX = $("#basketTitleWrap").offset().left;
var basketY = $("#basketTitleWrap").offset().top;
}
var gotoX = basketX - productX;
var gotoY = basketY - productY;
var newImageWidth = $("#productImageWrapID_" + productIDVal).width() / 3;
var newImageHeight = $("#productImageWrapID_" + productIDVal).height() / 3;
$("#productImageWrapID_" + productIDVal + " img")
.clone()
.prependTo("#productImageWrapID_" + productIDVal)
.css({'position' : 'absolute'})
.animate({opacity: 0.4}, 100 )
.animate({opacity: 0.1, marginLeft: gotoX, marginTop: gotoY, width: newImageWidth, height: newImageHeight}, 1200, function() {
$(this).remove();
$("#notificationsLoader").html('<img src="images/loader.gif">');
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "addToBasket"},
success: function(theResponse) {
if( $("#productID_" + productIDVal).length > 0){
$("#productID_" + productIDVal).animate({ opacity: 0 }, 500);
$("#productID_" + productIDVal).before(theResponse).remove();
$("#productID_" + productIDVal).animate({ opacity: 0 }, 500);
$("#productID_" + productIDVal).animate({ opacity: 1 }, 500);
$("#notificationsLoader").empty();
} else {
$("#basketItemsWrap li:first").before(theResponse);
$("#basketItemsWrap li:first").hide();
$("#basketItemsWrap li:first").show("slow");
$("#notificationsLoader").empty();
}
}
});
});
});
$("#basketItemsWrap li img").live("click", function(event) {
var productIDValSplitter = (this.id).split("_");
var productIDVal = productIDValSplitter[1];
$("#notificationsLoader").html('<img src="images/loader.gif">');
$.ajax({
type: "POST",
url: "inc/functions.php",
data: { productID: productIDVal, action: "deleteFromBasket"},
success: function(theResponse) {
$("#productID_" + productIDVal).hide("slow", function() {$(this).remove();});
$("#notificationsLoader").empty();
}
});
});
});

I think what you might have to-do is at the end of the click event function then unbind the event http://api.jquery.com/unbind/ $(this).unbind();
You could possibly bind it again once the ajax has finished

Related

How to send a big amount of data with ajax and jquery?

I would like to send a big amount of data by using Ajax, php and Jquery and see the result each time has been added to the database in a div. I tried this approach but the requests slow down after ten thousand requests. I never did that before. please can you help me optmize the code ? i tried also to upload a csv file but when it's a big file it take too much time to be upload.
$(document).ready(function () {
$('#clear').click(function () {
$('#title').val('');
$('#date').val('');
$('#csvfile').val('');
$('#result').empty();
$(".loader").css('display','none');
});
$('#csv').on('submit',function (e) {
e.preventDefault();
$('.loader').css('display','inline-block');
var title = $('#title').val();
var date = $('#date').val();
if(title.length == 0 ){
$('#title').css("border","2px solid red");
}else{
$('#title').css("border","2px solid #bdc3c7");
}
if(date.length == 0 ){
$('#date').css("border","2px solid red");
}else{
$('#date').css("border","2px solid #bdc3c7");
}
if($('#csvfile').val() == 0){
$('#csvfile').css("border","2px solid red");
}else{
$('#csvfile').css("border","2px solid #bdc3c7");
var file = document.getElementById('csvfile').files[0];
}
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function(event){
var csv = event.target.result;
var rows = csv.split('\n');
let data = [];
const csvCleanUp = /("|\s"|\s)*/g;
var headers = rows[0].split(';');
for(var i=1;i<rows.length;i++){
var obj = {};
var currentline=rows[i].split(";");
for(var j=0;j<headers.length;j++){
const header = String(headers[j]).replace(csvCleanUp,'');
const currentValue = String(currentline[j]).replace(csvCleanUp,'')
obj[header] = currentValue;
}
data.push(obj);
}
console.log(data);
let nb = 1;
let d = 0;
var myInter = setInterval(function () {
if(d < data.length){
data[d]['title'] = title;
data[d]['date'] = date;
console.log(data[d]);
$.ajax({
url: "/admin/add/action/",
type: "POST",
data: data[d],
cache: false,
dataType: "json",
success: function (resp) {
//console.log(resp.msg);
if(typeof resp.msg != 'undefined'){
$('#result').append('<span class="' + resp.color + '"> n° ' + nb + '<br>' + resp.msg + '</span>');
}
$('#result').animate({ scrollTop: $('#result')[0].scrollHeight }, 50);
nb++;
}
});
$('#clear').click(function () {
$('#title').val('');
$('#date').val('');
$('#csvfile').val('');
$('#result').empty();
$(".loader").css('display','none');
clearInterval(myInter);
});
}
if(d > data.length){
$(".loader").css('display','none');
$('#result').append('<span class="success">Fin d\'execution du script</span>');
clearInterval(myInter);
}
d++;
},100)
}
});
});
this is the other aproach i have used:
$(document).ready(function () {
$('#clear').click(function () {
$('#title').val('');
$('#date').val('');
$('#csvfile').val('');
$('#result').empty();
$(".loader").css('display','none');
});
$('#csv').on('submit',function (e) {
e.preventDefault();
$('.loader').css('display','inline-block');
var title = $('#title').val();
var date = $('#date').val();
if(title.length == 0 ){
$('#title').css("border","2px solid red");
}else{
$('#title').css("border","2px solid #bdc3c7");
}
if(date.length == 0 ){
$('#date').css("border","2px solid red");
}else{
$('#date').css("border","2px solid #bdc3c7");
}
if($('#csvfile').val() == 0){
$('#csvfile').css("border","2px solid red");
}else{
$('#csvfile').css("border","2px solid #bdc3c7");
var file = document.getElementById('csvfile').files[0];
}
var data = new FormData(this);
$.ajax({
url: "/admin/add/v2/action/",
type: "POST",
data: data,
contentType: false,
cache: false,
processData:false,
success: function (resp) {
}
});
});

Multiple wfs from database; changes the url

I need to show multiple wfs features into map. The requested url is http://localhost/pdan/map.php?id=150 This is what I have done:
var id = <?php echo $_REQUEST['id']; ?>;
function getVector(obj) {
var url = "";
var geojsonFormat = new ol.format.GeoJSON();
var vectorSource = new ol.source.Vector({
loader: function(extent, resolution, projection) {
var url = 'http:192.168.0.101:8082/geoserver/pdan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pdan:' + obj.data_set_name + '&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
$.ajax({url: url, dataType: 'jsonp', jsonp: false, cache:false});
},
strategy: ol.loadingstrategy.bbox
});
window.loadFeatures = function(response) {
vectorSource.addFeatures(geojsonFormat.readFeatures(response));
};
return new ol.layer.Vector({
source: vectorSource,
style: new ol.style.Style({
stroke: new ol.style.Stroke({
color: 'rgba(0, 0, 255, 1.0)',
width: 2
})
})
});
}
function getObject(id) {
var result;
$.ajax({
url: "dbQueries.php",
async: false,
cache: false,
dataType: "JSON",
data: {'query': 110, 'id': id},
success: function (data) {
result = data;
}
});
return result;
}
var vector = [];
var rowObject = getObject(id);
var size = Object.size(rowObject);
//Prepare vector Layer
if (size != 0) {
for (var i = 0; i < size; i++) {
vector[i] = getVector(rowObject[i]);
}
}
//Now Initialise map
var map = createMap();
var graticule = getGraticule();
graticule.setMap(map);
//Add vector to the map
if (size != 0) {
for (var i=0; i<size; i++) {
map.addLayer(vector[i]);
}
}
Everything seems okey to me but the url is changed and in the console I get error as:
GET
http://localhost/pdan/192.168.0.101:8082/geoserver/pdan/ows [HTTP/1.1 403 Forbidden 3ms]
What am I missing here?
The problem was with the url I requested. It should be
var url = 'http://192.168.0.101:8082/geoserver/pdan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pdan:' + obj.data_set_name + '&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';
instead of
var url = 'http:192.168.0.101:8082/geoserver/pdan/ows?service=WFS&version=1.0.0&request=GetFeature&typeName=pdan:' + obj.data_set_name + '&' +
'outputFormat=text/javascript&format_options=callback:loadFeatures' +
'&srsname=EPSG:3857&bbox=' + extent.join(',') + ',EPSG:3857';

My chat website(php+ajax) makes my browser stuck

This is the script I use for various purposes like scrolling, getting the data from php etc:
<script>
$(document).ready(function(){
$("#full_chat").animate({ scrollTop: $('#full_chat')[0].scrollHeight+1000}, 1500);
setInterval(function refreshPage() {
var user=$("#head").text();
$.post("retrieve.php",{ user:user }, function(data,status){
if($.trim(data)!="0"){
$("#full_chat").append("<span class='you'>"+data+"</span>");
$('#full_chat').emoticonize();
window.onblur = function () {
$('#full_chat').bind("DOMSubtreeModified",function(){
$.titleAlert("New Message!", {
requireBlur:true,
stopOnFocus:true,
//duration:10000,
//interval:500
});
});
}
}
}); }, 1500);
$("#form").on('submit',function (e) {
e.preventDefault();
var user=$("#head").text();
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
var txt= $("#chat_input").val();
$.post("chat.php",{ txt:txt,user:user,time:time },function(data,status){
if(data=="OFFLINE"){
$("#full_chat").append("User not available right now<br>");
}else{
$("#full_chat").append("("+time+") ").append("<span class='me'>"+"Me: "+txt+"</span><br>").emoticonize({delay: 1,animate:false});
}
});
$("#full_chat").animate({ scrollTop: $('#full_chat')[0].scrollHeight+1000}, 1500);
$('#chat_input').val('');
});
});
</script>
This is the PHP code I use to get the chats from database:
<?php
session_start();
$other_user=$_POST['user'];
$flag=$_POST['flag'];
include_once('db.php');
$uname=$_SESSION['username'];
//date_default_timezone_set('Asia/Kolkata');
$q="select message,sender,time from chat where username='$uname' and delivered=0 and sender='$other_user' order by time ASC";
$qe = mysqli_query($con,$q);
$q1="UPDATE chat SET delivered=1 WHERE username='$uname' and sender='$other_user'" ;
$qe1 = mysqli_query($con,$q1);
if($r=mysqli_fetch_array($qe)) {
echo "(".$r['2'].") ". $r['1'].": ".$r['0']."<br>";
}else {
echo "0";
}
mysqli_close($con);
?>
What may be the reason for the problem? Is it the page refresh that happens every 1.5 seconds or something else?
This is just to give you an idea, it is not tested.
<script>
$(document).ready(function() {
var user = $("#head").text();
var postTimeout = 0;
var refreshPage = function(postInterval, postData) {
$.post("retrieve.php", postData, function(data, status) {
if (!postTimeout) {
postTimeout = setTimeout(function() {
refreshPage(postInterval, postData);
postTimeout = 0;
}, postInterval);
}
if ($.trim(data) != "0") {
$("#full_chat").append("<span class='you'>" + data + "</span>");
$('#full_chat').emoticonize();
window.onblur = function() {
$('#full_chat').bind("DOMSubtreeModified", function() {
$.titleAlert("New Message!", {
requireBlur: true,
stopOnFocus: true,
//duration:10000,
//interval:500
});
});
}
}
});
}
$("#full_chat").animate({
scrollTop: $('#full_chat')[0].scrollHeight + 1000
}, 1500);
refreshPage(1500, {user: user});
$("#form").on('submit', function(e) {
e.preventDefault();
var user = $("#head").text();
var dt = new Date();
var time = dt.getHours() + ":" + dt.getMinutes() + ":" + dt.getSeconds();
var txt = $("#chat_input").val();
$.post("chat.php", {
txt: txt,
user: user,
time: time
}, function(data, status) {
if (data == "OFFLINE") {
$("#full_chat").append("User not available right now<br>");
} else {
$("#full_chat").append("(" + time + ") ").append("<span class='me'>" + "Me: " + txt + "</span><br>").emoticonize({
delay: 1,
animate: false
});
}
});
$("#full_chat").animate({
scrollTop: $('#full_chat')[0].scrollHeight + 1000
}, 1500);
$('#chat_input').val('');
});
});
</script>

What would i use as a get request in jquery/ajax to set parameters

i am new to Jquery/Ajax and i am trying to have the source url for the json change based on the url parameters i setup, i have working version in PHP, but i don't know how to write it in JQuery
This is my PHP Code (what i am currently using
$id = urlencode($_GET['id']);
$page = urlencode($_GET['results']);
$url = "https://gdata.youtube.com/feeds/api/playlists/$id?alt=jsonc&v=2&max-results=25&&start-index={$results}";
This code grabs the id and includes it to alter the url of the source file used in the script
so how would i make this code act in the same way?
$(document).ready(function() {
startindex = 1;
loadmore = 20;
addMore(startindex, loadmore);
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore($('#list li').length, 20);
});
});
function addMore(startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/ID_WOULD_GO_HERE?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
Please help, Thanks!
Please try this:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="list"></div>
<script>
$(document).ready(function() {
startindex = 1;
loadmore = 20;
id = urlVar("id");
if (id!="") {
addMore(id, startindex, loadmore);
}
$('#addmore').on('click',function(e) {
e.preventDefault();
addMore(id, $('#list li').size(), 20);
});
});
function urlVar(varName) {
var vars = {};
var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
vars[key] = value;
});
return vars[varName]?vars[varName]:"";
}
function addMore(id, startindex,loadmore) {
src = "https://gdata.youtube.com/feeds/api/playlists/"+ id +"?alt=json&max-results=" + loadmore + "&start-index=" + startindex;
$.ajax({
dataType: "jsonp",
url: src,
success: function(data, textStatus, jqXHR) {
console.log(data);
if (data.feed && data.feed.entry) {
var $list = $('#list');
$.each(data.feed.entry, function(i, e) {
$list.append('<li class="video"><img src="'+ e.media$group.media$thumbnail[0].url +'" width="250"></img><br>' + e.title.$t + '<P>' + e.author[0].name.$t + ' | '+ e.yt$statistics.viewCount +' Views</span></li>');
});
}
}
});
}
</script>
To test: this_script.php?id=RD029cW4vF6U2Dc
Potentially you could also get PHP to put the variable into the URL before hand.
Example:
src = "https://gdata.youtube.com/feeds/api/playlists/<?php echo $_GET['id'];?>?alt=json&max-results=" + loadmore + "&start-index=" + startindex;

jQuery FullCalendar isn't clearing the event

I am currently working away with FullCalendar, which is pretty cool and has done a lot of neat stuff for me. The only problem I'm having is that if I edit an event, and then try and create another event the javascript seems to hold onto the initial events data.
I am using calendar.fullCalendar('unselect') when I need the link to end, but it doesn't seem to make a difference no matter what I do. I'm hoping you guys might be able to see something I'm overlooking.
<script type='text/javascript'>
$(document).ready(function() {
var date = new Date();
var d = date.getDate();
var m = date.getMonth();
var y = date.getFullYear();
var calendar = $('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultView: 'agendaWeek',
selectable: true,
unselectAuto: true,
selectHelper: true,
editable: true,
select: function(start, end, allDay) {
//var title = prompt('Event Title:');
//var desc = prompt('Event Description:');
//calendar.fullCalendar('unselect');
$('#eventStart').val(start);
$('#eventEnd').val(end);
$('#eventAllDay').val(allDay);
$('#formName').fadeIn();
$('.closeSchedule a').click(function(){
$('#formName').fadeOut('slow');
$('#calendar').fullCalendar('unselect');
//alert(jsEvent);
});
},
events: [
<?php
$first = true;
foreach ($events as $event)
{
if ($first == true)
{
$comma = '';
$first = false;
}
else
{
$comma = ',';
}
echo $comma."
{
id: '".$event->id."',
title: '".addSlashes($event->title)."',
start: '".$event->start."',
end: '".$event->end."',
allDay: ".$event->allDay."
}";
$first = false;
}
?>
],
eventClick: function(event) {
//alert(event.id);
$.ajax({
url: './schedule/getEdit/'+event.id,
success: function(data) {
var formEmpty = $('formName').html();
$('#formName').html(data);
$('#formName').fadeIn('fast');
$('.closeSchedule a').click(function(){
$('#formName').fadeOut('slow');
$('#calendar').fullCalendar('unselect');
});
$('#deleteEvent').live('click', function(){
var answer = confirm("Are you sure you wish to delete this event?")
if (answer){
$.ajax({
type: "POST",
url: "./schedule/deleteEvent/"+event.id,
success: function(msg){
$('#formName').fadeOut('fast');
calendar.fullCalendar( 'removeEvents', [event.id ] )
$('#calendar').fullCalendar('unselect');
}
});
}
});
$('#updateEvent').live('click', function(){
var title = $('#eventName').val();
var trainerID = $('#eventTrainer').val();
var trainer = $('#eventTrainer option:selected').text();
var classID = $('#eventType').val();
var eventType = $('#eventType option:selected').text();
var eventStart = $('#eventStart').val();
var eventEnd = $('#eventEnd').val();
var eventAllDay = $('#eventAllDay').val();
if (eventAllDay == 'false')
{
allDay = false;
}
else
{
allDay = true;
}
// This runs the ajax to add the event to the database.
newData = 'title='+title+'&trainerID='+trainerID+'&classID='+classID+'&start='+eventStart+'&end='+eventEnd+'&allDay='+allDay
$.ajax({
type: "POST",
url: "./schedule/updateEvent/"+event.id,
data: newData,
success: function(msg){
event.title = title;
calendar.fullCalendar('rerenderEvents');
//calendar.fullCalendar('unselect');
$('#calendar').fullCalendar('unselect');
}
});
$('#formName').fadeOut('fast');
$('#eventName').val('');
$('#eventTrainer').val();
$('#eventType').val();
});
}
});
},
eventDrop: function(event,dayDelta,minuteDelta,allDay,revertFunc) {
newData = 'start='+event.start+'&end='+event.end+'&allDay='+allDay
$.ajax({
type: "POST",
url: "./schedule/updateEventTime/"+event.id,
data: newData,
success: function(msg){
}
});
},
eventResize: function(event,dayDelta,minuteDelta,revertFunc) {
newData = 'start='+event.start+'&end='+event.end+'&allDay='+event.allDay
$.ajax({
type: "POST",
url: "./schedule/updateEventTime/"+event.id,
data: newData,
success: function(msg){
}
});
}
});
$('#submitEvent').click(function(){
$('#calendar').fullCalendar('unselect');
var title = $('#eventName').val();
var trainerID = $('#eventTrainer').val();
var trainer = $('#eventTrainer option:selected').text();
var classID = $('#eventType').val();
var eventType = $('#eventType option:selected').text();
var eventStart = $('#eventStart').val();
var eventEnd = $('#eventEnd').val();
var eventAllDay = $('#eventAllDay').val();
if (eventAllDay == 'false')
{
allDay = false;
}
else
{
allDay = true;
}
// This runs the ajax to add the event to the database.
newData = 'title='+title+'&trainerID='+trainerID+'&classID='+classID+'&start='+eventStart+'&end='+eventEnd+'&allDay='+allDay
$.ajax({
type: "POST",
url: "./schedule/addEvent",
data: newData,
success: function(msg){
var description = '<ol><li>'+title+'</li><li>'+trainer+'</li><li>'+eventType+'</li><li class="eventID hide">'+msg+'</li>';
calendar.fullCalendar('renderEvent',
{
id: msg,
title: title,
description: description,
start: eventStart,
end: eventEnd,
allDay: allDay
},
true // make the event "stick"
);
calendar.fullCalendar('unselect');
//calendar.fullCalendar( 'rerenderEvents' )
}
});
$('#formName').fadeOut('fast');
$('#eventName').val('');
$('#eventTrainer option:selected').removeAttr('selected');
$('#eventType option:selected').removeAttr('selected');
});
});
</script>
At this point, I feel like I've tried it all, and I'm just hoping a fresh set of eyes will see what I missed.
Ok took a quick look it looks like you aren't initializing the form with a blank form for the add action in the "select:" function of your full calendar:
In your event click you are doing this:
$('#formName').html(data);
I don't see where you are clearing that with a blank form for a new event. (might have just missed it there is a lot of code there)
Let me know.

Categories