$.post getting canceled in chrome - php

I am calling a php file using $.post. From the server I am returning json response. When I open the server url directly in browser it returns successfully. But from js it is not working.
The link I am calling is this(http://54.249.240.120/qcorner/login).
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<input type="button" id="testID">
<script type="text/javascript">
$(document).ready(function() {
$("#testID").click(function() {
$.post('http://54.249.240.120/qcorner/login',function(result){
alert(result);
});
});
});
</script>
</body>
</html>
I also tried in Firefox. In that I get 200 OK, but no response.
Why this is happening

The problem is that it is a cross domain request the error being returned can be viewed by turning on the javascript console:
XMLHttpRequest cannot load http://54.249.240.120/qcorner/login. Origin null is not allowed by Access-Control-Allow-Origin.
You will need to make sure that the Access-Control-Allow-Origin headers are set to allow this to happen or Chrome will cancel the request.

I suspect you're running into a Cross-origin resource sharing problem. I'm guessing you're not accessing this page from http://54.249.240.120/, given that Chrome is showing it explicitly in the network tab (usually it doesn't do that if it's the same domain).
Long story short, you can't post via Javascript to another domain name. If you're accessing this at www.example.com, the browser won't recognize the IP address as the same domain name (even if the domain name resolves there). Easiest way, if you're in control of the whole situation, is just put that login code on the same domain as the code you're testing. In a local environment you can do this with your [hosts file, something like 54.249.240.120 www.example.com to redirect example.com (replace with your own domain that you are accessing the test page from) to the IP address. This won't work for the public internet, however.
If you must POST to another domain via javascript, you'll need to look into implementing the CORS standard. Here's an article I found explaining how to implement it in PHP.

An HTML 200 OK is not the same as a valid response. It means the server got your request, but it doesn't mean that your PHP file actually returned usable data. It could be returning an empty response altogether. It's time to debug the PHP file. I'd suggest logging to a file temporarily or use FirePHP. If error display is disable (as it should be on a production server), this can happen if your script is failing before any output is generated.

What exactly is happening with the request? You can't make an ajax request cross-domain with what you have listed in the question.
However, you're sending an empty POST request to the URL, and when I replicate an empty post request, it responds with an HTTP 206 error, which is what you need to sort out.
curl -X POST http://54.249.240.120/qcorner/login
{"head":{"status":206,"message":"Only 0 fields received, required 2"},"body":""}

I had the same issue as you and what I did is very simple.
In you PHP file receiving the ajax request, just add this line before sending the response :
<?php
header("Access-Control-Allow-Origin: *");
... // your code here
?>

Related

$_COOKIE not working when php file called using xmlhttprequest

Hi anyone please help me. I writted on php simple code test.php. I am just reading cookie only and displaying it. when i execute the below url in chrome browser i am get response
https://www.domainname.com/cbscheck/test.php
response
testa3433^| 1^|1^|0da1d48927ec9118d271cc6a4f0df3e90ee4d296^|1
same php url i called in below html file using xmlhttprequest but i am not getting the above reponse.
file:///G:/Hari/MyTaks/Chat/chatCheck.html
response i am getting empty.
My perception $_COOKIE not working when i called using xmlhttprequest. please any help me how to resolve it. i shared code below
testCheck.htm
<html>
<body>
<div id = 'onlineUsers' class='bottomDiv'>
</div>
<script>
var url = 'https://www.somedomain.com/cbscheck/test.php';
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange=function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("onlineUsers").innerHTML = this.responseText;
}
};
xhttp.open("GET", url , true);
xhttp.send();
</script>
</body>
</html>
test.php
<?php
echo $_COOKIE["loginInfo"];
?>
You need to set xhttp.withCredentials = true; to send credentials (and COOKIES too) to the target server using XMLHttpRequest. For more information look the docs.
The next problem you faced is about Access-Control-Allow-Origin header. Your server sends Access-Control-Allow-Origin: * header, and thats why your browser rejects your XMLHttpRequest. Access-Control-Allow-Origin: * header means that your server application allows you to send requests from frontend to ANY other server. With combination of xhttp.withCredentials = true it's very big vulnerability, cause malware js script on your page can send user's credentials to any other place. Thats why your browser rejects your request. You should add yours domain to Access-Control-Allow-Origin header and remove *. This problem was already solved in this question.
Ensure that domain the cookie is set on and domain you are making ajax request to are the same. Also, check the url path the cookie is set on.
Browser will send cookies only to the domain and within the url path it was set on (if you don't apply specific cross-domain rules).
I think you have to run in server if you open html directly in browser it will not understand php code so that's why it's not working.

How have safe HTTP Request Method

when use GET Method for receive JSON data , we can acsses the result directly from web browser , for example i send a mydata value from ajax to a main.php file and it process and get answer show a result some thing like below :
<?php
if (isset($_GET["mydata"])) {
if ($_GET["mydata"]=="hello"){
echo "hello world";
}
}
?>
but when a user call it in browser directly like http:mysite.com/mydata.php?mydata=hello recive answer . i want dont allow users to get answer of http request directly , and just can show it from ajax result of main page is it possible ?
You're asking how to prevent an ajax-only request from being accessed directly by copy-pasting the URL into the web browser; that is, only allowing the URL to be accessible via ajax on the main web page.
Well, there are a few things you can try:
Check the Referrer for the URL of the main page with $_SERVER['HTTP_REFERER']
Set a header in Javascript using xhr.setRequestHeader() and then ensure it's value by checking for $_SERVER['HTTP_X_....'] in PHP
Like Jay Bhatt recommended, check for the X_REQUESTED_WITH header, but be aware this might not always be set (see: X-Requested-With header not set in jquery ajaxForm plugin)
However, in any of these situations you should be aware that anyone who knows what they are doing can easily set any HTTP header, variable, or even modify the referrer which is sent to the server. As such, there is no 100% guarantee that your resouce can be accessed only via AJAX on the main web page. There is no control built in the internet to verify where a request is coming from, so anyone can easily spoof or fake it.

$_SESSION Variables empty at XMLHttpRequest

After the hoster upgraded from PHP 4.x to PHP 5.4.1 a friend of mine has a huge problem accessing $_SESSION variables when doing it via XMLHttpRequest (he uses jQuery for that).
I hope the following snippets of his code are illustrating his problem:
index.php
<?PHP
session_start ();
$_SESSION['chatfenster'] = array();
$_SESSION['user'] = 1;
?>
<!-- HTML Markup -->
<script type="text/javascript" src="../scripts/jquery/js/jquery-1.8.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
setInterval(function() {
$.post("http://www.his-domain.at/ticker_tracker.php", function( feedback ) { alert(feedback); } )
},
10000);
});
ticker_tracker.php:
<?PHP
session_start();
var_dump($_SESSION);
?>
When he browses to index.php and afterwards manually to ticker_tracker.php, the $_SESSION variables are var_dumped correctly, but if the php file is called via $.post(), the $_SESSION variables are all empty, thus alerting just "array{}".
Hosters support says everything is fine and they didn't change any settings at all, but I noticed that Chrome blocks the XMLHttpRequest due to cross domain requests, giving the error message (also only appearing after upgrade to PHP 5.4.1):
XMLHttpRequest cannot load. No 'Access-Control-Allow-Origin' header is present.
Adding Access-Control-Allow-Origin headers on the very top of every php solves this error, but the main problem (empty $_SESSION variables) still remains.
Any advice is appreciated. Thanks in advance!
If you get the access-control-allow-origin error (that can be solved as you said by adding a header), then you are doing a cross-domain request. That's why you have different session contents: they are different sessions!
This can be from one machine (domain) to the other (www.one.com to www.two.com), this could be from one subdomain to the other (www.one.com vs one.com) or this could be a different service (e.g. http vs https, and these might be served by a different machine or process).
All these things have one thing in common: you have a request that seems to go to a different place (hence the allow origin). And a different place has different sessions, as they are not shared.
Check why you have the access control thingy going on: the request isn't going to the same place. So 'fixing' it with headers is just a fix for the origin: remove that 'fix', and make the request not needing it. then you're back at the same server/process/whatever, and will have the same session.

Blank PHP/Index Page on Android HTTP Post Request

Upon using the code samples below, I try to send a HTTP request to validate a username and password entry to a PHP script (returning either 1 or 0 in an echo).
Using HTTP Assistant, testing the HTTP Post request has the expected results... But for some reason, when logging the 'res' String (the HTTP response) in the java code, I get a blank PHP/Index page:
<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML3.2Final//EN"><html><title>Indexof/</title></head><body><h1>Indexof/</h1><ul><li>cgi-bin/</li></ul></body></html>
Code: HomeActivity.java and Http.java
Have I done something wrong code-wise? Or is this a server issue?
What you are seeing there is the standard webserver listing of a directory. So you probably have the wrong URL you're hitting. Is there any redirect magic involved?
[edit] As you have controll of the PHP page yourself, do the following: Edit it so that it accepts parameters per GET and try to call the page via your android browser with the username and password as GET parameters . If that works, you've at least a clue that it's possible from your phone.

Will all code after redirect header in PHP always get executed?

So I know the general rule of thumb is after doing a header redirect in PHP, you should call exit() to avoid having extra code running, but I want to know if you put code after the redirect header, if it will always run?
I was doing some research on various ways of tracking referrals in Google Analytics and came across this post: Google Analytics Tips & Tricks – Tracking 301 Redirects in Google Analytics
It recommends doing something like this:
<?
Header( “HTTP/1.1 301 Moved Permanently” );
Header( “Location: http://www.new-url.com” );
?>
<script type=”text/javascript”>
var gaJsHost = ((“https:” == document.location.protocol) ? “https://ssl.” : “http://www.”);
document.write(unescape(“%3Cscript src=’” + gaJsHost + “google-analytics.com/ga.js’ type=’text/javascript’%3E%3C/script%3E”));
</script>
<script type=”text/javascript”>
try {
var pageTracker = _gat._getTracker(“UA-YOURPROFILE-ID”);
pageTracker._trackPageview();
} catch(err) {}</script>
From the way I've always understood the header() function, it's up to the browser and it can run the redirect whenever it wants to. So there's no guarantee the JavaScript would actually begin or finish executing prior to the redirect occurring.
PHP's documentation for the header() function indicates the reason for exiting after a redirect is to "make sure that code below does not get executed when we redirect." That doesn't sound like they guarantee all following code will run, just that it could happen.
Regardless, I found a different way to actually manage the tracking, but I wanted to see if I could find out how exactly header() worked in this situation..
Thanks for your help.
Using the header function in PHP only adds to the headers of the response returned by the server. It does not immediately send any data and does not immediately terminate the connection. Any code after the header call will be executed.
In particular, it's a good idea to add a response body even after doing a 301 redirect so that clients that do not support the redirect also get some descriptive response. Infact according to the HTTP 1.1 specification Section 10.3.2 -
Unless the request method was HEAD, the entity of the response SHOULD
contain a short hypertext note with a hyperlink to the new URI(s). If
the 301 status code is received in response to a request other than
GET or HEAD, the user agent MUST NOT automatically redirect the
request unless it can be confirmed by the user, since this might
change the conditions under which the request was issued.
It's a race condition. Once the redirect header is sent to the browser, the browser will close the current connection and open a new one for the redirect URL. Until that original connection is closed and Apache shuts down the script, your code will continue to execute as before.
In theory, if there was a sufficiently fast connection between the client/server, and there was no buffering anywhere in the pipeline, issuing the header would cause the script to be terminated immediately. In reality, it can be anywhere between "now" and "never" for the shutdown to be initiated.
The HTML after your Location line doesn't run inside PHP; it would run in the browser. It's up to the browser whether or not to execute the Javascript that you've included on that page; PHP has nothing to do with it.
To me, the PHP docs imply that any PHP below the header() when you send a redirect will continue to run. But it 'runs' in the PHP interpreter, dumping JS to the browser. There's no relation between what it says in the PHP docs and whether or not the JS gets run by the browser.
EDIT:
Well, as Anupam Jain pointed out, looks like that browsers do not terminate connection without getting the response body and it sounds sensible. So i rethinked my answer
That doesn't sound like they guarantee all following code will run
Exactly More likely it's a warning in case there is some sensible code that shouldn't be executed. A private page contents for example. So, beside sending header you have to also make sure that no sensitive content were sent and exit looks like quite robust solution. So, I'd phrase it as "make sure that sensible code below does not get executed when we redirect."
So there's no guarantee the JavaScript would actually begin or finish executing prior to the redirect occurring.
Exactly It seems it has nothing to do with script execution but rather with browser's will to execute anything after getting 3xx response. I think I'm gonna test it, but you can test it as well too.
I have noticed that the code does still execute and multiple headers based on if statements can cause a "redirect loop error". i made it a habit to now add in die("Redirecting..."); after every header redirect and have not see the problem persist.

Categories