0

How to Send Ajax Request in specific time and only that particular event

I m User Time Interval But it’s not Working.

i want get data in request 1 for use in request 2 but it get null data in request 2

setInterval()

it's not Working for me.

I want To send Request 2 After the some time of Request 1

Request 1:-

$(document).on("change", ".supplyItem", function (event) {

        var id = $(this).attr("data-id");
        var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
        var hospital = $("#hospital").val();
        var physician = $("#physician").val();
        var category = $("#category").val();
        var manufacturer = $("#manufacturer").val();
        var project = $("#project").val();

        if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
            $.ajax({
                url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
                data: {
                    supplyItem: supplyItem,
                    hospital: hospital,
                    project: project,
                },

                success: function (data) {

                    console.log(id);
                    if (data.status) {
                        var html_data = '';
                        var item = data.value;
                        console.log(item);


                        $('.hospitalPart[data-id=' + id + ']').val(item.hospitalNumber);
                        $('.mfgPartNumber[data-id=' + id + ']').val(item.mfgPartNumber);

                        // $('.mfgPartNumber[data-id='+id+']').text('something');
                    } else {
                        $('.hospitalPart[data-id=' + id + ']').val('');
                        $('.mfgPartNumber[data-id=' + id + ']').val('');

                    }

                    $('.quantity[data-id=' + id + ']').val('');
                    $('.purchaseType[data-id=' + id + ']').val('');
                    $('#serial-text' + id).val('');
                    $('#serial-drop' + id).val('');

                    $('#serial-drop' + id).empty();


                }

            });
        }

    });

Request 2:-

 $(document).on('change', '.supplyItem', function (event) {
        var timer, delay = 2000;
        var id = $(this).attr("data-id");
        var client = $("#hospital").val();

        timer = setInterval(function(){

            var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
            var hospitalPart = $(".hospitalPart[data-id=" + id + "]").val();
            var mfgPartNumber = $(".mfgPartNumber[data-id=" + id + "]").val();
            alert(supplyItem);
            alert(hospitalPart);
            alert(mfgPartNumber);

            $.ajax({
                url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
                data: {
                    supplyItem: supplyItem,
                    hospitalPart: hospitalPart,
                    mfgPartNumber: mfgPartNumber,
                    client: client,

                },

                success: function (data) {

                    if (data.status) {
                        var html_data = '';

                        var check = data.value;

                        if (check == 'True') {
                            html_data += "<option value=''>Purchase Type</option><option value='Bulk'>Bulk</option><option value='Consignment'>Consignment</option>";
                            $('.purchaseType[data-id=' + id + ']').html(html_data);

                        } else {
                            html_data += "<option value=''>Purchase Type</option><option value='Consignment'>Consignment</option>";

                            $('.purchaseType[data-id=' + id + ']').html(html_data);

                        }
                    }


                }


            });
            }, delay);
        clearInterval(timer);
    });
Ravi Thummar
  • 5,048
  • 1
  • 11
  • 22
  • If you need to fire request 2 after request 1 finishes, you should look into promises. Javascript is asynchronous, so your approach is likely to be flakey on slow network connections. – Joe Dec 11 '17 at 11:13
  • This is an [XY Problem](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). You dont want to send the second request after an interval, you want to send request 2 after receiving a response from request 1, dont you? – Jamiec Dec 11 '17 at 11:23
  • Try to call the second request with the interval in the `success:` block of the first request !! – Maraboc Dec 11 '17 at 11:28
  • @Maraboc I suspect the interval is only to try to wait for the first request. See he clears the interval right after – Jamiec Dec 11 '17 at 11:33
  • @Jamiec I see, but it depends on the needs of the asker :) – Maraboc Dec 11 '17 at 11:37
  • yeah Right @Maraboc – Ravi Thummar Dec 11 '17 at 11:44
  • @punit Is it working in the `success:` block ?? – Maraboc Dec 11 '17 at 11:48
  • no @Maraboc its not working. – Ravi Thummar Dec 11 '17 at 11:49
  • @Joe, JS is not Asynchronous, that is why you want to use AJAX, which stands for Asynchronous Javascript and Extensible Markup. And the async effect of it is an illusion, JS is still only single threaded, the only work around is to use BackgroundWorkers to give it true async properties. – Kickass Dec 11 '17 at 12:09
  • Please try my solution and let me know if you have any further problems. Im pretty sure you're not getting the expected response from your second call because you're waiting an arbitrary amount of time for call1 to have completed. – Jamiec Dec 11 '17 at 12:36
  • BTW: you can declare 'async: false|true' in the AJAX call - default true. Just read http://api.jquery.com/jquery.ajax/#success – Kickass Dec 11 '17 at 12:40
  • @JuanTheron the pure fact you even suggest `async:false` shows you shouldnt be answering jQuery questions. – Jamiec Dec 11 '17 at 13:20
  • Jamiec you are starting to irritate me....Do you not know what BTW stands for? It was a 'By the way'!, not a suggestion – Kickass Dec 11 '17 at 13:53
  • @JuanTheron BTW when you suggest something in a comment, its a suggestion even if you tag "BTW" in front of it.. – Jamiec Dec 11 '17 at 14:57

3 Answers3

0

You can move Request 2 into a function and this JS code will call the Request2 function after given interval of time (milliseconds), I have set it to 5 seconds for now.

setInterval(function () { Request2(); }, 5000);

function Request2(){
console.log("Request 2 called");
//add request 2 code here
}
nicedev80
  • 1,575
  • 1
  • 13
  • 17
-1

Ok first though: Instead of using setInterval and then clearing the interval after it has run a single time, why not just use

setTimeout(function, delay);

Then personally I prefer to use XMLHttpRequest instead of Jquery AJAX, Jquery uses XMLHttpRequest at its base anyway,I just prefer it so I dont have to use Jquery, but if your already using Jquery in your site then it should be no more heavy. Here is a quick example of XMLHttpRequest so u can use it if you prefer.

var xhr = new XMLHttpRequest();
  xhr.open("POST", 'URL::to("admin/repcasetracker/getdevicedata")', true);
  xhr.setRequestHeader("Content-Type", "application/json charset=utf8");
  xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
      // content is loaded...
      if (xhr.responseText) {
        //Some code to run after the server responds and it was successfull
      }
    }
  };
  xhr.send(JSON.stringify({test:'test'})); //This is the data you are handing to the server

Notice the use of xhr.responseText, JQuery uses the same variable and this is usually the response from the server. One sure way to know is use your browser's debugging engine (F12 on Chrome and Firefox, have no idea on other browsers) to inspect the variables, it is very easy to ascertain the correct variable to use.

And then one last thought: I see you are not declaring the content-type and not JSON.stringify'ing() your data when you send it to the server.

Best way to debug a situation like this is 'proccess of elimation' so find out if the server is receiving the data then if the server is proccessing the data correctly and then check if the server is sending the data correctly. If you are using Nginx use the /var/log/nginx/error.log to see if it throws any errors ( tip: tail -f /var/log/nginx/error.log | Apache uses /var/log/http/error.log on most distros ) and if you are using .NET just debug it in Visual Studio.

And read up on the Jquery success event there is 2 more arguments that gets passed - String textStatus and jqXHR jqXHR http://api.jquery.com/jquery.ajax/

So to summarize: Make sure to declare the dataType: 'json'

Use the correct variable, should be responseText

when passing the server data and using 'json' make sure to JSON.stringify() it

And I don't quite see why you want to use setTimeout in the first place. If you are simply waiting for the server to respond then using any type of delay will be a terrible idea, instead use the events that gets fired after the server responds.

So in Jquery that is success: function() {} and error: function() {} and in XMLHttpRequest its the xhr.onreadystatechange = function () { }

Kickass
  • 1,114
  • 9
  • 16
  • I dont understand the point of this answer. Its basically 50% a rant on why to use vanilla ajax instead of jQuery (which is totally a waste of time. OP is already using jQuery!) 45% some help on Unix debugging (without knowing if the OP is even writing any server side code) and at most 5% actually trying to answer the question. – Jamiec Dec 11 '17 at 12:07
  • @Jamiec I'm trying to help the OP without writing his code for him. If you read closely you will see his main problem is not getting any data back in 'response 2' which I believe is the result of using data.value which I addressed so I think this is as complete an answer as can be expected without knowing the server-side code – Kickass Dec 11 '17 at 12:13
  • I get that if the OP has shown no effort - but helping correct code is kinda the point of SO (again, assuming they have shown effort - which this poster has) – Jamiec Dec 11 '17 at 12:15
  • I hear what you are saying, but the XMLHttpRequest uses the same concept as AJAX so it is still relevant. Then obviously the OP did not check the server side for exceptions otherwise he would have mentioned it, so giving a tip on how to debug different servers is also relevant – Kickass Dec 11 '17 at 12:20
-1

jQuery's $.ajax method returns a promise, which is passed the result of the server-side call. You can chain these calls together so that you can build the result of multiple ajax calls. When you use it this way you do away with success callbacks as they are no longer necessary.

Applied to your code it might looks something like this:

$(document).on("change", ".supplyItem", function (event) {

        var id = $(this).attr("data-id");
        var supplyItem = $(".supplyItem[data-id=" + id + "]").val();
        var hospital = $("#hospital").val();
        var physician = $("#physician").val();
        var category = $("#category").val();
        var manufacturer = $("#manufacturer").val();
        var project = $("#project").val();

        if (hospital != "" && physician != "" && category != "" && manufacturer != "" && project != "") {
            $.ajax({
                url: "{{ URL::to('admin/repcasetracker/getitemfile')}}",
                data: {
                    supplyItem: supplyItem,
                    hospital: hospital,
                    project: project,
                })
                .then(function(data1){
                   // process result of call1 and make call2
                   var item = data1.value;
                   return $.ajax({
                      url: "{{ URL::to('admin/repcasetracker/getdevicedata')}}",
                      data: {
                        supplyItem: supplyItem,
                        hospitalPart: value.hospitalPart, // note using result from 1 directly
                        mfgPartNumber: value.mfgPartNumber,
                        client: hospital 
                     }
                   });
                })
                .then(function(data2){
                    // process result of call2
                });
        };
    });

The point here is that you don't need to stash the result of call1 into some elements and re-read them before making call2, and trying to wait enough time before making call2. You just chain it all together with then.

Jamiec
  • 133,658
  • 13
  • 134
  • 193
  • I believe you improved on the setInterval but did not address the problem properly. The OP's problem was not getting a result back in the second request. So you have improved the coding but not addressed the problem. – Kickass Dec 11 '17 at 12:25
  • @JuanTheron Im willing to bet the reason was the input to the second call was not yet ready (after an arbitrary 2 seconds). This *will* fix that problem. Nice revenge downvote though! – Jamiec Dec 11 '17 at 12:26
  • I agree the 2000ms is completely arbitrary and using it that way is not a good solution but the point is you did not solve anything. I will say this: Excellent solution to the setInterval – Kickass Dec 11 '17 at 12:29
  • @JuanTheron buuut you stil revenge downvoted. Great participation. – Jamiec Dec 11 '17 at 12:32
  • I downvoted you because you did not answer the question. I'd be laying if I said it didn't feel good. – Kickass Dec 11 '17 at 12:33
  • @JuanTheron You have zero idea if this solves the question. I am 100% sure your answer cannot possibly (because you didnt give one). – Jamiec Dec 11 '17 at 12:34
  • Anyway You simply posted some code ( nice looking code but still ), I gave the OP the tools to figure the problem out himself – Kickass Dec 11 '17 at 12:35