fetch and http does not get complete file. nativescript iOS - nativescript

Nativescript has two functions for making http requests fetch or the function http. I use those two functions to get the string of a site (response with the html) for IOS.
The problem is that it returns some of the response but it does not return all of the response for IOS. Meaning it only returns half the file for an http request.
For example:
http.getString("https://slashdot.org").then(function (html) {
console.log(html)
}), function (error) {
console.log("Error: " + error)
}
returns some of the response (html) but then it stops:
var e = document.createElement('script');
e.type = 'text/javascript';
e.id = 'janrainAuthWidget';
if (doc
Those are the last lines of the response before it returns at "if (doc". The last line should of been </html>. So http (and I also tried fetch) does not return the whole file.
I need to get a response for the whole file for my project to work.
What do I need to do so that http or fetch works? Is there some hidden timeout that gets activated. Or should I use CocoaPods and if I should use CocoaPods how?

The same code at my side is returning the whole HTML content
result from the redirect page
JS: <!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML 2.0//EN">
JS: <html><head>
JS: <title>302 Found</title>
JS: </head><body>
JS: <h1>Found</h1>
JS: <p>The document has moved here.</p>
JS: </body></html>
Even the redirect link is returing all the HTML needed so I guess it problem with your local setup or connectivity.
JS: $(document).ready(function () {
JS: function checkCloseAd(){
JS: var adon = $('div.ad-on');
JS: if(adon){
JS: var closead = adon.find('.close-ad');
JS: if(!closead || closead.length === 0){
JS: adon.prepend('<div class="close-ad"><span>Close Ad</span></div>');
JS: }
JS: }
JS: }
JS: function footerFixer(){
JS: var footer = $('#home .stage-center #footer');
JS: if(footer.length){
JS: if(footer.length > 1){
JS: $('#home .stage-center #footer').eq(1).remove();
JS: }
JS: if(footerHtml != $(footer).html()) footerHtml = $(footer).html();
JS: }else{
JS: $('#home .stage-center div').first().append('<div id="footer">'+footerHtml+'</div>');
JS: }
JS: }
JS: $('#river_bottom').prepend('<div class="close-ad"><span>Close Ad</span></div>');
JS: $('body').on('click','.close-ad', function(){
JS: $(this).hide();
JS: $('#river_bottom,#story_slot2').toggleClass('ad-on');
JS: });
JS: setInterval(checkCloseAd,1000);
JS: setInterval(footerFixer,1000);
JS: });
JS: </script>
JS:
JS: </body>
JS: </html>

Related

Vue JS Ajax Calls

I am trying to make the change from jQuery to Vue.js and am having some difficulty running an Ajax Call using vueresource. Below is a sample script I am using, with both jQuery and Vuejs. Both trying to access the same ajax call. The jQuery call works, the vuejs call doesn't. The sendAjax method is being called because the first 2 alerts show - then nothing.
Edit - this is only causing an error while running the Ajax call through Wordpress. Outside of WP, it does work. Any ideas??
<!DOCTYPE html>
<html>
<head>
<title>Vue Resource</title>
<script src="https://cdn.jsdelivr.net/npm/jquery#3.2.1/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/vue/latest/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue-resource#1.5.1"></script>
</head>
<body>
<button id="jQueryAjax">Jquery AJAX</button>
<div id="myvue">
<button #click.prevent="sendAjax()">AJAX</button>
</div>
<script>
let AjaxUrl = "http://localhost:8888/mySite/wp-admin/admin-ajax.php";
const postData = { action: 'my_ajaxcall', function: 'AjaxTest' };
Vue.use(VueResource);
const ajax_app = new Vue({
el: '#myvue',
methods: {
sendAjax() {
alert("VueAjax");
alert(JSON.stringify(postData));
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
});
}
}
});
$("#jQueryAjax").click(function() {
alert("jQueryAjax");
alert(JSON.stringify(postData));
alert(AjaxUrl);
$.ajax({
type: 'POST',
url: AjaxUrl,
data: postData,
dataType: 'json',
success: function(data) {
alert(JSON.stringify(data));
},
error: function (xhr, ajaxOptions, thrownError) {
alert("Error");
}
});
});
</script>
</body>
</html>
You AJAX call probably encounters an error and you handle only the successful calls. Please extend your sendAjax function like this:
this.$http.post(AjaxUrl, postData).then(res => {
alert(JSON.stringify(res));
}, err => {
alert(err);
});
Now an error should be alerted.
BTW: It is better to use console.log() instead of alert(), it is much more readable and you won't have to confirm every alert.
After #mbuechmann pointing me to be able to see the actual error, I was able to determine that the issue I was having was actually to do with Wordpress. In order to use the Wordpress Ajax handler, you need to send an action to the REQUEST header. To do this, you need to send FormData, and without sending headers.
This code was found in this question : Custom Shortcode AJAX 400 Bad Request and enabled me to get my Fetch working with Wordpress.
var data = new FormData();
data.append( 'action', 'aj_ajax_demo' ); data.append( 'nonce', aj_ajax_demo.aj_demo_nonce );
fetch(aj_ajax_demo.ajax_url, {
method: 'POST',
body: data, }).then(response => {
if (response.ok) {
response.json().then(response => {
console.log(response);
});
} });

Is there any way to convert result from "nativescript-mediafilepicker" choose to byte [] for save it into Postgres database field bytea type?

I am trying to convert an result from nativescript-mediafilepicker to bytea for store it into a field from a postgres database table. The result from the pick is:
I had test loadFromData, fromData methods from "image-source" for decode it too and nothing.
0: {
JS: "type": "image",
JS: "file": "/storage/emulated/0/Pictures/facebook/FB_IMG_15599124283098587.jpg",
JS: "rawData": {}
JS: }
when i print "rawData" i get this:
JS: ==== object dump start ====
JS: constructor()
JS: <init>()
JS: describeContents()
JS: getOrientation()
JS: setOrientation()
JS: writeToParcel()
JS: equals()
JS: getBucketId()
JS: getBucketName()
JS: getDate()
JS: getId()
JS: getName()
JS: getPath()
JS: getSize()
JS: hashCode()
JS: isSelected()
JS: setBucketId()
JS: setBucketName()
JS: setDate()
JS: setId()
JS: setName()
JS: setPath()
JS: setSelected()
JS: setSize()
JS: clone()
JS: finalize()
JS: getClass()
JS: notify()
JS: notifyAll()
JS: toString()
JS: wait()
JS: ==== object dump end ====
JS: com.vincent.filepicker.filter.entity.ImageFile#3aee1ead
It is inserting into the database nice, but i know that is not working because when i tries to see the image from my program i can't, its a format damaged, and when i am doing from my webapp (JSP) it store it and shows like a charm.

In Django, how to click button to call a view and then reload page

In Django, how to click button on page without passing any value to view.py and then reloading current page? I have a button in the HTML:
<button type="button" class="btn btn-primary" id="refresh">refresh page</button>
I want to call a view in view.py, in which new HTML will be returned:
#csrf_exempt
def topology_show_refresh(request):
'''topology refresh'''
plan = {...}
...
return render(request, 'topology_show.html', {'plan': plan})
The plan dictionary will be used in the new page.
{% if plan.try == 'first' %}
<script type="text/javascript">
var max_lane_num = {{plan.max_lane_num}};
var flag = 0;
</script>
{% else %}
<script type="text/javascript">
var max_lane_num = {{plan.lane_second}};
var flag = 1;
</script>
{% endif %}
In my way, I use ajax to jump to this view, but I have no idea how to handle the return, e.g., pass the plan to HTML.
$(function(){
$("#refresh").click(function(event){
url = 'refresh/';
$.post(url, {}, function(ret){
//do something
//how to pass "plan" dictionary to HTML
});
});
});
You are very close to the task of reloading page,
Use 'location.reload(true)' instead of 'window.location.reload();'
And handle the response data by success() function.
Try this :
$(function(){
$("#refresh").click(function(event){
$.ajax({
type: "POST",
url: 'refresh/',
success:function(response) {
location.reload(true);
//do something with 'response'
}
});
});

Json call in js file returns NetworkError: 404 Not Found

I am using asp.net mvc 4, knockout-js within my application.
I would like to ask how can i make an call from js file to the controller?
it works when i write this code into the view (razor) page:
<script type="text/javascript">
$(document).ready(function () {
var url = '#Url.Action("GetTechnicians", "Ticket")';
$.post(url, null, function (data) {
alert("get data");
});
});
</script>
now I would like to make the call in *.js file.
the problem is that Url.Action is invalid within js file.
My url mapping in global.asax is: "{culture}/{controller}/{action}/{id}",
signature of my controller looks like: public JsonResult GetTechnicians()
When I use in js file:
var url = "/Ticket/Technicians";
I get an error: "NetworkError: 404 Not Found - http://localhost/Ticket/Technicians"
I would like to know how to complete the call from js file?
You could do the following...
In your JS file
var app = {
urls: {
getTechnicians: null
},
culture: "en",
getTechnicians: function () {
if (!app.urls.getTechnicians) {
throw new Error("getTechnicians URL not set");
}
$.post("/" + app.culture + app.urls.getTechnicians, null, function (data) {
alert("get data");
});
}
};
In your view
<script type="text/javascript" src="myscriptfile.js"></script>
<script type="text/javascript">
$(document).ready(function () {
app.urls.getTechnicians = '#Url.Action("GetTechnicians", "Ticket")';
app.culture = "en-us";
// Later on...
app.getTechnicians();
});
</script>

Is there a way to get Internet Explorer not to wait until an AJAX request completes before following a link?

I have a html page that displays some basic account information and begins a long-ish running jQuery AJAX request to retrieve more detailed data. While the Ajax request is in progress it is possible for the user to click a button that has an onclick event to navigate to a new page using location.assign.
Unfortunately if the button is clicked before the ajax request is complete nothing will happen until the ajax request completes. This is a live server issue. I want the user to be able to immediately navigate away. FF and Chrome appear to behave better but since this is a corporate intranet application they are not really an option.
The following code is similar to the page in question:
<html>
<head>
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"> </script>
<script type="text/javascript">
<!--
$(function () {
jQuery.ajax({
type: 'GET',
url: '/long-running-partial-html-ajax-endpoint',
success: function (result) {
$('#detail').html(result); });
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
$('#detail').html('Failed to load additional information:<br />' + textStatus + '<br />' + errorThrown);
}
});
});
//-->
</script>
</head>
<body>
<h2>Account Information</h2>
<div>Some basic details here</div>
<div><button onclick="location.assign("/somewhere-else")" type="button">Go somewhere else now</button></div>
<div id="detail">
<img src="/ajax-loading-animation.gif" alt="Loading ..." />
Loading ...
</div>
</body>
</html>
Things I've tried in the debugger (not on live) already:
using a plain anchor rather than a scripted button
using xhr.abort() before the location.assign
put alerts around the location.assign to reassure myself that the code is executing when expected
Observation:
IE stops animating the gif as soon as the button is clicked.
FF/Chrome must automatically abort the ajax request as the jQuery ajax error event is fired
Has anyone come across this issue before? Have you a resolution that will make the navigation more responsive?
Have you tried to call the ajax method after the page is loaded
<body onload="myFunctionThatCallsAjax()">
There are some browser behavior differences when you embed Javascript in the HTML code. Using onload will ensure this is not an issue.
I ended up executing the long running task in a separate thread on the server. The ajax call then just repeatedly calls in to check if a response is ready yet. That way each ajax request is very short.
My solution is fine for a intranet application but would probably need to be made more robust for a Internet application.
So the html becomes:
<html>
<head>
<script src="/js/jquery-1.3.2.min.js" type="text/javascript"> </script>
<script type="text/javascript">
<!--
var detailRequest = null;
function StartDetailRequest() {
detailRequest = jQuery.ajax({
type: 'GET',
url: '<%= Url.Action("EnquiryDetail", "Account", new { requestGuid = ViewData["detailRequestGuid"] }) %>',
success: function (result) {
if (result.length == 0) {
setTimeout("StartDetailRequest()", 500);
}
else {
$('#detail').html(result);
$("table tbody").each(function () { $("tr:odd", this).addClass("odd"); });
}
},
error: function (xmlHttpRequest, textStatus, errorThrown) {
$('#detail').html('Failed to load additional information:<br />' + textStatus + '<br />' + errorThrown);
}
});
}
$(function () {
setTimeout("StartDetailRequest()", 500);
});
//-->
</script>
</head>
<body>
<h2>Account Information</h2>
<div>Some basic details here</div>
<div><button onclick="location.assign("/somewhere-else")" type="button">Go somewhere else now</button></div>
<div id="detail">
<img src="/ajax-loading-animation.gif" alt="Loading ..." />
Loading ...
</div>
</body>
</html>
On the server side I do something like (ASP.NET MVC 2 with pseudo code):
private Dictionary<Guid, DetailRequestObject> detailRequestList = new Dictionary<Guid, DetailRequestObject>();
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index(string id)
{
var model = GetTheBasicDetails(id);
var request = CreateDetailRequestObject(id);
CheckForTimedOutDetailRequests();
detailRequestList.Add(request.Guid, request);
ViewData["detailRequestGuid"] = request.Guid;
return View(model);
}
[AcceptVerbs(HttpVerbs.Get)]
public ActionResult EnquiryDetail(Guid requestGuid)
{
DetailRequestObject detailRequest = detailRequestList[requestGuid];
if (detailRequest == null)
{
throw new TimeoutException("Timed out retrieving details");
}
else if (!detailRequest.IsComplete)
{
return Content("");
}
else
{
var details = detailRequest.Response();
return PartialView(details);
}
}
The DetailRequestObject class encapsulates the creation of a separate thread using the async model of your choice, sets a flag when complete and collects the response data.
I also have a method CheckForTimedOutDetailRequests that collects requests that have timed out for retrieving so that any that have been 'aborted' can be cleared up.
I think I would prefer to have the long running requests run in a separate Windows Service that would do it's own clean-up, request throttling and such but the above works so...

Resources