Debugging Ajax code with Firebug - ajax

I've a couple of problems debugging code returned in an Ajax call - specifically, a function returned in json (errors don't get trapped in Firefox) - up to the point where I started debugging these problems in Internet Explorer (I think it's a firefox related problem, as Venkman doesn't detects those errors either) Do you know of any way to debug code returned in json from an Ajax call?
EDITED 03/04/2009 15:05
Thanks to all for your responses, but I think I didn't explain myself well enough. I know enough of Firebug to do basic debugging, but my problem happens when I fetch some code in an Ajax call that has a problem with it. Let's say we have the following HTML file (you'll need prototype in the same folder to make it work correctly):
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<script type="text/javascript" src="prototype.js"></script>
</head>
<body>
<script>
function ajaxErrorTest()
{
new Ajax.Request('data.json', {
'method': 'get',
'onSuccess': function(data){
if(data.responseJSON.func)
data.responseJSON.func();}});
}
</script>
<input type="button" value="test" onclick="ajaxErrorTest();" />
</body>
</html>
and then, the contents of the data.json file is this:
{'func':function(){console.log('loaded...');alert('hey');}}
If you load the page in a browser and click the 'Test' button (and everything goes well) you'll get something in the console, and an alert box that says 'hey'. Now change the data.json file to this:
{'func':function(){console.log('loaded...');alerts('hey');}}
...and click the 'Test' button again (no need to reload the page ;-)
You get the console line, but no alert box... and no errors!!! this is the kind of errors I'm trying to debug.

Try clicking on the "Console" panel (it's a tab) and enabling it. You will find that any HTTP requests will be caught along with any information that they contain. I use this in order to view any JSON stored in the request as well as any errors (500/404/etc).
Also be aware that you have to enable the console panel on a per-domain basis. There are usually three subtabs: headers, post, and response. I usually use the post/response tabs quite a bit when I'm debugging my AJAX.

You probably want to use the Net tab and filter the requests for XMLHttpRequests (XHR) only.
Additional tips:
don't hesitate to console.dir(yourObject) in your code or directly in the console panel. This will give you the complete state and properties of your object.
check your request/response HTTP headers; sometimes it's just a matter of encoding.
if you don't know what event/user action triggered this XHR call, you can add console.trace() right before your AJAX call. This way you'll get the complete call stack.
Edit:
Code executed in another context
The only way I came up with is surrounding your code with an (ugly) try/catch.
I guess it's because the code is executed in another javascript context
<script>
function ajaxErrorTest()
{
new Ajax.Request('data.json', {
'method': 'get',
'onSuccess': function(data){
try{
if(data.responseJSON.func)
data.responseJSON.func();}});
} catch (err) {
console.dir(err);
}
}
</script>
This code gives a detailed error message:
ReferenceError: alerts is not defined
I really doubt changing the execution context will solve the problem.
I don't know how to this with prototype, but with jquery, it can be done easily:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});

I'm not sure this issue involves the actual JSON that is retrieved. Can you try throwing an error directly in your onSuccess handler and see if it appears in the Firebug console? Something like this:
onSuccess: function() { alerts('hey'); }
If this is the case, then this issue should be fixed in Firebug 1.7.

I would use a combination of the net/console tabs in firefox.
Copy the json results from the Net Tab in Firefox.
Then paste the results into a variable in the console and try executing the offending function.
In this case, I pasted this:
var x = {'func':function(){console.log('loaded...');alerts('hey');}}
x.func();
When I run this, firebug gives me this error.
ReferenceError: alerts is not defined

As others have mentioned, view the JSON/Javascript returned by expanding the AJAX URL in the Console tab.
Then if you copy that to the run/eval panel of the Console tab (there's an up/down arrow in the bottom right, clicking the up will change it into a textarea on the right hand side, clicking down gives a single line running along the bottom).
If your Ajax call returns: function(){alert("hello")}
Then you can use something like the following:
x = eval('function(){alert("hello")}')
x();
This will allow you to execute the returned ajax.
To debug with breakpoints use the HTML view to create a tag (using Firebug's HTML view) and then simply paste the code into a function within this tag. You can then set breakpoints and fire it by calling the previous function from the run'/eval panel.
If this works fine then clearly there's a bug outside of your control, but you could simply workaround that by sending the json back as text/plain, assigning it to a variable and then evaluating it.

This one is simple, i allways use FIDDLER
to debug my ajax calls.
Fiddler is a Web Debugging Proxy which
logs all HTTP(S) traffic between your
computer and the Internet. Fiddler
allows you to inspect all HTTP(S)
traffic, set breakpoints, and "fiddle"
with incoming or outgoing data.
Fiddler includes a powerful
event-based scripting subsystem, and
can be extended using any .NET
language.

I use an HTTP Proxy Debugger called fiddler which has always worked fine for debugging my AJAX problems. It captures all HTTP requests and responses for you to view. Its freely available from http://www.fiddlertool.com/

the error you are trying to debug is pretty visible on native firefox console. it is: "tools" - "error console"
of course, you see it after it ocurrs but with an wrong line number (infinite resemblance)

I know the specific issue mentioned in the post is for firefox. I landed on this page when googling for generally how to debug java script that comes from an AJAX call and I'm sure a lot of others will.
I my case I was returning some HTML that had a script tag in it, if there was for example, a sytax error in the javascript that came down from the AJAX request in firebug you will get no exception, or errors. The AJAX content will just not render.
In the google chrome built debugger you'll get the error that has been raised, but you'll not be able to step through the code. If you wan't to step though then you'll need to make a dummy page for that.
Thats the best I've been able to get it so far.

When you use a library or javascript code that you have loaded it dynamically, you can use the phrase //# sourceURL=foo.js at the beginning of your javascript code that foo.js is the name that assign it. debugger will show it with that name.
This is true in chrome that I think in firebug.
In this case you can place a breakpoint in the dynamically loaded javascript ( or json ) code.

Use "debbuger;" as line of code where you wanna stop execution. In this way the loaded source code will be available in the source section of your debbuger. I know for sure it works on chrome.

Related

ajax returns page source, not the message

All the answers I saw here or elsewhere on Google were with jquery. This is not jquery.
I send an ajax string to a php file.
The php, among other things, formulates a message string which I echo
back to the client.
The returned string is put up in the client as an alert.
The form is then reset.
The problem is that when I do this it puts up as much of the page source that the alert can handle. If I open developer tools to look at the return, it puts the message up correctly, not the page source. Here is the return snippet in my ajax:
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
alert(ajaxRequest.responseText);
document.getElementById("thisForm").reset();
}
}
The php file does a simple echo of a text string.
What is it about developer tools that makes this run correctly and why doesn't it print out the message in the alert when developer tools is not there?
When I run the backend php by itself, with or without developer tools, it displays the message properly.
Does anyone have any ideas?
More information: I tried to replace the alert and reset with a
display.innerHTML=ajaxRequest.responseText where display is a javascript object formed from getElementById("ajaxReturn") of a "div id="ajaxReturn". It didn't work. When I tried developer tools, it showed the network response text as being the page source.
I also added && this.status == 200 to the if statement. No change.
The problem is solved. I am not deleting this because it might help some other poster who runs into the same problem. I launched the AJAX with an onclick to a javascript function called ajaxFunction(). The html entity containing the onclick had an href="#" in it. Removing that href solved the problem.
I had the exact same issue and my cause was related to having an extra slash in my URL.
Lets say my URL was:
https://example.com/index.php
I had a wrong link as follows:
https://example.com/index.php/
On both instances my server loads the page,
But the Ajax shows the page source as response for:
https://example.com/index.php/
But works fine for:
https://example.com/index.php
The ajax is essentially posting to index.php/ajaxpage.php which then responds with whats on index.php instead of whats on ajaxpage.php

How to solve No 'Access-Control-Allow-Origin' in polymer-project?

I am exploring Polymer-project 1.0 and the task is to get the JSON and print output repeatedly.
But no matter what I tried, the error below is coming. I even tried with Github pages, but this also gives me same error response in terminal.
Error
XMLHttpRequest cannot load https://ajax.googleapis.com/ajax/services/search/news?v=1.0&rsz=8&pz=1&cf=all&ned=in&hl=en&topic=tc. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://rajasimon.github.io' is therefore not allowed access.
Not into theming and designing the material design. All I want is for the functionality to work first. So I wrote below code:
index.html
<iron-ajax
auto
url="https://ajax.googleapis.com/ajax/services/search/news?v=1.0&rsz=8&pz=1&cf=all&ned=in&hl=en&topic=tc"
handle-as="json"
last-response="{{ajaxResponse}}"></iron-ajax>
<template is="dom-repeat" items="{{ajaxResponse.responseData.results}}">
<paper-material elevation="1" class="paper-font-body2">
<h1>{{item.title}}</h1>
<iron-image src="[[item.image.url]]" style="width:800px; height:450px; background-color: lightgray;" sizing="cover" preload fade></iron-image>
<p>{{item.content}}</p>
</paper-material>
</template>
Enabling
For debugging I installed Google Chrome app named Allow-Control-Allow-Origin: *. Then the above code started working.
Even if I tried with iron-ajax demo will give the same result. What's happening here? Am I the one person receiving this error in the universe?
You can solve this problem using byutv-jsonp. It a Polymer 1.0+ element that allows for making JSONP requests. The Google API you are using supports JSONP. I have tested the code below and get back the proper response.
<byutv-jsonp
auto
url="https://ajax.googleapis.com/ajax/services/search/news"
params='{"v":"1.0","rsz":"8","pz":"1","cf":"all","ned":"in","hl":"en","topic":"tc"}'
last-response="{{lastResponse}}"
last-error="{{lastError}}"
debounce-duration="300"></byutv-jsonp>
<template is="dom-repeat" items="{{lastResponse.responseData.results}}">
<paper-material elevation="1" class="paper-font-body2">
<h1>[[item.title]]</h1>
<iron-image src="[[item.image.url]]" style="width:800px; height:450px; background-color: lightgray;" sizing="cover" preload fade></iron-image>
<p>[[item.content]]</p>
</paper-material>
</template>
It is important to add the query parameters to the params attribute instead of the url attribute with the current version (1.2.0) of byutv-jsonp.
You will need to use jsonp -- more info about it here https://en.wikipedia.org/wiki/JSONP
Demo
https://jsfiddle.net/1v2z799o/
Code
$.ajax({
url: "https://ajax.googleapis.com/ajax/services/search/news?v=1.0&rsz=8&pz=1&cf=all&ned=in&hl=en&topic=tc",
jsonp: "callback",
// Tell jQuery we're expecting JSONP
dataType: "jsonp",
// Work with the response
success: function( response ) {
console.log(response); // server response
}
});
Result
However i dont see an option in Polymer iron-ajax handleAs for jsonp but try the available options
https://elements.polymer-project.org/elements/iron-ajax
I had a look around and there is byutv-jsonp
The byutv-jsonp element () exposes network request
functionality. It is a Polymer v1.0+ element that facilitates making
JSONP requests. It uses Polymer behaviors (Byutv.behaviors.Jsonp). It
is patterned after Polymer's iron-ajax element (). It has
been tested using unit tests. It is part of the BYUtv Elements group
of elements.
https://github.com/coderfin/byutv-jsonp
I tried JSONPbut it did not work for me. Then I ran my Chrome browser in web security disabled mode and Access-Control-Allow-Origin issue for 3rd party URL being invoked via AJAX requests got resolved for me.
Please note, this is a temporary fix in development environment and it will only work for Chrome.
Create a shortcut of Google Chrome on your desktop or somewhere else
Right click on it > Select Properties
Change target like this:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security
When you run Chrome you will receive a warning that it is running in unsafe mode, but you can ignore it for the time being and continue with development.
Hope this works!
UPDATE: Commands you can try for OSX and Linux/Ubuntu
Being a Windows user I am not very sure about the solutions but but you can give it a try.
Linux:
$ google-chrome --disable-web-security
Command line approach:
chromium-browser --disable-web-security
OSX:
$ open -a Google\ Chrome --args --disable-web-security
To access local files like AJAX or JSON, you can use this flag too. Again, this is strictly for dev purpose.
-–allow-file-access-from-files
NB: You should be careful if you are browsing internet with web security disabled. This will make your PC more vulnerable to attacks!
Remember, you need to close all instances of Chrome and its background apps before you run it in --disable-web-secutiry mode.
Let me know if this resolves your issue.

Firefox Ajax post web console summary says 'undefined'

I use Ajax extensively in my JavaScript code. Today I added an Ajax call to a page and nothing happens. The Firefox web console shows a result of "undefined". The exact log entry is:
[11:15:50.733] POST http://mastersw.com/theme/test9.php [undefined 78ms]
(I had to modify the URL to satisfy the editor rules here.)
When I click on the log entry, I see a message dialog with no response. Everything else is correct in the message.
I have checked the Apache logs and there is no sign that the post request got to the server. I use my own JavaScript library Ajax routines. They work everywhere else. I have double checked that the script (test9.php) exists.
I cannot find any documentation on what Firefox means when they say "undefined". Google search returns millions of hits about other things.
The problem seems to be that Firefox is for some reason not completing the post operation and I cannot figure out why.
Update: The JavaScript function invoking the Ajax call was itself being invoked from the onclick handler of an anchor. When I changed the element to a div it worked.
I don't have any idea why Firefox gave an 'undefined' for the post. Chrome complained about an invalid header "Content-Length". Changing to a div fixed this as well.
You need to cancel the click event
$("a").on("click", function (evt) {
evt.preventDefault();
//ajax call here
});

Blank cache entry after asynchronous JavaScript load in IE8

I'm using Modernizr in one of my projects. I want to test for the existence of placeholder before downloading a polyfill for it. Here's the code I'm using to accomplish this:
yepnope({
test : Modernizr.input.placeholder,
nope : '/js/jquery.placeholder.js',
complete: function(){
$('input, textarea').placeholder();
}
});
I'm experiencing an odd issue with this. It works perfectly when I hit the page without loading any resources from cache, but if I refresh the page, I'm getting an undefined method error for the call to .placeholder().
Looking in the dev tools, an empty jquery.placeholder.js (from the cache) seems to be the culprit. I can verify in Fiddler that the second response is returning a 304, and sending an empty body, which means IE should have the right version in cache, but it is empty somehow. What could cause this behavior?
EDIT: If I add placeholder.js to the head, everything works fine all the time. Just thought I'd point that out.

What does status=canceled for a resource mean in Chrome Developer Tools?

What would cause a page to be canceled? I have a screenshot of the Chrome Developer Tools.
This happens often but not every time. It seems like once some other resources are cached, a page refresh will load the LeftPane.aspx. And what's really odd is this only happens in Google Chrome, not Internet Explorer 8. Any ideas why Chrome would cancel a request?
We fought a similar problem where Chrome was canceling requests to load things within frames or iframes, but only intermittently and it seemed dependent on the computer and/or the speed of the internet connection.
This information is a few months out of date, but I built Chromium from scratch, dug through the source to find all the places where requests could get cancelled, and slapped breakpoints on all of them to debug. From memory, the only places where Chrome will cancel a request:
The DOM element that caused the request to be made got deleted (i.e. an IMG is being loaded, but before the load happened, you deleted the IMG node)
You did something that made loading the data unnecessary. (i.e. you started loading a iframe, then changed the src or overwrite the contents)
There are lots of requests going to the same server, and a network problem on earlier requests showed that subsequent requests weren't going to work (DNS lookup error, earlier (same) request resulted e.g. HTTP 400 error code, etc)
In our case we finally traced it down to one frame trying to append HTML to another frame, that sometimes happened before the destination frame even loaded. Once you touch the contents of an iframe, it can no longer load the resource into it (how would it know where to put it?) so it cancels the request.
status=canceled may happen also on ajax requests on JavaScript events:
<script>
$("#call_ajax").on("click", function(event){
$.ajax({
...
});
});
</script>
<button id="call_ajax">call</button>
The event successfully sends the request, but is is canceled then (but processed by the server). The reason is, the elements submit forms on click events, no matter if you make any ajax requests on the same click event.
To prevent request from being cancelled, JavaScript event.preventDefault(); have to be called:
<script>
$("#call_ajax").on("click", function(event){
event.preventDefault();
$.ajax({
...
});
});
</script>
NB: Make sure you don't have any wrapping form elements.
I had a similar issue where my button with onclick={} was wrapped in a form element. When clicking the button the form is also submitted, and that messed it all up...
Another thing to look out for could be the AdBlock extension, or extensions in general.
But "a lot" of people have AdBlock....
To rule out extension(s) open a new tab in incognito making sure that "allow in incognito is off" for the extention(s) you want to test.
In my case, I found that it is jquery global timeout settings, a jquery plugin setup global timeout to 500ms, so that when the request exceed 500ms, chrome will cancel the request.
You might want to check the "X-Frame-Options" header tag. If its set to SAMEORIGIN or DENY then the iFrame insertion will be canceled by Chrome (and other browsers) per the spec.
Also, note that some browsers support the ALLOW-FROM setting but Chrome does not.
To resolve this, you will need to remove the "X-Frame-Options" header tag. This could leave you open to clickjacking attacks so you will need to decide what the risks are and how to mitigate them.
Here's what happened to me: the server was returning a malformed "Location" header for a 302 redirect.
Chrome failed to tell me this, of course. I opened the page in firefox, and immediately discovered the problem.
Nice to have multiple tools :)
Another place we've encountered the (canceled) status is in a particular TLS certificate misconfiguration. If a site such as https://www.example.com is misconfigured such that the certificate does not include the www. but is valid for https://example.com, chrome will cancel this request and automatically redirect to the latter site. This is not the case for Firefox.
Currently valid example: https://www.pthree.org/
A cancelled request happened to me when redirecting between secure and non-secure pages on separate domains within an iframe. The redirected request showed in dev tools as a "cancelled" request.
I have a page with an iframe containing a form hosted by my payment gateway. When the form in the iframe was submitted, the payment gateway would redirect back to a URL on my server. The redirect recently stopped working and ended up as a "cancelled" request instead.
It seems that Chrome (I was using Windows 7 Chrome 30.0.1599.101) no longer allowed a redirect within the iframe to go to a non-secure page on a separate domain. To fix it, I just made sure any redirected requests in the iframe were always sent to secure URLs.
When I created a simpler test page with only an iframe, there was a warning in the console (which I had previous missed or maybe didn't show up):
[Blocked] The page at https://mydomain.com/Payment/EnterDetails ran insecure content from http://mydomain.com/Payment/Success
The redirect turned into a cancelled request in Chrome on PC, Mac and Android. I don't know if it is specific to my website setup (SagePay Low Profile) or if something has changed in Chrome.
Chrome Version 33.0.1750.154 m consistently cancels image loads if I am using the Mobile Emulation pointed at my localhost; specifically with User Agent spoofing on (vs. just Screen settings).
When I turn User Agent spoofing off; image requests aren't canceled, I see the images.
I still don't understand why; in the former case, where the request is cancelled the Request Headers (CAUTION: Provisional headers are shown) have only
Accept
Cache-Control
Pragma
Referer
User-Agent
In the latter case, all of those plus others like:
Cookie
Connection
Host
Accept-Encoding
Accept-Language
Shrug
I got this error in Chrome when I redirected via JavaScript:
<script>
window.location.href = "devhost:88/somepage";
</script>
As you see I forgot the 'http://'. After I added it, it worked.
Here is another case of request being canceled by chrome, which I just encountered, which is not covered by any of answers up there.
In a nutshell
Self-signed certificate not being trusted on my android phone.
Details
We are in development/debug phase. The url is pointing to a self-signed host. The code is like:
location.href = 'https://some.host.com/some/path'
Chrome just canceled the request silently, leaving no clue for newbie to web development like myself to fix the issue. Once I downloaded and installed the certificate using the android phone the issue is gone.
If you use axios it can help you
// change timeout delay:
instance.defaults.timeout = 2500;
https://github.com/axios/axios#config-order-of-precedence
For my case, I had an anchor with click event like
<a href="" onclick="somemethod($index, hour, $event)">
Inside click event I had some network call, Chrome cancelling the request. The anchor has href with "" means, it reloads the page and the same time it has click event with network call that gets cancelled. Whenever i replace the href with void like
<a href="javascript:void(0)" onclick="somemethod($index, hour, $event)">
The problem went away!
If you make use of some Observable-based HTTP requests like those built-in in Angular (2+), then the HTTP request can be canceled when observable gets canceled (common thing when you're using RxJS 6 switchMap operator to combine the streams). In most cases it's enough to use mergeMap operator instead, if you want the request to complete.
I had faced the same issue, somewhere deep in our code we had this pseudocode:
create an iframe
onload of iframe submit a form
After 2 seconds, remove the iframe
thus, when the server takes more than 2 seconds to respond the iframe to which the server was writing the response to, was removed, but the response was still to be written , but there was no iframe to write , thus chrome cancelled the request, thus to avoid this I made sure that the iframe is removed only after the response is over, or you can change the target to "_blank".
Thus one of the reason is:
when the resource(iframe in my case) that you are writing something in, is removed or deleted before you stop writing to it, the request will be cancelled
I have embedded all types of font as well as woff, woff2, ttf when I embed a web font in style sheet. Recently I noticed that Chrome cancels request to ttf and woff when woff2 is present. I use Chrome version 66.0.3359.181 right now but I am not sure when Chrome started canceling of extra font types.
We had this problem having tag <button> in the form, that was supposed to send ajax request from js. But this request was canceled, due to browser, that sends form automatically on any click on button inside the form.
So if you realy want to use button instead of regular div or span on the page, and you want to send form throw js - you should setup a listener with preventDefault function.
e.g.
$('button').on('click', function(e){
e.preventDefault();
//do ajax
$.ajax({
...
});
})
I had the exact same thing with two CSS files that were stored in another folder outside my main css folder. I'm using Expression Engine and found that the issue was in the rules in my htaccess file. I just added the folder to one of my conditions and it fixed it. Here's an example:
RewriteCond %{REQUEST_URI} !(images|css|js|new_folder|favicon.ico)
So it might be worth you checking your htaccess file for any potential conflicts
happened to me the same when calling a. js file with $. ajax, and make an ajax request, what I did was call normally.
In my case the code to show e-mail client window caused Chrome to stop loading images:
document.location.href = mailToLink;
moving it to $(window).load(function () {...}) instead of $(function () {...}) helped.
In can this helps anybody I came across the cancelled status when I left out the return false; in the form submit. This caused the ajax send to be immediately followed by the submit action, which overwrote the current page. The code is shown below, with the important return false at the end.
$('form').submit(function() {
$.validator.unobtrusive.parse($('form'));
var data = $('form').serialize();
data.__RequestVerificationToken = $('input[name=__RequestVerificationToken]').val();
if ($('form').valid()) {
$.ajax({
url: this.action,
type: 'POST',
data: data,
success: submitSuccess,
fail: submitFailed
});
}
return false; //needed to stop default form submit action
});
Hope that helps someone.
For anyone coming from LoopbackJS and attempting to use the custom stream method like provided in their chart example. I was getting this error using a PersistedModel, switching to a basic Model fixed my issue of the eventsource status cancelling out.
Again, this is specifically for the loopback api. And since this is a top answer and top on google i figured i'de throw this in the mix of answers.
For me 'canceled' status was because the file did not exist. Strange why chrome does not show 404.
It was as simple as an incorrect path for me. I would suggest the first step in debugging would be to see if you can load the file independently of ajax etc.
The requests might have been blocked by a tracking protection plugin.
It happened to me when loading 300 images as background images. I'm guessing once first one timed out, it cancelled all the rest, or reached max concurrent request. need to implement a 5-at-a-time
One the reasons could be that the XMLHttpRequest.abort() was called somewhere in the code, in this case, the request will have the cancelled status in the Chrome Developer tools Network tab.
In my case, it started coming after chrome 76 update.
Due to some issue in my JS code, window.location was getting updated multiple times which resulted in canceling previous request.
Although the issue was present from before, chrome started cancelling request after update to version 76.
I had the same issue when updating a record. Inside the save() i was prepping the rawdata taken from the form to match the database format (doing a lot of mapping of enums values, etc), and this intermittently cancels the put request. i resolved it by taking out the data prepping from the save() and creating a dedicated dataPrep() method out of it. I turned this dataPrep into async and await all the memory intensive data conversion. I then return the prepped data to the save() method that i could use in the http put client. I made sure i await on dataPrep() before calling the put method:
await dataToUpdate = await dataPrep();
http.put(apiUrl, dataToUpdate);
This solved the intermittent cancelling of request.

Resources