The code below performs ajax request whenever a link is clicked. It first performs request and then follows the link specified in href. This works fine in Chrome, but in Firefox or Safari, such code doesn't successfully post data for reasons unknown to me. What would be the workaround for these 2 browsers?
$(".submit-link").click(function(e){
var value=$.trim($(".url-submit").val());
if(value.length>0){
//initialize name and email
$.ajax({
url: "getPOST.php",
type: 'POST',
data: {"id":value,"name":nameValue, "email":emailValue},
success: function(response) {
console.log(response); //nothing gets printed in console when using Firefox or Safari, but in Chrome it works as expected
}
//go to link in href now
});
}else{
//do something else
e.preventDefault();
}
});
Just lets make the code more simple;
$(".submit-link").click(function (e) {
e.preventDefault();
var value = $.trim($(".url-submit").val());
if (value.length > 0) {
//initialize name and email
$.ajax({
url: "getPOST.php",
type: 'POST',
data: { "id": value, "name": nameValue, "email": emailValue },
success: function (response) {
console.log(response);
window.location = $('.submit-link').attr('href'); //Assumed your element that has submit-link class also contains the href attribute
}
});
}
});
After you completed your ajax request, now you can go to link.
I added e.preventDefault(); at the start of function. If the value length greater than "0" it will make the ajax request and after the ajax request completed user will be redirected to link.
Also check your value to be sure it has length greater than "0".
Related
the title may be a bit misleading but I'm not sure how to phrase it better, so I apologize for that.
I'm creating a custom handler so the site doesn't refresh when new content is pressed (similar to how youtube works, for example).
For that I'm using this script:
$('.sidebar2 li a').click(function (e) {
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
e.preventDefault();
test = false;
return false;
}
}
});
});
even though I've stated e.preventDefault() to trigger, javascript loads the new content into the current frame without refreshing, but the browser refreshes again anyway.
I've tried to use href="#" however in this case when I go back and handle that, I always end up with two same pages, one without and one with # at the end, and in addition to that it wouldn't be very user friendly to have all links href="#"
What am I doing wrong to make the browser redirect "normally" even though I've told him no no no?
I've also tried adding onclick="javascript:void(0)" on a elements and that didn't help
ajax is async. By the time success callback is called event will already be bubbled up the DOM tree and processed. You need to call preventDefault before sending a request.
$('.sidebar2 li a').click(function (e) {
e.preventDefault(); // here for example
test = true;
var button = $(this);
var noteId = button.data("noteid");
$(".sidebar2 li.active").removeClass("active");
var postData = { id: noteId };
$.ajax({
url: '/API/Note',
type: 'get',
data: postData,
success: function (resp) {
if (resp.success == true) {
$('#app-bar-left').html(resp.note.navBarHTML);
$('#cell-content').html(resp.note.noteContentHTML);
window.history.pushState({ path: window.location.href }, resp.note.title, '/MyNotes/Note/' + resp.note.noteId);
document.title = resp.note.title;
$('*[data-noteId="'+resp.note.noteId+'"]').parent().addClass("active")
test = false;
// returning here makes no sense also
// return false;
}
}
});
});
I want to change the content of an element using .html() to indicate that a process has started.
But the problem is that it won't work no matter what I do. I might be missing something here that prevents the script from working.
Code:
if(counter < 1 && flag == true){
alert("test");
$("#updownform").html("Please Wait...");
// if(confirm("Are you sure you want to proceed?")){
// counter++;
// $.ajax({
// method: "POST",
// url: "index.php?module=Accounts&action=processUpdowngrade",
// data: {form_data: $(this).serialize()},
// success: function (datas) {
// counter = 10000;
// location.reload();
// }
// });
// }else{
// $("#updownform").html("Save changes");
// }
}
In this example where everything is commented out except for the alert and .html(). The .html() works but if I uncomment everything it will only work when AJAX is finished with the request even after the confirm condition was triggered. Which I found weird since I already placed it before the confirm condition. So ideally it would have executed before the confirm condition.
I also tried using beforeSend but it still didn't work. I also tried setting it to asynch:false/true together with beforeSend to no avail.
I would recommend trying the code below to see if it helps.
<script>
if (counter < 1 && flag == true) {
alert("test");
document.getElementById("updownform").value = "Please Wait...";
if (confirm("Are you sure you want to proceed?")) {
counter++;
$.ajax({
type: "POST",
url: "index.php?module=Accounts&action=processUpdowngrade",
data: $("#enter_your_form_id").serialize(), // serializes the form's elements.
success: function(data) {
counter = 10000;
location.reload();
}
});
} else {
document.getElementById("updownform").value = "Save changes";
}
}
</script>
I have developed an ASP.NET MVC Application using JavaScript, jQuery.
I have implemented to be restrict multiple user logins at same time using onbeforeunload/beforeunloadevent.
It works fine, but sometimes not working in onbeforeunload/beforeunloadevent.
var myEvent = window.attachEvent || window.addEventListener;
var chkevent = window.attachEvent ? 'onbeforeunload' : 'beforeunload'; /// make IE7, IE8 compitable
myEvent(chkevent, function (e) { // For >=IE7, Chrome, Firefox
if (!validNavigation)
{
$.ajax({
url: '#Url.Action("ClearSession", "Account")',
type: 'Post',
data: "",
dataType: "json",
success: function (data)
{
console.log("onbeforeunload Success")
},
error: function (data) {
console.log("onbeforeunload Error")
}
});
}
return null;
});
There is one also function in AJAX - jQuery is called complete: function(){};
This function checks weather request is running for same user id and password on browser or not, Like this here
complete: function() {
$(this).data('requestRunning', false);
}
Whole AJAX-jQuery implementation here see and implement accordingly, I hope it will work fine for you
Code Here
$('#do-login').click(function(e) {
var me = $(this);
e.preventDefault();
if ( me.data('requestRunning') ) {
return;
}
me.data('requestRunning', true);
$.ajax({
type: "POST",
url: "/php/auth/login.php",
data: $("#login-form").serialize(),
success: function(msg) {
//stuffs
},
complete: function() {
me.data('requestRunning', false);
}
});
});
See this me.data('requestRunning', false); if it will get any request running for same user id and password it returns false and cancel login.
For more help see here link Duplicate, Ajax prevent multiple request on click
This is not perfect solution but you can implement like this
I have the following jQuery code, the point of this code is to create a short time delay, so the AJAX request gets time to execute properly:
$('#form_id').submit(function(e) {
e.preventDefault();
$submit_url = $(this).data('submitUrl');
$submit_url = $submit_url.replace('http://','').replace(window.location.host,'');
if ($(this).data('toBeAjaxSubmitted') == true) {
$.ajax($submit_url, {
type : $(this).attr('method'),
data : $(this).serialize(),
complete : function(data) {
$(this).data('toBeAjaxSubmitted', false);
$('#form_id').submit();
}
});
}
});
What happens is, the form starts off with a submit url that I need to submit to in order for the component to save an entry to the database. But I also need user input to submit directly to a payment gateway URL where the user then makes a payment.
The code above creates the AJAX request, but does not return to normal postback behaviour (via $('#form_id').submit()).
It keeps submitting the form over and over, but never posts to the gateway URL or redirects out.
What am I doing wrong?
The following worked for me after some more debugging:
$('#chronoform_Online_Submission_Step8_Payment').submit(function(e) {
var form = this;
e.preventDefault();
$submit_url = $(this).data('submitUrl');
$submit_url = $submit_url.replace('http://','').replace(window.location.host,'');
if ($(this).data('toBeAjaxSubmitted') == true) {
$.ajax($submit_url, {
type : $(this).attr('method'),
data : $(this).serialize(),
complete : function(data, status) {
}
}).done(function() {
form.submit();
});
}
});
What really put me on the wrong path was that in Chrome's Developer Tools I had the following option enabled 'Disable cache (while DevTools is open)' and this was causing some headaches with inconsistent behaviour between Safari, Firefox (which worked) and Chrome which did not.
What about some fiddling with this approach?
$('#form_id').submit(function(e) {
// closures
var $form = $(this);
var fAjaxComplete = function(data) {
// don't send the ajax again
$form.data('toBeAjaxSubmitted', 'false');
// maybe do some form manipulation with data...
// re-trigger submit
$form.trigger('submit');
};
var oAjaxObject = {
type : $form.attr('method'),
data : $form.serialize(),
complete : fAjaxComplete
};
var sSubmitUrl = $form.data('submitUrl');
// scrub url
sSubmitUrl = sSubmitUrl.replace('http://','').replace(window.location.host,'');
// if ajax needed
if ($form.data('toBeAjaxSubmitted') != 'false') {
// go get ajax
$.ajax(sSubmitUrl, oAjaxObject);
// don't submit, prevent native submit behavior, we are using ajax first!
e.preventDefault();
return false;
}
// if you got here, go ahead and submit
return true;
});
I have the following code build using jquery. When a user copies and pastes a a youtube url, i am suppose to extract the video id is the getVideoId(str) method in jquery. Using the id, i get the video image picture title and contents.
When the textbox->("#url") has a length more than 10, i will make a ajax request. Thus the ajax request is working. But now i have another problem. The very first time when the textbox has more than 10 characters, there is two ajax request being fired (tested using firebug). Than when the user enters more characters, there are many ajax request fired.
Thus this will slow down the process of the last ajax request. I just want to get the data of the youtube link and show a suggest where the user can add the title and content. It is like how the old facebook video video link is. Anyone has a better suggest in improving the codes?
jQuery(document).ready(
function(){
$("#url").keyup(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if($length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
alert('success in getting data');
}
});
return;
}
});
function getVideoId(str) {
var urlRegex = /(http|https):\/\/(\w+:{0,1}\w*#)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%#!\-\/]))?/;
if (urlRegex.test(str) && str.indexOf('v=') != -1)
{
return str.split('v=')[1].substr(0, 11); // get 11-char youtube video id
} else if (str.length == 11) {
return str;
}
return null;
}
}
);
You could cache the calls and use blur event and not keyup: you are firing a lot of AJAX call because keyup() fires an event each time a key is pressed, you should use blur that fires an event when an input loses focus.
If you cache the calls in an object you can avoid a lot of repeated calls
var cacheUrl = {};
$("#url").blur(function() {
var $t1 = $("#url").val();
var $length = $t1.length;
var $data;
$("#title").val($length);
$("#content").val($t1);
if($length==0){
alert('zero value');
return;
}
if(cacheUrls[$t1] !== undefined && $length>10){
$data = $.ajax({
url: '<?php echo $this->Html->url(array("action" => "retrieveVideoFeed"));?>',
dataType: "json",
data: {
vid: getVideoId($t1)
},
success: function(data) {
//save the data to avoid a future call
cacheUrls[$t1] = data;
alert('success in getting data');
}
});
return;
}elseif ($length>10){
//you already have the data in cacheUrls[$t1]
}
});
EDIT if you want to use the submit key to start the search you could trigger the blur event when you press enter like this:
$("#url").keypress(function(e){
if(e.which == 13){
$(this).blur();
return false;
}
});
I think many ajax requests are fired because you are using $("#url").keyup(function()
so that for every key event in url input the particular funciton will exectue.So, as per i know better to use focusout method instead of keyup.
If you stay with the keyup-Event you maybe want to use an ajaxmanager-plugin for jQuery which can manage queues or limits the number of simultaneous requests.
$.manageAjax.create('myAjaxManager', {
queue: true,
cacheResponse: false,
maxRequests: 1,
queue: 'clear'
});
....
if($length>10){
$data = $.manageAjax.add({ ...
This will prevent having alot of ajaxrequests active at the same time when the user is typing. As soon as he stops the request will not aborted and the results will show up.