Is it a proper way to send empty request? - javascript

My Example works, but I want to now if it is a good way to send empty request like my example below.
$(document).ready(function () {
$("#home").click(function (e) {
// Prevent default form action
e.preventDefault();
// AJAX Request
$.ajax(
{
url: "/command/home",
type: "GET",
success: function (response) {
alert(response);
},
error: function (error) {
alert("Error!" + error);
}
});
});
});
Thank You!

Related

How to access a selector on AJAX Complete?

I make an Ajax Request that adds content to the page with HTML from the back-end, and then I make another Ajax Request that modifies that dynamically added HTML.
$("#list-customers-button").click(function () {
var selectedAcquirer = $("#acquirer-select").val();
if (selectedAcquirer === "adyen") {
if (listed) {
listed = false;
$("#customer-list-area").hide().html('').fadeIn(fadeTime);
} else {
listed = true;
$.ajax({
type: "GET",
url: "/adyen_list_customers",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#list-progress").show();
},
success: function (data) {
console.log(JSON.stringify(data));
$("#customer-list-area").hide().html(data["response_html"]).fadeIn(fadeTime).promise().done(function () {
$(".collapsible").collapsible();
resetDatepicker();
});
},
complete: function () {
$(document).on("change", "#file-download-datepicker", function () {
$("#file-download-progress").hide();
$("#file-download-date").val(selectedDate);
fileDownloadData = $("#file-download-form").serialize();
displayMessage(fileDownloadData);
$.ajax({
type: "POST",
url: "/adyen_update_file_list_by_date",
data: fileDownloadData,
beforeSend: function () {
$("#file-download-progress").show();
},
success: function (response) {
},
complete: function (response) {
$("#file-download-progress").hide();
console.log(response.responseText);
// Doesn't work. Selector should exist, but it doesn't.
$("#merchant-file-list").html(response.responseText);
},
error: function (response) {
displayMessage(response["responseText"]);
}
});
});
},
error: function (data) {
displayMessage(data);
},
});
}
} else if (selectedAcquirer === "stone") {
displayMessage("Adquirente indisponível no momento.");
} else {
displayMessage("É necessário selecionar uma adquirente.");
}
});
I get a perfect HTML response from the server, but selectors that were previously added with HTML also from the server (#file-download-progress, #merchant-file-list) are completely ignored. .html() doesn't work, nor anything, and I don't know how to use .on() to work around this because I just need to access that content. Since the ajax request is being made after the previous one is complete, they should be able to be accessed. They just don't exist nowhere in time.

using select2.js to send ajax request

I have two select elements both using selec2.js, the first select element has drop down options populated from the database, now what I want to do is to choose an option from select element 1, get the value and send that value via ajax to query the database and return matching results and populate the results in the 2nd select element. unfortunately, I haven't succeeded with returning data back from the server, below is my code and oh I am using laravel.
$('#province').on('change', function (e) {
var data = $("#province option:selected").val();
$.ajax({
url: "{{route('list-townships')}}",
type: 'get',
data: {
province_id: data
},
success: function (response) {
console.log(response);
response.filter(function (response) {
if (response) {
//Append data to the 2nd select element
}
})
},
error: function (err) {}
})
});
Okay, I find the issue here, due to laravel CSRF request protection I had forgotten to define the CSRF Token in the ajax header. the complete code is below.
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#province').on('change', function(e) {
var data = $("#province option:selected").val();
console.log(data);
$.ajax({
url: "{{route('list-townships')}}",
type: 'get',
data: {
province_id: data
},
success: function(response) {
console.log(response);
response.filter(function(response) {
if (response) {
var townships = new Option(response.name, response.id, false, false);
$('#township').append(townships).trigger('open');
}
})
},
error: function(err) {}
})
});
});

HTTP get requests in ajax

I am pretty new to javascript where I am trying with ajax to make an get request. I am trying to get the password from the response.
Javascript code:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
var jsonStr = JSON.stringify(data);
alert(jsonStr['password']);
}
});
});
})
The response JSON code looks like this:
{"userId":16,"firstName":"mojn","lastName":"mojn","email":"mojn#mojn.dk","accountName":"Mikkel1337","password":"123","userRoleId":1,"active":false,"userRole":null,"competetion":[],"judge":[],"team":[]}
When im running this I only get the error function. Any suggestions or solution is appreciated :)
Basically you are converting the JSON to string and trying to access the string as object. Please don't stringify the data, and for JSON why using long code, your code should be:
$(document).ready(function () {
$("#LoginUser").click(function () {
$.getJSON( "http://website/api/user/Mikkel1337", function( data ) {
// do something on success
alert(data.password);
});
});
});
Cheers !!!
dont need to JSON.stringify of data simple use
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
error: function () {
alert("An error had occurred");
},
success: function (data) {
alert(data.password);
}
});
});
})
You should pass two argument for error:function(jqXHR, exception) as below.
And check once your API Url using proper way, may be your API is not show you proper result and you not get any of data from that API so that may be a reason you get error message.
$(document).ready(function () {
$("#LoginUser").click(function () {
$.ajax({
url: 'http://website/api/user/Mikkel1337',
dataType: 'json',
type: 'GET',
contentType: 'application/json',
success: function (data) {
var jsonStr = JSON.stringify(data);
//also try this way to get JSON data:
// var jsonStr =JSON.parse(data);
alert(jsonStr['password']);
},
error: function (jqXHR, exception) {
alert("An error had occurred");
},
});
});
});

Ajax success callback is not invoked

When I pass function() { location.reload(); } as a callback - it doesn't get invoked.
$('#swapLanguageLink').click(function() {
$.post('#Url.Action("SwapLanguage", "Language")', function() { location.reload(); });
//location.reload();
});
If I un-comment //location.reload(); (instead of passing callback) - it works nice, but I am not sure if it is async or not.
It can happen that my document will be reloaded before async operation is finished, right? So why my callback doesn't work?
Edit:
$.post('#Url.Action("SwapLanguage", "Language")', null, function () {
location.reload();
}).done(function () {
location.reload();
}).error(function () {
alert('error');
});
I've tried the code above. error get invoked. But "SwapLanguage" invokes. Something really strange to me!
Something like this:
jQuery.ajax({
type: "POST",
async: true,
url: '#Url.Action("SwapLanguage", "Language")',
success: function (data) {
location.reload();
},
error: function (err)
{
alert("error");
}
});
OR
$.post('#Url.Action("SwapLanguage", "Language")', null)
.done(function(data) {
location.reload();
});

Error handling for Remote Autocomplete is not working

I have this jquery autocomplete code.Everything works fine data is loaded etc.Success is working.But when i have error...error handling is not working in below code.
$("#autocomplete").on("filterablebeforefilter", function (e, data) {
if (value && value.length > 0) {
//$ul.listview("refresh");
$('.ui-responsive-panel').enhanceWithin();
$.ajax({
type: "GET",
url: "http://domain.com/food.php",
dataType: "jsonp",
crossDomain: true,
data: $(this).serialize(),
success: function (data) {
alert("success");
},
error: function () {
alert("an error occurred!");
},
beforeSend: function () {
// This callback function will trigger before data is sent
},
complete: function () {
setTimeout(function () {}, 1);
}
})
.then(function (response) {
$.each(response, function (i, val) {
//do something with data
});
}
});
As the jQuery doc states for jQuery.ajax error handler functions:
Note: This handler is not called for cross-domain script and cross-domain JSONP requests.
It is related to the technique of JSONP where the actual request is injected as a <script> tag. So a standard jqXHR object including an ajax error event isn't available. There's some plugin as workaround available. This plugin and solutions for dealing with network timeouts are discussed e.g. in this and this stackoverflow questions.
Try handling the error in the then (or use done() and fail() )
$.ajax({
//... code omitted ...
})
.then(
function (response) {
$.each(response, function (i, val) {
//do something with data
});
},
function (error) {
//do something with error
}
});

Categories