After $.ajax request, i cannot load other page on new tab in browser. what is the reason?
my javascript code in this url https://example.com/page1.php:
$('#myButton').on("click", function(event) {
event.preventDefault();
$.ajax({
url: "models/data.php",
type: "POST",
data: {...},
dataType: 'json',
context: this,
success: function(data) {
//...
},
error: function (asd, textStatus, errorThrown) {
//...
}
});
});
after click on myButton i cannot load another url in other tabs, As long as the ajax request ends. for example https://example.com/page2.php what is the reason?
Related
I'm trying to create a search field on the top navbar with ajax. Since it's on the navbar, it has to be present on all pages, therefore the URL is constantly changing.
$.ajax({
type: 'GET',
url: CURRENT_URL,
dataType: 'json',
data: {
search: userSearch
},
success: function (){...
I'm working with Laravel, so i tried this on the navbar page:
<script>
var CURRENT_URL = "{{url()->current()}}"
</script>
The CURRENT_URL is displayed fine if i try to console log it, but ajax gives an error "Source map error: Error: request failed with status 404".
How can i insert the current URL into the ajax request?
You can use location.href instead of CURRENT_URL
$.ajax({
type: 'GET',
url: location.href,
dataType: 'json',
data: {
search: userSearch
},
success: function (){...
or
<script>
var CURRENT_URL = location.href;
</script>
Hopefully, this can help. Here's my approach to make my url dynamically I get the URL in every forms var URL = $('#example_form').prop('action'); then the URL variable must append or set via Js/Jquery. check my example below.
<script type="text/javascript">
var URL = $('#example_form').prop('action');
$.ajax({
type:'GET',
url: URL+'/clearContent',
beforeSend: function (xhr) {
var TOKEN = $('meta[name="csrf-token"]').attr('content');
if (TOKEN) {
return xhr.setRequestHeader('X-CSRF-TOKEN', TOKEN);
}
},
data:{
get_category_id : $('.parent-id').val(),
},
success:function(data){
if (data.response.status == true) {
// your codes here
}
},
dataType: 'json',
complete: function () {}
});
I have a pretty standard ajax call for a live update, however, say I call the the ajax, everything is good, but say I want to call it again, this time, I will get 2 calls, and if I try again then I'll have 3, I can verify this by invoking and alert and with the Network DevCon of Chrome, any idea why this is happening?
P.S: I'm using Laravel 5.1
$('button[name=act]').click(function() {
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function() {
icon.show();
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
$(icon).fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
});
The problem is that every time you click on the act button you call $("form").submit(), which adds anothersubmithandler to the form. So if you click on theact` button 3 times, and then click on the form's submit button, it will send 3 AJAX requests.
It's almost always wrong to bind one event handler inside another event handler, you should bind all the event handlers at top level.
var icon;
$(document).ajaxStart(function() {
if (icon) {
icon.show();
}
});
$('button[name=act]').click(function() {
icon = $(this).closest('div.thumbnail').find('i');
});
$("form").submit(function (e) {
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr) {
if (icon) {
icon.fadeIn(function() {
$(this).removeClass('fa-spinner fa-spin').addClass('fa-check text-success').fadeOut(1000, function() {
$(this).removeClass('fa-check text-success').addClass('fa-spinner fa-spin');
});
});
}
}/*,
error: function (jqXhr, textStatus, errorThrown) {
console.log("Error response:", jqXhr.responseText);
}*/
});
});
The reason this is happening is because you are rebinding the submit event function every time the button is clicked which results in multiple copies of the function. Just move it out of the click even, and if you want to force a submit on a click, you can call the submit() function with no parameters to fire the event.
Try the following:
$(function(){
$('button[name=act]').click(function(){
var icon = $(this).closest('div.thumbnail').find('i');
$(document).ajaxStart(function()
{
icon.show();
});
$("form").submit(); //This submits the form on click
});
//This binds the function, so it should only be called once.
$("form").submit(function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: "ajax/acttdb",
data: formData,
dataType: "json",
type: "POST",
cache: false,
contentType: false,
processData: false,
success: function (data, status, jqXhr)
{
//BLAH
}
});
});
});
I noticed two other things you might want to address. You want to somehow update the icon after it is loaded. You will need to have some other way to find the icon inside of the success function (possibly looking at the data that came back could yield some information that could be useful. Since it is json, it should be easy to update.)
Also, the way you currently have it will bind to all forms on the page. In the event that you have multiple forms on the page, you will probably want to change the selector to use an id.
Hope this helps!
Based in incremental calls and my guessings, I have to say that you're printing this code each time you make the (ajax) call, leading to bind your form element again in each call..
Am I right?
JO.
Hi everyone I'm trying to incorporate jQuery AJAX on my multi-step form so that it updates a certain div to the one on the process.php page but it keeps loading the results on a new page. How can I get it to update the div without refreshing the page?
This is the jQuery code I'm using:
$.ajax({
url: 'process.php',
data: $('form[name="booking"]').serialize(),
dataType: 'html',
type: 'POST',
success: function(data) {
// this is the bit that needs to update the div
$('#last-step').fadeOut(300, function() { $('#result').html(data).fadeIn(300);
},
complete: function (data) {
// your code here
},
error: function (url, XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
This is the code for my multistep form: http://jsfiddle.net/xSkgH/47/.
Many thanks in the advance
I dont see a div called result in your Markup. So probably you need to show your result in the last div you are showing. And you are missing }) also. the below code should work,
$.ajax({
url: 'process.php',
data: $('form[name="booking"]').serialize(),
dataType: 'html',
type: 'POST',
success: function(data) {
// this is the bit that needs to update the div
$('#last-step').fadeOut(300, function() {
$('#last-step').html(data).fadeIn(300);
});
},
complete: function (data) {
// your code here
},
error: function (url, XMLHttpRequest, textStatus, errorThrown) {
alert("Error: " + errorThrown);
}
});
I'm not sure why this is happening, but when my page loads, there's an XHR request immediately for the search results. It's invisible to the user, but it's loading a fairly large chunk of json data.
Here's my code:
$.ajax({
type: "POST",
url: "http://localhost:8888/index.php/ajax/get_client",
dataType: "json", data: "{}",
success: function(data) {
$('#search').autocomplete({
source:data,
minLength:2,
delay:0,
appendTo:'header',
selectFirst:true,
select:function(event, ui) {
$("input#search").val(ui.item.value);
$("#search").closest('form').submit();
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
How can I make it so the json data is only requested when the user types in the input#search box?
It looks like you want to load a list autocomplete results and then initialize the autocomplete plugin only if the user starts typing. To do this, bind a keyup function to the search box, if the results have not been loaded, then load the results and initialize the plugin.
$(document).ready(function(){
var searchInput = $("input#search");
function loadData(onSuccess){
$.ajax({
type: "POST",
url: "http://localhost:8888/index.php/ajax/get_client",
dataType: "json", data: "{}",
success: onSuccess,
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
}
function initializeAutocomplete(data){
searchInput.addClass('loaded').autocomplete({
source:data,
minLength:2,
delay:0,
appendTo:'header',
selectFirst:true,
select:function(event, ui) {
searchInput.val(ui.item.value).closest('form').submit();
}
});
}
searchInput.keyup(function(){
if($(this).is(".loaded")) return;
loadData(initializeAutocomplete);
});
});
Wrap your ajax call into a button.click() event or if you want it calling while the user is typing, put it in a textbox.keypress() event.
You need to bind a keyup event listener to your input box.
If you've inserted this code right inside your html page without a event listener, the code will execute right after your page loads.
This should probably work: http://jsfiddle.net/XNbrX/
I haven't tested it.
I don't know if I understand you, but I think that you want to run this code on every key press (really key up) to load results on every change of search box value.
If I'm right, put your code into function which is triggered on 'onkeyup' event.
$('input#search-box').keyup(function() {
$.ajax({
type: "POST",
url: "http://localhost:8888/index.php/ajax/get_client",
dataType: "json", data: "{}",
success: function(data) {
$('#search').autocomplete({
source:data,
minLength:2,
delay:0,
appendTo:'header',
selectFirst:true,
select:function(event, ui) {
$("input#search").val(ui.item.value);
$("#search").closest('form').submit();
}
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
I'm creating a CMS using jQuery and AJAX. When I click, my "Add Campaign" buttom, it creates a unique client ID in the DB and on a hard reload, the new client shows up in its container. I am trying to use ajax to reload the container on the fly and I'm not having the exact luck i am hoping for. I can get it to reload, but it's like it's pulling in descriptions of each of the clients as well!
function AddNewClient() {
dataToLoad = 'clientID=' + clientID + '&addClient=yes';
$.ajax({
type: 'post',
url: '/clients/controller.php',
datatype: 'html',
data: dataToLoad,
target: ('#clientssidebar'),
async: false,
success: function(html){
$('#clientssidebar').html(html);
},
error: function() {
alert('An error occured!');
}
});
};
Try:
function AddNewClient()
{
dataToLoad = 'clientID=' + clientID + '&addClient=yes';
$.ajax({
type: 'post',
url: '/clients/controller.php',
data: dataToLoad,
success: function(html){
$('#clientssidebar').html(html); },
error: function() {
alert('An error occured!'); }
});
}