So I am making a checkbox for each row in my table so I can delete multiple rows at once.
I am trying to do this for each row inside my table:
<td><input id="checkItem" name="delete[]" type="checkbox" value="<?=$product->id;?>"></td>
Then delete[] is holding the array.
My issue is, I am using json (ajax) to parse my data.
It is only recognizing the last delete[] checkbox I have on my page.
If I check the last checkbox and hit delete all (my button to execute multi-selected rows), it shows the product id, this is good.
If I try any other checkbox, it returns nothing.
Here is the checkbox line that creates checkbox array for each row:
enter image description here
Here is the post function:
enter image description here
Here is my delete function:
enter image description here
Here is my json ajax code to process the requests:
$("body").on("submit", ".ajax-form", function (e) {
e.preventDefault();
form = $(this);
url = form.attr("action");
method = form.attr("method");
data = {};
form.find("[name]").each(function (key, value) {
type = $(this).attr("type");
name = $(this).attr("name");
if (type == "radio" || type == "checkbox") {
value = "";
if ($(this).prop("checked")) value = $(this).val();
} else value = $(this).val();
data[name] = value;
});
button_lang = $("[type=submit]", form).html();
var saveData = $.ajax({
type: method,
crossDomain: true,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
url: url,
data: data,
dataType: "json",
success: function(response) {
messages = "";
if(response.success === true)
{
if(response.redirect)
{
$('.ajax-form').trigger("reset");
window.location.href = response.redirect;
}
else if(response.success)
{
for (var message in response.messages) {
messages += response.messages[message] + "<br>";
}
if(response.timer) {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'success',
title: "<h6 style='text-align: left!important;'>" + messages + "</h6>"
});
$('.ajax-form').trigger("reset");
window.setTimeout(function(){window.location.href = response.sendTo;},response.timer);
} else {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'success',
title: "<h6 style='text-align: left!important;'>" + messages + "</h6>"
});
$('.ajax-form').trigger("reset");
}
}
else
{
location.reload();
}
}
else
{
for (var message in response.messages) {
messages += response.messages[message] + "<br>";
}
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'error',
title: "<h6 style='text-align: left!important;'>" + messages + "</h6>"
});
}
}
});
saveData.fail(function() {
const Toast = Swal.mixin({
toast: true,
position: 'top-end',
showConfirmButton: false,
timer: 3000,
timerProgressBar: true,
onOpen: (toast) => {
toast.addEventListener('mouseenter', Swal.stopTimer)
toast.addEventListener('mouseleave', Swal.resumeTimer)
}
});
Toast.fire({
icon: 'error',
title: "<h6 style='text-align: left!important;'>A system error occured</h6>"
});
});
});
Try this. But #El_Vanja is right. Your code is highly room for improvement
form.find('input:checkbox').each(function (key, value) {
type = $(this).attr("type");
name = $(this).attr("name");
if (type == "radio" || type == "checkbox") {
value = "";
if ($(this).prop("checked")) value = $(this).val();
} else value = $(this).val();
data.push({name:value});
});
Related
When I start to dragging an event, always scrolls to top of the day (timeGridDay). If I drag and drop when I see, p.e. from 00:00 to 08:00 is ok, but I if I try to drag an event that's at 17:00 then automitically moves to 00:00 -- 08:00 area on the top..
I have another calendar that's working fine... I've compared and it's all the same I think..
Thanks for your help.
var doubleClick = false;
var calendarEl = document.getElementById('calendar');
var calendar = new FullCalendar.Calendar(calendarEl, {
schedulerLicenseKey: 'GPL-My-Project-Is-Open-Source',
height: '700',
plugins: [ 'timeGrid','dayGrid' ,'resourceTimeGrid','interaction'],
titleFormat: {
year: 'numeric',
month: 'numeric',
day: 'numeric'
},
defaultView: 'timeGridDay',
locale: lan,
minTime: '00:00:00',
maxTime: '23:59:00',
allDaySlot: false,
editable: true,
selectable: true,
select: function(info)
{
$('#newEventForm').trigger('reset');
cadenaStr = info.startStr;
cadenaEnd = info.endStr;
datavisita = cadenaStr.substr(0,10);
horainici = cadenaStr.substr(11,8);
horafi = cadenaEnd.substr(11,8);
$('#horastart').val(horainici);
$('#horaend').val(horafi);
$('#data').val(datavisita);
$('#newEventModal').modal('show');
},
droppable: true,
dragScroll: true,
eventResourceEditable: true,
header: {
left: 'prev,next, addEventButton, addReserveButton',
center: 'title',
// right: 'resourceTimeGrid,dayGridMonth,timeGridWeek,timeGridDay'
right: ''
},
views: {
resourceTimeGrid: { buttonText: resbtnname },
//dayGridMonth: { buttonText: 'month' },
//dayGridWeek: { buttonText: 'week' },
//dayGridDay: { buttonText: 'day' }
},
timeZone: 'local',
customButtons: {
addEventButton: {
text: '+',
click: function() {
$('#newEventForm').trigger("reset");
//alert ("passo abans client");
//$('#client').val('').trigger('change');
//$('#pacient').val("");
$('#newEventModal').modal('show');
}
},
addReserveButton: {
text: '||',
click: function() {
$('#newReserveModal').modal('show');
$('#newReserveForm').trigger('reset');
}
}
},
// title: info.event.extendedProps.pacientnom+': '+info.event.extendedProps.description,
// tootlip show up on event mouse hover
dayClick: function(date, jsEvent, view) {
if(!doubleClick) {
doubleClick = true;
setTimeout(function() { doubleClick = false; }, 500); //this waits for a second click for the next 500ms
}
else {
alert ("doble cliiiiikkkk");
//do your double click action here (date and time available in date variable)
}
},
eventRender: function(info) {
var tooltip = new Tooltip(info.el, {
title: info.event.extendedProps.description,
placement: 'top',
trigger: 'hover',
container: 'body'
});
$(info.el).on("mousedown", function(){
tooltip.hide();
});
$(info.el).on("mouseup", function(){
tooltip.hide();
});
$(info.el).on("click", function(){
tooltip.hide();
});
},
// edit form modal show up on event click
eventClick: function(info) {
$('#editsala').empty();
$('#editpacient').empty();
var idvisita = info.event.id;
$('#idvisitaorg').val(idvisita);
$('#visitaForm').submit();
},
// drag and drop event with database records change
eventDrop: function( info ) {
$('.tooltip').hide();
//if (!confirm("Are you sure about this change?")) {
//
// info.revert();
//} else {
var id = info.event.id;
var title = info.event.title;
var timeSettings = { "hour": "2-digit", "minute": "2-digit", "hour12": false };
var starttime = calendar.formatDate(info.event.start, timeSettings);
var endtime = calendar.formatDate(info.event.end, timeSettings);
var startdate =moment(info.event.start).format('YYYY-MM-DD');
if(info.newResource) {
var resourceId = info.newResource.id;
} else {
if(info.oldEvent.extendedProps.Resource_Id){
var resourceId = info.oldEvent.extendedProps.Resource_Id;
} else {
var resourceId =0;
}
}
$.ajax({
url: "calvis_event_dropped_update.php",
type: "POST",
data: ({
id: id,
title: title,
starttime: starttime,
endtime: endtime,
startdate: startdate,
resourceId: resourceId
}),
success: function(data){
calendar.refetchEvents()
},
error: function() {
info.revert();
}
});
//}
},
// resize event with database records change
eventResize: function( info ) {
$('.tooltip').hide();
//if (!confirm("Are you sure about this change?")) {
// info.revert();
//} else {
var id = info.event.id;
var title = info.event.title;
var timeSettings = { "hour": "2-digit", "minute": "2-digit", "hour12": false };
var starttime = calendar.formatDate(info.event.start, timeSettings);
var startdate = moment(info.event.start).format('YYYY-MM-DD');
var endtime = calendar.formatDate(info.event.end, timeSettings);
var resourceId=info.event.extendedProps.Resource_Id;
//console.log(starttime);
//console.log(endtime);
// console.log(info.event.extendedProps.Resource_Id);
$.ajax({
url: "calvis_event_dropped_update.php",
type: "POST",
data: ({
id: id,
title: title,
starttime: starttime,
endtime: endtime,
startdate: startdate,
resourceId: resourceId
}),
success: function(data){
calendar.refetchEvents()
},
error: function() {
info.revert();
}
});
//}
},
//hide select resource for other views
viewSkeletonRender: function(info){
if(info.view.type=="resourceTimeGrid"){
$("#resource_select_div").show();
$("#filter_events_div").hide();
$('#usuario_filter').val('none');
calendar.refetchEvents();
} else{
$("#resource_select_div").hide();
$("#filter_events_div").show();
}
},
// generate events
eventSources: [
{
url: 'calvis_get_events_caltask.php',
method: 'POST',
extraParams: function() {
return {
idusuario: $('#usuario_filter').val()
};
},
failure: function() {
alert('there was an error while fetching events!');
}
}
// any other sources...
],
// generate resources
resources: 'calvis_get_resources.php',
});
//render calendar
calendar.render();
Im fetching my data in my server side and I put checkbox.
I need some clarification, do I need to put checkbox here or it will be automatically added?
Controller
$result[] = array(
'#' => '<span style="font-size: 12px; color: gray">'.$counter++.'</span>',
'number' => '<p>'.$value->number.'</p>',
'vendor' => '<p>'.$vendor->name .'</p>',
'document_reference' => '<p>'.$value->document_reference.'</p>',
'date_needed' => '<p>'.$value->date_needed.'</p>',
'requesting_department' => '<p>'.$department->name.'</p>',
'amount' => '<p align="right">'.number_format($value->total_amount,2).'</p>',
'status' => '<p>'.$status.'</p>',
'approval_status' => '<p id="'.$value->id.'">'.$approval.'</p>',
'created_by' => '<p id="created_at'.$value->id.'">'.$user->name.'</p>',
'action' => '<i class="fa fa-eye"></i>',
'checkbox' => '<input type="checkbox" name="checkbox[]" value="'.$value->id.'">'
In my view page I used route to call this method. In here I have now my data.
My View
var table3 = $('#get-rfp-for-approval-table').DataTable({
'processing': true,
'serverSide': true,
ajax: {
url: '/requests/request-for-payment/getRFPforApproval',
dataSrc: ''
},
columns: [
{ data: '#' },
{ data: 'number' },
{ data: 'vendor' },
{ data: 'document_reference' },
{ data: 'date_needed' },
{ data: 'requesting_department' },
{ data: 'amount' },
{ data: 'status' },
{ data: 'created_by' },
{ data: 'approval_status' },
{ data: 'action' },
{ data: 'checkbox' },
],
columnDefs: [
{
targets: 11,
checkboxes: {
selectRow: true
}
}
],
select: {
style: 'multi'
},
order: [[1,'desc']]
});
Example I have 15 data, I checked data 5 and data 14. then I submit the form.
My form
if ( $('#approved-selected-form').length > 0 ) {
$('#approved-selected-form').submit(function(e){
var form = this;
var rows_selected = table3.column(0).checkboxes.selected();
// Iterate over all selected checkboxes
$.each(rows_selected, function(index, rowId){
// Create a hidden element
$(form).append(
$('<input>')
.attr('type', 'hidden')
.attr('name', 'checkbox[]')
.val(rowId)
);
});
var formData = $(this).serialize();
swal({
title: "Are you sure?",
text: "Transaction will be approved.",
icon: "warning",
buttons: true,
dangerMode: true,
})
.then((willSave) => {
if (willSave) {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
url: '/requests/request-for-payment/approvedTransaction',
type: "POST",
data: formData,
beforeSend: function() {
var span = document.createElement("span");
span.innerHTML = '<span class="loading-animation">LOADING...</span>';
swal({
content: span,
icon: "warning",
buttons: false,
closeOnClickOutside: false
});
$('.request-for-payment-finish').attr('disabled', 'disabled');
},
success: function(response) {
if (response != '') {
$('#get-request-for-payment-table').DataTable().destroy();
getRequestForPaymentTable();
$('#add-request-for-payment-form').trigger("reset");
swal("Transaction has been saved!", {
icon: "success",
});
setTimeout(
function()
{
window.location.href = "/requests/request-for-payment?id="+response+"#view-request-for-payment-modal";
}, 1500);
}
},
complete: function() {
$('.request-for-payment-finish').removeAttr('disabled');
}
});
} else {
swal("Save Aborted");
}
});
e.preventDefault();
return false;
})
}
NOTE: I tried to dd it in my controller it gives me this
array:1 [
"get-rfp-for-approval-table_length" => "10"
]
I also noticed that in my th, I dont have checkbox(when I clicked this, everything will be checked). Im using this as a guide. https://jsfiddle.net/snqw56dw/3182/.
Question: How can I get those values in my controller?
You should be returning ID in your controller.
$result[] = array(
// ... skipped ...
'checkbox' => $value->id
);
Also since checkbox in column with index 11, you should be using that index when retrieving the data.
var rows_selected = table3.column(11).checkboxes.selected();
On the side note, I see that you're using server-side processing mode ('serverSide': true). Make sure your controller returns proper response.
Need help in converting PDO array execution to mysqli statements. This executes for an AJAX POST call for deleting a particular id from database with SWAL function.
<?php
require_once 'connectivity.php';
$response = array();
if ($_POST['delete']) {
$pid = intval($_POST['delete']);
$query = "DELETE FROM students WHERE id=$pid";
$stmt = mysqli_query($query,$connect);
$stmt->execute(array(':pid'=>$pid));
if ($stmt) {
$response['status'] = 'success';
$response['message'] = 'Student Deleted Successfully ...';
} else {
$response['status'] = 'error';
$response['message'] = 'Unable to delete ...';
}
echo json_encode($response);
}
?>
This is the consecutive swal function which is to be executed once the delete button clicked.
<script>
$(document).ready(function(){
$(document).on('click', '#deleteid', function(e){
var productId = $(this).data('id');
SwalDelete(productId);
e.preventDefault();
});
});
function SwalDelete(productId){
swal({
title: 'Are you sure?',
text: "It will be deleted permanently!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!',
showLoaderOnConfirm: true,
preConfirm: function() {
return new Promise(function(resolve) {
$.ajax({
url: 'delete.php',
type: 'POST',
data: {'delete' : productId}
})
.done(function(response){
swal('Deleted!', response.message, response.status);
readDetails();
})
.fail(function(){
swal('Oops...', 'Something went wrong with ajax !', 'error');
window.location.reload(true);
});
});
},
allowOutsideClick: false
});
}
function readDetails(){
window.location.reload(true);
}
I am trying to debug a problem I have with submitHandler: function. What is happening, in firebug it is displaying the correct error message based on the true handle in the submitHandler. But, it is firing the success dialog and not the error dialog. I am fairly new to jquery and ajax so I have proably got some brackets or commas in the wrong place.
I would be grateful if someone could point out my error. Thanks
submitHandler: function() {
if ($("#USRboxint").valid() === true) {
var data = $("#USRboxint").serialize() + '&submit=true';
$.post('/domain/users/box.php', data, function(msgs) {
if (msgs.boxerror === true) {
var $dialog = $('<div id="dialog"></div>').html('<br /><b>Your New entry was NOT SUBMITTED.<br /><br />Thank you.</b>');
$dialog.dialog({
autoOpen: true,
modal: true,
title: 'New entry Unsuccessfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function() {
$( this ).dialog( "close" );
}
}
});
}
else
var messageOutputs = '';
for (var i = 0; i<msgs.length; i++){
messageOutputs += msgs[i].box+' ';
}
$("#USRboxint").get(0).reset();
var $dialog = $('<div id="dialog"></div>').html('<br /><b>Your New entry was successfully submitted.<br /><br />Thank you.</b>');
$dialog.dialog({
autoOpen: true,
modal: true,
title: 'New entry successfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function() {
$( this ).dialog( "close" );
}
}
});
//$("#frmreport").get(0).reset();
}, 'json');
}
},
success: function(msgs) {
}
PHP Code
<?php
$boxerrortext = 'No duplicates';
$array = split('[,]', $_POST['box_add']);
if (isset($_POST['submit'])) {
if ($box == 'DEMO111')
{
$error = array('boxerror'=>$boxerrortext);
$output = json_encode($error);
echo $output;
return;
}
else
$form = array();
foreach ($array as $box) {
// if (empty($box)) {
// $error = array('boxerrortext'=>$boxerrortext);
// $output = json_encode($error);
// echo $output;
// }
// else
// {
$form[] = array('dept'=>$dept,
'company'=>$company,
'address'=>$address,
'service'=>$service,
'box'=>$box,
'destroydate'=>$destroydate,
'authorised'=>$authorised,
'submit'=>$submit);
}
}
$result=json_encode($form);
echo $result;
?>
Creating dialogs each time is not efficient, better to initialize the dialogs on document ready:
$(function(){
$('<div id="dialog_error"></div>').html('<br /><b>Your New entry was NOT SUBMITTED.<br /><br />Thank you.</b>').dialog({
autoOpen: false,
modal: true,
title: 'New entry Unsuccessfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function () {
$(this).dialog("close");
}
}
});
$('<div id="dialog_success"></div>').html('<br /><b>Your New entry was successfully submitted.<br /><br />Thank you.</b>').dialog({
autoOpen: false,
modal: true,
title: 'New entry successfull',
width: 400,
height: 200,
draggable: false,
resizable: false,
buttons: {
Close: function () {
$(this).dialog("close");
}
}
});
});
Then open them when you need them:
submitHandler: function () {
if ($("#USRboxint").valid() === true) {
var data = $("#USRboxint").serialize() + '&submit=true';
$.post('/domain/users/box.php', data, function (msgs) {
if (msgs.boxerror === true) {
$("#dialog_error").dialog("open");//Open error dialog
} else var messageOutputs = '';
for (var i = 0; i < msgs.length; i++) {
messageOutputs += msgs[i].box + ' ';
}
$("#USRboxint").get(0).reset();
$("#dialog_success").dialog("open");//Open success dialog
//$("#frmreport").get(0).reset();
}, 'json');
}
}
You should add braces around the code for the else-statement, or else only the first line is is part of the else block, and all the lines after it are executed no matter what.
Change this:
else
var messageOutputs = '';
To this:
else {
var messageOutputs = '';
// Other lines that belong in the else block.
}
I disagree with Wilmer, but you should properly clean up the dialog when it is closed. Since you create the div just to display the dialog once, you should remove it when the dialog is closed. You can do this by adding the following dialog option:
close: function() { $(this).dialog('destroy').remove(); },
I get an array with the geolocation JavaScript, then I want to pass this array to a php script via ajax to process it and get an processed array back. Unfortunately it seems that the passed array to php is always NULL, I have no idea why.
My JavaScript/jQuery:
dataArray = [];
var lat = pos.coords.latitude;
dataArray.push({'lat':lat});
var lon = pos.coords.longitude;
dataArray.push({'lon':lon});
var identifier = 'ajax';
dataArray.push({'identifier':identifier});
console.debug(dataArray);
$.ajax({
async: true,
type: 'post',
cache: false,
url: 'custom.php',
data: {myJson: dataArray},
dataType : 'json',
success: function(data){
console.debug(data);
var json = $.parseJSON(data);
console.debug(json);
alert(json);
}
});
My php:
$JSArray['array'] = json_decode($_POST['myJson'], true);
$_SESSION['jsonArray'] = $JSArray['array'];
var_dump($_SESSION);
The result is always ["jsonArray"]=> NULL.
try this one. it works for me
(function($){
if(navigator.geolocation){return;}
var domWrite = function(){
setTimeout(function(){
throw('document.write is overwritten by geolocation shim. This method is incompatible with this plugin');
}, 1);
},
id = 0
;
var geoOpts = $.webshims.cfg.geolocation.options || {};
navigator.geolocation = (function(){
var pos;
var api = {
getCurrentPosition: function(success, error, opts){
var locationAPIs = 2,
errorTimer,
googleTimer,
calledEnd,
endCallback = function(){
if(calledEnd){return;}
if(pos){
calledEnd = true;
success($.extend({timestamp: new Date().getTime()}, pos));
resetCallback();
if(window.JSON && window.sessionStorage){
try{
sessionStorage.setItem('storedGeolocationData654321', JSON.stringify(pos));
} catch(e){}
}
} else if(error && !locationAPIs) {
calledEnd = true;
resetCallback();
error({ code: 2, message: "POSITION_UNAVAILABLE"});
}
},
googleCallback = function(){
locationAPIs--;
getGoogleCoords();
endCallback();
},
resetCallback = function(){
$(document).unbind('google-loader', resetCallback);
clearTimeout(googleTimer);
clearTimeout(errorTimer);
},
getGoogleCoords = function(){
if(pos || !window.google || !google.loader || !google.loader.ClientLocation){return false;}
var cl = google.loader.ClientLocation;
pos = {
coords: {
latitude: cl.latitude,
longitude: cl.longitude,
altitude: null,
accuracy: 43000,
altitudeAccuracy: null,
heading: parseInt('NaN', 10),
velocity: null
},
//extension similiar to FF implementation
address: $.extend({streetNumber: '', street: '', premises: '', county: '', postalCode: ''}, cl.address)
};
return true;
},
getInitCoords = function(){
if(pos){return;}
getGoogleCoords();
if(pos || !window.JSON || !window.sessionStorage){return;}
try{
pos = sessionStorage.getItem('storedGeolocationData654321');
pos = (pos) ? JSON.parse(pos) : false;
if(!pos.coords){pos = false;}
} catch(e){
pos = false;
}
}
;
getInitCoords();
if(!pos){
if(geoOpts.confirmText && !confirm(geoOpts.confirmText.replace('{location}', location.hostname))){
if(error){
error({ code: 1, message: "PERMISSION_DENIED"});
}
return;
}
$.ajax({
url: 'http://freegeoip.net/json/',
dataType: 'jsonp',
cache: true,
jsonp: 'callback',
success: function(data){
locationAPIs--;
if(!data){return;}
pos = pos || {
coords: {
latitude: data.latitude,
longitude: data.longitude,
altitude: null,
accuracy: 43000,
altitudeAccuracy: null,
heading: parseInt('NaN', 10),
velocity: null
},
//extension similiar to FF implementation
address: {
city: data.city,
country: data.country_name,
countryCode: data.country_code,
county: "",
postalCode: data.zipcode,
premises: "",
region: data.region_name,
street: "",
streetNumber: ""
}
};
endCallback();
},
error: function(){
locationAPIs--;
endCallback();
}
});
clearTimeout(googleTimer);
if (!window.google || !window.google.loader) {
googleTimer = setTimeout(function(){
//destroys document.write!!!
if (geoOpts.destroyWrite) {
document.write = domWrite;
document.writeln = domWrite;
}
$(document).one('google-loader', googleCallback);
$.webshims.loader.loadScript('http://www.google.com/jsapi', false, 'google-loader');
}, 800);
} else {
locationAPIs--;
}
} else {
setTimeout(endCallback, 1);
return;
}
if(opts && opts.timeout){
errorTimer = setTimeout(function(){
resetCallback();
if(error) {
error({ code: 3, message: "TIMEOUT"});
}
}, opts.timeout);
} else {
errorTimer = setTimeout(function(){
locationAPIs = 0;
endCallback();
}, 10000);
}
},
clearWatch: $.noop
};
api.watchPosition = function(a, b, c){
api.getCurrentPosition(a, b, c);
id++;
return id;
};
return api;
})();
$.webshims.isReady('geolocation', true);
})(jQuery);
jQuery(window).ready(function(){
navigator.geolocation.getCurrentPosition(successCallback,errorCallback,{timeout:10000});
function successCallback(pos) {
$('#localstore').
load("geo?latitude="+ pos.coords.latitude +"&longitude=" + pos.coords.longitude, function()
{
$('#storefinder').hide();
$('#localstore').show();
});
}
function errorCallback(pos) {
/*
$('#storefinder').show();
$('#localstore').hide();
*/
}
});
There are multiple points are which your script can be failing.
I would test each step and see where it fails (by commenting out the echo statments one at a time):
echo $_POST['myJson'];
$JSArray['array'] = json_decode($_POST['myJson'], true);
//echo $JSArray['array'];
$_SESSION['jsonArray'] = $JSArray['array'];
//var_dump($_SESSION);
Also you ajax call should contain alert(data) without parseJSON, since the server is not sending JSON back, it is just echoing out a var_dump:
$.ajax({
async: true,
type: 'post',
cache: false,
url: 'custom.php',
data: {myJson: dataArray},
dataType : 'html', // change back to json when you send json from server
success: function(data){
console.debug(data);
//var json = $.parseJSON(data);
//console.debug(json);
//alert(json);
alert(data);
}
});