this question might duplicate but I need some help to fix the code.
Scenario: Once the submit button is clicked, ajax will send the form data to server . And based on the form data (variables and update-speed), perform polling to get the response data.
Current bottleneck: Since the speed and variables is declared globally, the correct response will show only first time the submit is clicked and completed. Otherwise for the setTimeout polling for doPoll, it will show null value since the form data is not captured.
Desired Outcome: Once user submit the click button, pull the data periodically based on user'update speed value and save all the response in key-value array. The response will used to draw Chart.js.
Any suggestion and thanks.
Code:
$('#submit-button').click(function(e){
var speed = $('#update-speed-input').val();
var variables = $('#variables-select-input').val();
function doPoll(speed,variables){
$.post("{{ route('getFilterUnitData') }}", {
speed: speed,
variables: variables,
}, function(response) {
console.log(response);
setTimeout(doPoll,speed);
});
}
$.ajax({
url: "{{ route('getFilterUnitData') }}",
method: 'post',
data: {
speed: speed,
variables: variables
}
,
success: function(response){
console.log(count(response));
},
error: function(result) {
console.log(result);
},
complete: setTimeout(doPoll(speed,variables), speed)
});
});
Did you try assigning the values to "window" object? like to window.speed and window.variables
The speed and variables is inside a function scope and not global.
Related
I have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});
I'm trying to retrieve the data I submitted to an asynchronous ajax request should the back-end fail in some way. The data in 'myJSONData' is actually pulled off a queue (array) in memory and I need to put it back into the queue if any kind of error occurs.
e.g.
var myJSONData = {"parm1":"value1","parm2":"value"};
$.ajax({
type: "POST",
url: "/postData.ajax",
dataType: "json",
data: myJSONData,
success: function(jsonReply) {
// I need to refer to the posted data here (i.e. myJSONData)
},
error: function(xhr,ajaxOptions,thrownError) {
// I need to refer to the posted data here (i.e. myJSONData)
}
});
My code fires off a number of calls at various times, the trouble is that if I refer to myJSONData within the success or error blocks it contains the most recent value of that variable in memory, and not what was in the variable at the time of the ajax call.
Is there some other way to access the data associated with the particular instance of ajax call - something like $.ajax.data ?
You should be able to access it in your success and error functions :
success: function(jsonReply) {
var p1 = myJSONData.param1;
}
I have been working on this for a while and posted several related topics about it, but this is slightly different question. I have the following AJAX code with some html forms below it with in #container and .myselect is the class of a drop-down box. When I change the value in the box I want to be able to then use that value on other fields below the select. The AJAX code kinda works in that the alert shows the right value when changed but as you can see I have tried lots of success functions but no luck. The closest is
$('#reloadtest').html(data); which will show the value in my PHP and every time I change the value from then on it will change alot, but it reloads the page within the container.
Basically I want to know how I can reload the data but not the whole html/page so I can use the value of the drop down in my PHP.
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
type: "POST",
data: { orderidType : orderidVal },
success: function(data) {
//$('#container').reload('#container', function() {});
//$('#quoteselect').reload('#quoteselect', function() {});
//$('#container').load('orders.php #container', function() {});
//$('#quoteselect').load('orders.php #quoteselect', function() {});
//$('#testreload').reload('#testreload', function() {});
//location.href = "test2.php"
$('#reloadtest').html(data); //this allows me to use the variable but reloads the whole page within the page
}
})
});
});
If you are doing an ajax-request you have to allocate an URL where to send the request.
If you don't Request anything jQuery reloads the page. As you can see here in the jquery-api-docu the URL is the very first and most important parameter of the request.
$.ajax({
url: "/url/to/the/php/script.php",
success: function(data){
//do something ... with data parameter
}
});
would be the simple way of using ajax-request with javascript.
use two divs - one in which you can put ajax response and in other the remaining HTML code
it reloads your page because you have not specified what page to request.
use the code below and replace /path/to/script to your actual script path
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
cache: false,
async: true,
type: "POST",
url: '/path/to/script',
data: { 'orderidType' : orderidVal },
success: function(data) {
$('#reloadtest').html(data);
}
});
});
});
I would like to implement the AutoSave functionality for my site.
I mean, I would want all the fields which are edited by the user throughout the site should be autosaved without any button clicks. So user can keep editing.
[site designed with: CodeIgniter and JQuery].
This feature, I am implementing as follows.
1.Created a Queue data structure in javascript and to which I am pushing all the changes made by user. So this is like an object holding all the user changes.
2.Then wrote a function to save the contents of this Queue to the database.
function start(){
var changeData = dq.get(); //getting the data from Queue
while(changeData !== undefined){
$.ajax({
type: 'POST',
url: '/ci/ajax/insert/',
data: {changeData},
success: function(data, status, xml){
alert('succefully inserted data -- '+data);
}
});
changeData = dq.get();
}
setTimeout(function(){ start(); }, 5000);
};
start();
Here I am setting the interval as 5 sec.
The problem is that, I am making two or more changes within 5 sec, but, only the first change is getting updated. But I am getting the alert 2 or more times depending on changes I made.
Where I am going wrong?
Also suggest me the better ways of implementing the autosave feature.
Thanks!
You should define the setTimeout in the success method it would be great because when your first request will be completed then generate the second request otherwise if you will not wait for the server response and sending the no. of requests it be increase the load on your server
function start(){
var changeData = dq.get(); //getting the data from Queue
while(changeData !== undefined){
$.ajax({
type: 'POST',
url: '/ci/ajax/insert/',
data: {changeData},
success: function(data, status, xml){
setTimeout(function(){ start(); }, 5000);// defines when first request is accomplished
alert('succefully inserted data -- '+data);
}
});
changeData = dq.get();
}
};
start();
I have the following code:
$.ajax({
cache: false,
url: "/Administration/" + entity + "s/Update",
data: { pk: pk, rk: rk, fld: type, val: val },
success: function () {
disableLoadingIcon();
if (idArr.substr(0, 8) == 'Position') {
location.reload();
}
}
});
When a user changes some data the code updates the database. There is code that comes before this that picks the data values and it all works good.
When the user changes the Position column the database gets changed and I wanted to trigger a refresh of the screen (it's a report screen sorted by position). The refresh works but it seems like it is out of sync. I have the location.reload() in the success area but is it possible that is getting run before the Ajax has completed?
Is it possible that this kind of refresh is taking place before the database has been properly updated? When I do another refresh of the page manually from the browser the data always appears in the correct order.
Your document is cached. You shouold use
location.reload(true)
to realod with clear cache.
AJAX is asynchronous by default. Once the call is issued, the rest of your code will continue executing. If the value of location gets changed before the ajax call returns its data, the success function will be using the current-at-the-time-it-executes value of location, which is now something different than what it was when the ajax call started.
The success code will not run until the ajax call returns, so that's not the problem. but you're depending on location not being changed between the time you start the ajax stuff and the time it completes.
there is a API in jquery ajaxComplete. whenever a ajax call will be completed this will be invoked.
$.ajaxComplete(function(){
//do something
});
reference : http://api.jquery.com/ajaxComplete/
Whatever you write inside the success handler will be executed only after the completion of the ajax request you made to the server page. so you can load the updated content in that handler.you can use a parameter to accept the response from your success function and check whether your transaction is success or not.
From your server page, after making the database update,you can return true or false.
$.ajax({
cache: false,
url: "/Administration/" + entity + "s/Update",
data: { pk: pk, rk: rk, fld: type, val: val },
success: function (data) {
// This will be excuted only after you receive a response from your server page
if(data=="true") //db updated properly
{
disableLoadingIcon();
if (idArr.substr(0, 8) == 'Position') {
location.reload();
}
}
else
{
alert("Error in updating the data");
}
}
});