I am working on Php and ajax, I have button and whenever we click on that button,then
"Location popup" ( allow site to access your location) showing after select "allow" code is working fine
but whenever we click on "block" then futher code is not working (function error) not working,How can i do this ?
<script>
$(document).ready(function () {
$(".in").click(function () {
const options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
const crd = pos.coords;
var lats = crd.latitude;
var longs = crd.longitude;
var userId = <?php echo $ids=$_GET['eid']; ?>
$.ajax({
// further code
});
}
function error(err) {
var pathname = window.location.href;
// Now want to go futher even click on "block" button
}
navigator.geolocation.getCurrentPosition(success, error, options);
});
});
<button name="intime" class="clcbtn in">Clock in</button>
You can have another ajax call in your error function, but if the first error was caused by a problem with ajax, then the second ajax call might also run into an error.
So, you should make sure, that the error was because the user declined the access adn then you can have another ajax call.
function error(err) {
if (error.code == error.PERMISSION_DENIED) {
// Put your second ajax call here
}
}
Related
Jtable pagination is not working if I am pressing back button.
I have some 4 option in menu. First option is home and last is report. When I am clicking on report, getting a list which I am displaying by using jtable. After clicking page 1,2,3,4,10,20 new page come. But after pressing back button previous should display. For that I modified some code of jtable api.
/* Performs an AJAX call to reload data of the table.
*************************************************************************/
_reloadTable: function (completeCallback) {
var self = this;
//Disable table since it's busy
self._showBusy(self.options.messages.loadingMessage, self.options.loadingAnimationDelay);
//Generate URL (with query string parameters) to load records
var loadUrl = self._createRecordLoadUrl();
//Load data from server
self._onLoadingRecords();
self._ajax({
type:'GET',
url: loadUrl,
cache : false,
data: self._lastPostData,
success: function (data) {
var historyData = self._lastPostData;
historyData.url=loadUrl;
history.pushState(stringifyObject(self),'List',window.location.href);
location.hash = loadUrl;
self._hideBusy();
//Show the error message if server returns error
if (data.Result != 'OK') {
self._showError(data.Message);
return;
}
//Re-generate table rows
self._removeAllRows('reloading');
self._addRecordsToTable(data.Records);
self._onRecordsLoaded(data);
//Call complete callback
if (completeCallback) {
completeCallback();
}
},
error: function () {
self._hideBusy();
self._showError(self.options.messages.serverCommunicationError);
}
});
},
And added one more method
window.onhashchange = function() {
//console.log(JSON.stringify(eval("(" + history.state + ")"));
if(history.state!=null){
var self = JSON.parse(history.state);
alert(self._createRecordLoadUrl());
alert(self.state._lastPostData);
self._reloadTable(completeCallback);
}
}
I am not able to call these method because self is not jtable object.
Please provide better solution.
I have a website where users can work on projects and their work gets automatically saved to my database. Every couple seconds on my site an ajax (post) call occurs (usually in jquery) to check permissions and what not.
With one section of code is there any way so check if any of the ajax calls on your page fail. I don't want to have to go to every individual call and add a block of code to the end.
Basically this is so I can alert the user if they have lost connection or if something is going wrong.
You can use the jQuery event ajaxError. It will be triggered whenever an Ajax request completes with an error:
$(document).ajaxError(function() {
console.error('Error');
});
Check out the documentation.
$(document).ready(function(){
//ajax setup settings
$.ajaxSetup ({
cache: false,
async: false,
statusCode: {
404: function() {
alert('Page not found!');
},
500: function(jqXHR, textStatus) {
alert('Server side: ' + textStatus);
}
}
});
});
I hope this may help you
I would suggest you to override the original jquery ajax function.
var $_ajax = $.ajax; // reference to original ajax
$.ajax = function(options) {
if (options.error) {
// reference to original error callback
var originalErrorHandler = options.error;
var errorHandlerContext = options.context ? options.context : $;
var customErrorHandler = function(xhr, status, error) {
// notify error to your user here
};
// override error callback with custom implementation
options.error = customErrorHandler;
};
return $_ajax.apply($, arguments);
}
I have an ajax call in my javascript that returns and loads a partial view into a div. This function used to work but then all the sudden it stopped. I do not think I changed any code or anything that would cause issue but obviously something is going on. The Ajax call will work on the first time when you click on the button in which it is called but never again until you reload the page. I have tried adding more parameters and moving the javascript around but it still did not work. Is there any reason why this could happen?
I have tried moving the javascript out of the onOpen event and the same thing still happens. I have also put an alert call to make sure it is getting to the success call and the alert is called. I have also installed fiddler to check the call and the call is never made except on the first click of the button. This is a very frustrating error and all help is much appreciated.
Here is my Javascript:
#section scripts
{
<script type="text/javascript">
$(document).ready(function () {
$("#assets-button").on("click", function ()
{
$('#assets-container').bPopup(
{
modal: true,
onOpen: function () {
$.ajax({
type: 'GET',
url: '#Url.Action("EmployeeAssets", "Employee",new { id = Model.ID, empNo = Model.EmployeeNumber, username = Model.UserName })',
success: function (data) {
$('#assets-container').html(data);
}
});
},
onClose: function () {
var f = $('#assets-container').children('form');
var serializedForm = f.serialize();
var action = '#Url.Action("EmployeeAssets","Employee",new {empNo = Model.EmployeeNumber})';
$.post(action, serializedForm);
}
});
});
});
</script>
}
Here is the action that I am trying to call:
[HttpGet]
public ActionResult EmployeeAssets(int id, int empNo, string username = null)
{
var assets = _employeeDb.EmployeeAssets.FirstOrDefault(e => e.EmpNo == empNo);
if (assets == null)
{
var firstOrDefault = _employeeDb.EmployeeMasters.FirstOrDefault(e => e.EmployeeNumber == empNo);
if (firstOrDefault != null)
{
username = firstOrDefault.UserName;
}
var newasset = new EmployeeAsset()
{
EmpNo = empNo,
UserName = username
};
_employeeDb.EmployeeAssets.Add(newasset);
_employeeDb.SaveChanges();
assets = newasset;
}
return PartialView(assets);
}
You may try using the cache property of the settings object you are passing to the AJAX call. According to the jQuery documentation for .ajax the default for cache is set to true, so I wonder whether your browser is accessing a cached copy of the result after the first request. Looks like you could also set the dataType, and that will default the cache back to false.
Also, I would suggest putting your alert inside of the onOpen event handler in addition to the success handler just to be sure that's also being called. So that may help you debug a bit further.
I have a series of buttons that execute different functions when clicked. The function checks whether the user is logged in, and if so proceeds, if not it displays an overlay with ability to log in/create account.
What I want to do is re-execute the button click after log-in, without the user having to reclick it.
I have it working at the moment, but I'm pretty sure that what I'm doing isn't best practice, so looking for advice on how I can improve...
Here's what I'm doing: setting a global variable "pending_request" that stores the function to be re-run and in the success part of the log-in ajax request calling "eval(pending_request)"
Example of one of the buttons:
jQuery('#maybe_button').click(function() {
pending_request = "jQuery('#maybe_button').click()"
var loggedin = get_login_status();
if (loggedin == true) {
rec_status("maybe");
}
});
.
success: function(data) {
if(data === "User not found"){
alert("Email or Password incorrect, please try again");
}else{
document.getElementById('loginscreen').style.display = 'none';
document.getElementById('locationover').style.display = 'none';
eval(pending_request);
pending_request = "";
}
}
Register a function to handle the click and then invoke that func directly without eval().
jQuery('#maybe_button').on('click', myFunction)
This executes myFunction when the button is clicked. Now you can "re-run" the function code every time you need it with myFunction().
And btw since you are using jQuery you can do $('#loginscreen').hide() where $ is an alias for jQuery that's auto defined.
EDIT
Please, take a look at the following code:
var pressedButton = null;
$('button1').on('click', function() {
if (!isLoggedIn()) {
pressedButton = $(this);
return;
}
// ...
});
And, in your success handler:
success: function() {
// ...
if (pressedButton) pressedButton.trigger('click');
// ...
}
How would I go about integrating these two functions together so that when submitting the search form, it will first check the http get response, then depending on whether there was an error or not, either submit the form, or display an error message?
All that I've tried has either made the form not work at all, or not take into account the 'http.get function'.
var http = require("http");
var url = 'http://examplepage.com/';
search.submit(function (event) { // submit search query function
if (searchBox.val().length < 2) {
searchBox.focus();
event.preventDefault();
}
});
http.get(url, function (res) {
res.resume();
// successful - so submit search query
}).on('error', function () {
// unsuccessful - display error message
});
You should probably subscribe on click event for you button that triggers search, the go check the url and inside success handler do
Sample code of Click handler
http.get(url, function (res) {
// successful
if (searchBox.val().length < 2) {
$('your form selector').submit();
}
}).on('error', function () {
// unsuccessful - display error message
});