Getting xmlhttprequest to work from javascript inside qml document - javascript

So i wrote this qml app for mobile in which i am trying to pass some data via http POST request to a php page on a webserver. After having done some research, I am assured that I should be able to do this from a qml document using javascript xmlhttprequest. all seems very neat and simple (I found a few variations on the web like this Https POST / GET with Qml/Qt). From which I used the script in the answer.
For a test scenario, I have spun up a LAMP (with L = Ubuntu server) on a Virtualbox, I try to POST some data in a param (much like in above link) to a .php page but get only http.status = 0 . The php script is never getting any content in $_POST. So first thing to check is that i can actualy do a http POST request to that same server via a webform in a browser. That works without a hitch.
So i am begining to get the idea that doing xmlhttprequest outside of a browser is not the same as within one. And this may mean that i need to do some config voodoo on the Apache side. I am by no means an apache guru So I am at a loss now.
Hopefully someone has done something like this or is spotting what I am missing?
Thanks.

oh my :( I made the most idiotic php scripting error that I overlooked about 200 times. Sorry! well lets say that even geniuses err sometimes.
To make this somewhat usefull: I have to say that I still do not understand why I was handed back http.status = 0 . I discovered that this was the wrong errorcode when I started using curl. doing a POST from curl suddenly gave me back general http errorcode 500. So that made me dive into /var/log/apache2/error.log and there I saw my stupid mistake.

Related

Why would replacing a div via a GET request through AJAX cause my website to slow down so much compared to no JavaScript at all?

So the whole reason I am using AJAX is to make page changes seem smoother. However I have realized that using AJAX is actually slowing down the website significantly. I am using localhost with apache. I am running php on the backend to access a database for various pages.
It's taken up to 5 seconds just to load a single page.
Here is some AJAX:
$(function() {
$(".menu_nav").click(function() {
$.ajax({
type: "GET",
url: "menu.php",
dataType: 'html',
success: function(data) {
var toInsert = $(data).filter(".placeholder");
var style = $(data).filter("#style");
$("#style").replaceWith(style);
$(".placeholder").replaceWith(toInsert);
window.scrollTo(0,0);
}
});
});
});
'menu_nav' and 'home_nav' are both divs with click events attached to them, and on click they are performing a GET request to the server and asking for a div in the .php as well as it's styling sheet. It then will replace the div and style sheet on this page with what it retrieved from the GET request. Where I am having trouble understanding though is why is this taking up to 5 seconds to perform the GET request, whereas without any javascript I am getting minuscule load times, just less "pretty"?
I looked at the timeline and network tabs in the web inspector, and had noticed that every time I perform one of these requests, I get a new file from the server, rather than reading the one I've already got, which makes sense because there might be new data in the page since the last visit, however I don't see a duplicate being added to the list of sources when I am not using AJAX. For example:
Whereas without AJAX, there is only one. This makes sense since I am initiating a GET request to the server, but the same is happening when you click a link without AJAX.
Regardless, I still don't understand what is making it so slow as opposed to not using JavaScript. I understand it is doing more in addition to just a GET request, but is filtering and replacing text after a response really what is causing this issue?
Side question: This is outside the scope of this question, but in regards to AJAX, when I perform a request to the server, is the PHP within the file still executing before it gives me the HTML? So on pages where a user must have certain permissions, will the PHP that catches that still be ran?
EDIT: I am hosting a MySQL database through a free subscription to a cloud hosting service. This issue occurs when I access my website through both localhost, and when accessing the website that way deployed via the free cloud hosting service, though it is way slower when I use the cloud service. I am also using various resources from the MAMP (MacOS Apache, MySQL, PHP; If you're on windows and interested, WAMP is also available fore free) installation.
I'm not sure what is causing your slowness issues, but you could try doing some profiling to narrow down the issue. My guess is that while changing your code to use ajax, you also introduced or revealed some bug that's causing this slowness issue.
Is there an issue with the javascript? You can place console.time() and console.timeEnd() in different places to see how long a chunk of javascript takes to execute. (e.g. at the start and end of your ajax callback). Based on what you posted, this is likely not the issue, but you can always double check.
Is it PHP that's running slow? You can use similar profiling functions in PHP to make sure it's not hanging on something.
Are there network issues? You could, for example, log the timestamp of when javascript sent the request and when PHP received it, and vice versa. (this should work OK on localhost, but in other environments you have to be careful of clocks being out of sync)
There's a lot that could be going wrong here, so its hard to give a more specific answer, but hopefully that gives you some tools to help you start looking.
As for your side question: you are correct - PHP will start sending the HTML while it continues to execute. For example:
<div>
<?php someLongBlockingFunction(); ?>
</div>
<div> will get sent to the browser, then PHP will stall on the long-running-function before it finally sends out the ending </div>. The browser will piece together the chunks, and your event listener won't get called until PHP has finished sending the entire file.

Cross-domain interactions with a Java Servlet

I have a JavaScript web app on my server and I'm looking at the possibility of doing an AJAX connection with an existing Java servlet on a different server. I'm collaborating with the servlet developer, but he is currently dealing with other projects, and I'm trying to see how much I can get done without him needing to do anything. He's not too familiar with JS and I don't have any Java experience... but we've got a lot of good intentions!
His servlet has an HTML form interface sending a POST request. As a first step I downloaded his form, uploaded it to my server and changed the form's action to an absolute URL, from
<form action="/path/to/Servlet" [...] >
to
<form action="http://remoteserver.com/path/to/Servlet" [...] >
When I test the form on his server, it works fine, but when I test with the same exact input on the form on my server, the server returns a 500 error with a Java exception:
java.lang.NullPointerException
Filechange_b2.doPost(Filechange_b2.java:322)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I realize that this is a bit of a black box problem, but based on these clues, is there anything I can do from my end? It's my understanding that a form request wouldn't trigger any CORS-related security issues; my hunch based on the code here is that there is something in his code that is relying on the assumption that input is coming from a local page.
Any ideas to go on here? Thanks very much for your help.
EDIT: Okay, looks like the JSP/Java interaction is more complicated than I originally thought and involves passing a session ID back and forth. That at least gives me something more to go on. Yay learning!

Simple php script fetching visitor details like screen resolution, country of origin etc

First a little bit about me because it might help:
I am NOT a professional coder, I write HTML and CSS by hand with notepad++ because i like the lightweight and effective code + I have total control and clue of what is going on in my files/website.
I don't like WP. Its too much hassle and yes i know it's "easier" but since I know nothing about php, except that it's a server side language, it's not easier for me to get the look of the website that I want with it. (recently I found out I can INCLUDE a part(s).html in actual.html and compose actual.html - not up for that right now as it makes a new connection for each part.html (when i get to more complex web-developing, as my sites are static, etc...)) Tried multiple times, ended up deleting everything and writing my own code from scratch. I don't like to learn the (php) code from WP editing (extremely time-consuming and messy), I prefer learning it by using the code when i need it. That's how i remember and learn. That's how I learned C#.
I like one-file type of web pages as they are pretty much static. Any pics that i might use i DON'T create any links, I convert them in base64 and paste the code where i need it. So as minimalistic as possible with fewer requests as possible with least kb as possible - but resemble WP by look and behavior (responsivness).
I reserve one request for style.css and one for favicon.ico; #1 it's neater, #2 can't be base64-ed nor CSS loaded.
Anyway, a php contact form that I used in one of my sites was working perfectly, with just contact.php file on the server and a little bit of js in html. Therefore i ASSUME that fetching user data such as IP, time of access, screen resolution and OS would be easy similarly as the contact form was.
What I would like to know is next:
fetch device.useragent + device.resolution + time + IP;
write fetched to log.txt
Then i ftp the log.txt to my pc and investigate.
Thank you for reading and considering to help :)
The user agent, time, and IP address can be stored in variables as follows:
$userAgent = $_SERVER['HTTP_USER_AGENT'];
$time = date('Y-m-d H:i:s');
$ip = $_SERVER['REMOTE_ADDR'];
For resolution, you'd have to determine it with JavaScript and send it to the server with an AJAX request or as part of the request body. All of this can then be written to a log.txt file using file_put_contents('path/to/log.txt', $data);.
Note, that there are usually simpler ways of achieving this if using a framework (e.g. Symfony, Laravel, Zend), or there may even be a plugin for your CMS of choice.
Check this post, PHP's get_browser, and also this post is very helpful. For the resolution, like Sheraz said, you need JS or any JS library that can read the device resolution. If you want to use jQuery, check this post. To fetch user time of access, you can create a $_SESSION variable and use time. For the ip, check this. And for file handling, fopen, file_get_contents, file_put_contents and fclose will help you.

Requesting remote XML data with javascript

Ok here's my problem. I'm working on this little site called 10winstreak and I'm trying to detect if a stream is live or not with javascript because our server that we run the site off of cant handle processing every single request with PHP. The basis of detecting if a stream is live or not is you go to their XML file and in one of their tags (if it's live) it will say something along the lines of true and often time the XML file on their site will be empty if a particular stream isn't live. for example if you have a twitch.tv stream for gamespot you go to http://api.justin.tv/api/stream/list.xml?channel=gamespot and if it's got stuff in it then it's live if not then it's not.
so basically my code looks like this:
function check (URL, term){
$.get(URL , function(data){
console.log(data);
//data is whatever the server returns from the request, do whatever is needed with it to show who is live.
var number = data.search(term);
if (number > -1)
{
document.write("Live");
}
else
{
document.write("Offline");
}
});
}
and URL is a url that gets passed in and term is the term to search for in the xml file (usually "true" or "True"). but before anything happens I end up with "XMLHttpRequest cannot load http://api.own3d.tv/liveCheck.php?live_id=6815. Origin (my server's URL) is not allowed by Access-Control-Allow-Origin."
I've looked into it all over the net and i dont seem to be able to find anything that I can use. there's alot of theory stuff but not enough actual code and i dont understand the theory stuff to be able to start typing code out. from what i've seen you have 2 ways to go, use JSONP or add a line somewhere in your sever to allow for cross-domain accessing. neither of which i understand fully nor know how or what to do. It would be alot of help for someone to show me what needs to be done to get rid of this error. of course if you can explain it to a non-coder like me it would be even more awesome but at my current point, as long as the code works for all I care it might as well be magic lol.
You can solve it :)
Take a look at xReader
<script src="http://kincrew.github.com/xReader/xReader.full.js"></script>
<script type="text/javascript">
xReader("http://api.own3d.tv/liveCheck.php?live_id=6815", function(data) {
alert(data.content);
})
</script>
I think you need cacheburst option. but you can be banned from YQL.
I think its because the path is not relative. You may be calling this from a different domain/sub-domain. You can potentially allow other origins to access, which may open up a security hole or you can create a proxy locally.
In PHP creating a proxy is easy: http://blog.proxybonanza.com/programming/php-curl-with-proxy/
Now, instead of directing your request straight to that URL send the request from jQuery to your own local url and have it access it on the server side.
Another option would be to use YQL: http://www.parrisstudios.com/?p=333 (I wrote an article about this a while ago)... In that way you can turn the response into JSON, which can be accessed cross-domain (as can javascript).
You could ask for the API responses to all be returned using a JSONP server and in JSON.
You aren't going to be able to do this via client-side javascript unless they've enabled some way to retrieve their data cross-domain (CORS, JSONP, some flash widgety thing getting read permissions from crossdomain.xml file(s) located on their server...)
Short answer: unless 10winstreak offers a JSONP service, you'll have to do things on the server-side.
Slightly longer answer:
For security reasons browsers won't let you make AJAX requests from www.example.com to www.example2.com (or any other domain except www.example.com). There isn't much you can do about this except use JSONP (and you can only do that if the remote webservice offers it).
Therefore, what you end up needing to do is ask your server "hey what's on that other server?" and (since it's not limited the way a browser is) it can go get the XML from that other server. There are various ways of doing this, either with code or Apache config; not sure what's right for you, but hopefully now you understand the general principle.
P.S. See this question: Wouldn't have been simpler to just discard cookies for cross-domain XHR? if you are curious why browsers do this.
* EDIT *
I just checked out JustinTV's site, and it appears that they already have a PHP library for you to use:
https://github.com/jtvapi/jtv_php_api
This is very likely your best bet (if you want to keep using PHP that is; if not they have libraries for other languages: http://www.justin.tv/p/api).

Using POST to send data back to objective c

I am attempting to send data back to my objective c program from javascript.
I found a very helpful question here that got me started, but I quickly ran into a problem: the post seems to be failing.
I also verified syntax at this helpful site.
I know this because I update the contents of a div on my page before and after the post call and I only see the update pre-post. I also have a breakpoint at the beginning of shouldStartLoadWithRequest and it's not firing.
Here's my simple javascript code:
function updateAction(obj) {
document.getElementById("status").innerHTML="sending:"+obj;
$.post("http://actionupdate", {"data":obj});
document.getElementById("status").innerHTML="sent";
}
So.. my question: what am I missing? What's wrong with my post?
From your syntax, I guess you are using jquery? The UIWebViewDelegate's webView:shouldStartLoadWithRequest:navigationType: method does not seem to get called for ajax requests, which is what $.post() does. You have to use a normal post instead.
You may find UIWebViewDelegate not monitoring XMLHttpRequest? helpful.

Categories

Resources