AJAX multiple responses - javascript

I'm diving into JavaScript and AJAX technologies now, and I understand AJAX and POST well with it. Now I wonder whether there's something like a broadcasting channel that my PHP code (in this case, Laravel controller) broadcast to, which then is received by JavaScript on the client side in order to manipulate something, say a process like this:
User clicks a button, a spinner is shown inside the button. Next to the button, there's a status label indicating the current process/task being processed. Finally, the button becomes a link or something else. So, what I want now is that I can update the status multiple times, since my current AJAX code will only receive one message, or one status, at the end of the process and that's it, nothing in between:
$.ajax({
url: "/admin/test",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST',
dataType: 'json',
data: {
id: whatever
},
success: function(result)
{
console.log(result.status);
}
});
Now I wonder how this further works.

You can make use of beforeSend event of ajax and use to start a progress bar and when it completes you can make progress bar width to 100%
$.ajax({
url: "/admin/test",
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
method: 'POST',
dataType: 'json',
data: {
id: whatever
},
beforeSend : {
// start progress bar
},
success: function(result)
{
console.log(result.status);
// complete progress bar
}
});
Additionally, you could use css to apply transition to give the feeling the of progress in progress bar.

Use the concept of javascript callback or promise. You can creatw a script where when the button is clicked , a onclick function will run and change the content inside of tge button and when changed do the ajax call and if success call the promise again

Related

Opening new page passing parameters without showing them on the URL

I'm making a MVC C# Web App, and I began wondering whether you could open other pages that need parameters to function, without actually sending them through the URL, which is unsafe, and can lead to some user messing up another registry of the database.
My issue is though, I've never done such a thing, and I cannot find any example of code that does such a thing. The project is run with C# and JS, and the main things I've tried include:
-Doing so with Ajax:
First of all I have a button that calls for a function:
Link Text|
function openHorario(id, id_schedule, id_tool) {
alert(oid, id_schedule, id_tool);
$.ajax({
type: 'POST',
url: '/Schedules/actionEditStuff',
data: {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
},
async: 'false',
success: function (data) {
//???
}
});
}
I know there's a way to go to a new page with the success Ajax return, but... That also requires for you to send the parameters through URL.
Obviously, that didn't work, because what the action does in the controller is to return a view, not a page. So... I realized that my idea was not very smart, and moved onto somewhere else: Link, but those always end up having to send the parameters visibly through URL.
Is there any way at all to do this in a proper, clean manner?
Thank you!
#Layan - just to illustrate my comment above, - you could implement something along these lines:
your client side invokes via ajax
...
var data = {
id: id,
id_schedule: id_schedule,
id_tool: id_tool
};
$.ajax({
url: '/Schedules/actionEditStuff',
type: "POST",
data: data,
contentType: 'application/json; charset=utf-8',
success: function (view) {
//load returned data into div? or popup?
}
, error: function (xhr, status, error) {
...
}
});
...
and your controller action
public ActionResult actionEditStuff(....parameters...)
{
...
...do your magic ...
return PartialView("~/Views/_PartialViewThatShowsSomething.cshtml", ...pass model...);
}

Ajax call does not work at first, but successful call afterwards

I'm working on Cordova hybrid mobile app. I'm calling an API to load data into my variables and process it. Below is the problem.
First, I call the API using ajax. After ajax call, I check if jsonString is empty and if it is, I reload the page to run the ajax call again.
$.ajax({
url: GetConfigUrl // working URL,
type: 'POST',
data: {
token: '123456'
},
cache: false,
datatype: 'json',
contenttype: "application/json",
success: function (data, response, xhr) {
debugger
jsonString = data.Value;
},
error: function (data) {
// do nothing
)
});
if (jsonString == '') {
// Display popup to ask user the reload the page
}
return true;
I have a debugger in place in the success call function, but it does not hit and directly go to check if jsonString is empty, which is empty because it does not call the ajax to load data and proceed to display popup to ask user to reload the page.
After hitting the page reload, the debugger in the success call is being hit and able to retrieve the value. Thus the jsonString is not empty and able to proceed.
I check the Network tab in the console, it shows the below result:
It seems that the first call was made but always remain pending. The second call is the success one and return the correct value. So the jsonString checking is passed.
This issue happen all the time where the first ajax call is not success and in pending but all subsequent calls are successful.
So what could be wrong here? How do I ensure that the first ajax call will be made successfully and return the data all the time?
Ajax is executed asynchronous place your logic in the success function for it to get executed when the ajax call completes
$.ajax({
url: GetConfigUrl // working URL,
type: 'POST',
data: {
token: '123456'
},
cache: false,
datatype: 'json',
contenttype: "application/json",
success: function (data, response, xhr) {
debugger
jsonString = data.Value;
if (jsonString == '') {
// Display popup to ask user the reload the page
}
},
error: function (data) {
// do nothing
)
});
return true;

async ajax inside another ajax

I have an ajax call inside ajax. Problem is I have to wait second ajax finish because until that time browser freezes. Why is this happening if I set it to async true? I dont want to wait for any response from this second inner ajax and I dont need any response from it. It is just an email notification to some users based and needs parameters from first ajax.
$.ajax({
url: 'route_process.php',
cache: false,
async: true,
type: 'post',
data: {type: document.getElementById('type').value},
dataType: 'html',
success: function(data) {
data = data.split("brk");
$('.spinner').css({'display':'none'});
$('#save_button').prop("disabled",false);
$.ajax({
url: 'sent_hike_drive_notification.php',
cache: false,
type: 'post',
async: true,
data: {type: data[1], insert_id: data[2], date_search_array: data[3], from_city_lat: data[4], from_city_lng: data[5], to_city_lat: data[6], to_city_lng: data[7], counter: data[8], insert_id2: data[9], date_search_array2:data[10]},
dataType: 'html',
success: function(result) {
}
});
Drive.resetRoute();
alert(data[0]);
},
Thanks all, now I found out the problem is not maybe in those ajaxs. User wants to move to another webpage through load when click on menu icon.
$('.main_body').find('.container').load(url);
This dont works until those ajax finish. So not complete browser freezes only I cannot navigate to next page.
Common, Ajax is indeed async but You should remember that a success handler is called only when the ajax call is complete whether sync or async So this inner ajax call can be called only when the first is complete. There is no way you can access inner ajax call without first being completed. All you can do is make an ajax call via callback on the success handler of the outer ajax.
This is not an exact answer to your problem but only a help/checklist :
The most common causes of the UI freezing on making an ajax call when the call is async:true are as follows:
A lot of Dom manipulation taking place on response of the call.
A lot of data is being sent by the server and processing it requires time.
If a session is being maintained and it is not closed before multiple ajax callbacks (this happens to avoid race conditions).
Something on the server side goes wrong/extremely slow on the ajax call and the client side is stuck.
Network speed is too slow.
EDIT: Based on the response from asker , to help others if they face similar issue.
Is there a redirection involved which is locking up with ajax response.
It is highly unlikely that the UI freezes despite all the check points mentioned above taken care of.
In any case the solution might be one of the following approaches :
Try making a call to the second ajax after a timeout of like 5000 ms.
Try promises : how does jquery's promise method really work?
(worst way)Try using an iframe to make the requests.
try to use promise.
$.ajax({
url: 'route_process.php',
cache: false,
async: true,
type: 'post',
data: {type: document.getElementById('type').value},
dataType: 'html'
}).promise().then(function(data) {
data = data.split("brk");
$('.spinner').css({'display':'none'});
$('#save_button').prop("disabled",false);
$.ajax({
url: 'sent_hike_drive_notification.php',
cache: false,
type: 'post',
async: true,
data: {type: data[1], insert_id: data[2], date_search_array: data[3], from_city_lat: data[4], from_city_lng: data[5], to_city_lat: data[6], to_city_lng: data[7], counter: data[8], insert_id2: data[9], date_search_array2:data[10]},
dataType: 'html',
success: function(result) {
}
});
Drive.resetRoute();
alert(data[0]);
})

Link to anchor not yet loaded (ajax)

I'm loading comments with ajax in my website, and I'm sending to users notification with an anchor to the specific comment.
The anchor is not working, that piece of DOM isn't loaded yet.
How can I handle this? Maybe something "on ajax complete" ? I can do a script that launch "on ajax complete", but I don't know how to manage the anchor in the url.
$.ajax has a complete() callback that you can put code into. you can run location.hash = yourAnchorHash.
You could use jQuery's complete or success callback depending on whether you only want your code to fire when the call is successful or always when the call is complete.
$.ajax({
type: "POST",
url: "yourURL",
contentType: "application/json; charset=utf-8",
data: yourData,
async: true,
success: function (msg) {
//get stuff done when ajax call is successful
},
complete: function()
{
//get stuff done when ajax call is complete
}
});

Multiple AJAX requests in jQuery

I have a function that pulls data from two locations and places the returned content on a modal dialog that is displayed to the user.
Both requests are asynchronous because they're cross-domain. The problem lies in that I don't want to display the modal until both requests have finished loading. How can I check to make sure both requests have finished before loading the modal?
I have tried placing the openModal functions in the success handler of the second request and that works when the first requests finishes loading before the second request, but sometimes this isn't the case.
Here's a copy of my code:
function loadData(id) {
$.ajax({
type: 'GET',
url: 'https://someurl.com/v1.0/controller1/' + id,
dataType: 'jsonp',
success: function(data) {
// Do some stuff to the data
}
});
$.ajax({
type: 'GET',
url: 'https://someurl.com/v1.0/controller2/' + id,
dataType: 'jsonp',
success: function(data) {
// Do some stuff to the data
openModal();
}
});
}
function openModal() {
// Open the modal
}
Check out the new version of jQuery -- 1.5. It has support for exactly your problem, you can check out this blog post for the solution of your problem: http://www.erichynds.com/jquery/using-deferreds-in-jquery/
You could put the one of the ajax requests inside the success callback of the other request, but that wouldn't be as efficient as having them both request at the same time. Then you'd just have to put the openModal call inside the success callback of the inner ajax request. Not optimal, it would be a quick and easy fix if this solution would work for you until a better option is found.
I'm going to keep thinking on this one...
$.when(
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "moon",
tagmode: "any",
format: "json"
}),
$.getJSON("http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?", {
tags: "bird",
tagmode: "any",
format: "json"
})).then(function (res1, res2) {
});

Categories

Resources