1

This is killing me.

I am building a mobile app using apache cordova where jQuery AJAX and PHP are being used to communicate with the server and database. I first discovered this issue when I was encountering errors that my teammates were not, and we were using the same code. In some of our PHP code, we were using $_SESSION variables to store data but it is not being stored properly when running the app on my machine. Here is an example of the code that is not working:

<?php

header('Access-Control-Allow-Origin : *');
include 'connection.php';

$userId = $_SESSION["userId"];

$query = "SELECT * ".
         "FROM `db`.`users` ".
         "WHERE `userId` = $userId;";

$result = $conn->query($query);
$result_array = array();
while($row = mysqli_fetch_assoc($result))
{
    $result_array[] = $row;
}
echo json_encode($result_array);

In a page that runs prior to this, a different php file is called containing this line:

$_SESSION["userId"] = $userId;

include connection.php contains all our user/login info as well as session_start(); before anything. The workaround was this: This error does not happen when I build the app and test it on a device. It only occurs on my machine when debugging the app through the ripple emulator in a chrome browser window. Because I did not want to create a new build so frequently, I changed our code to store the data on the front end, using sessionStorage, and had to disable the Cross Domain Proxy setting on the emulator.

This is where I believe the error is: None of my AJAX calls are successful unless I set the Cross Domain Proxy to "Disabled", but if I do that, PHP $_SESSION no longer works (I discovered the session id just resets every new call). My teammate can debug on the emulator just fine and his Cross Domain Proxy is set to "Local". When I try it this way, all of my AJAX calls error out once again.

Also - one last thing to note: When I run the app in just a web browser, not using the ripple emulator or anything, everything runs just fine. Which would narrow the issue down to something specifically with the ripple emulator.

I am relatively new to this stuff - CORS and AJAX requests, but I did some serious research before posting on here - this is my last resort. I will be monitoring this question frequently in case you need anything else from me to help me solve this issue. Thanks!

EDIT: Below is the error I get when I run ripple emulate from the command line after making some of the suggested changes, it's the same error I was getting before:

 C:\Users\Brian\Documents\HoH Docs\Source Code\gitDev\HoH\www>ripple emulate
INFO: Server instance running on: http://localhost:4400
INFO: CORS XHR proxy service on: http://localhost:4400/ripple/xhr_proxy
INFO: JSONP XHR proxy service on: http://localhost:4400/ripple/jsonp_xhr_proxy
INFO: Could not find cordova as a local module. Expecting to find it installed g
lobally.
INFO: Using Browser User Agent (String)
INFO: Proxying cross origin XMLHttpRequest - http://www.server.com/php/
[email protected]&password=test
_http_outgoing.js:347
      throw new TypeError(
      ^

TypeError: Trailer name must be a valid HTTP Token ["access-control-allow-origin
 "]
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:347:13)
    at ServerResponse.res.setHeader (C:\Users\Brian\AppData\Roaming\npm\node_mod
ules\ripple-emulator\node_modules\express\node_modules\connect\lib\patch.js:59:2
2)
    at Request.pipeDest (C:\Users\Brian\AppData\Roaming\npm\node_modules\ripple-
emulator\node_modules\request\main.js:723:12)
    at C:\Users\Brian\AppData\Roaming\npm\node_modules\ripple-emulator\node_modu
les\request\main.js:614:14
    at Array.forEach (native)
    at ClientRequest.<anonymous> (C:\Users\Brian\AppData\Roaming\npm\node_module
s\ripple-emulator\node_modules\request\main.js:613:18)
    at ClientRequest.g (events.js:260:16)
    at emitOne (events.js:77:13)
    at ClientRequest.emit (events.js:169:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:433:21
)

And get this from the Fiddler Web Debugger when the request is made:

The connection to 'localhost' failed. <br />Error: ConnectionRefused (0x274d). <br />System.Net.Sockets.SocketException No connection could be made because the target machine actively refused it 127.0.0.1:4400                                                                                                                                                                                                                                                                                                     
5
  • $_SESSION by default work with a cookie that store on the browser the id of the session. This cookie id is normaly send every time in the header when the browser call a script. Moreover when you do a CORS call the header have to be with allow-all. So I hthink it' will be a good bet to go to see the header that is used in your app or on your server. Commented Aug 22, 2016 at 7:24
  • How do I see the header? Commented Aug 22, 2016 at 7:36
  • You have access to it in the chrome dev tool in network section. Commented Aug 22, 2016 at 16:35
  • I see the header section, not quite sure what I am looking for though. Commented Aug 22, 2016 at 17:53
  • In the header you shoudl have something like cookie that return the data of your cookie. You said that you have no problem on your brother. So now you see what the header should be. After you have to figure which header is send in the ripple emulator. I can help you for that because I don't know it. Commented Aug 22, 2016 at 18:20

2 Answers 2

1

This is most likely your problem:

header('Access-Control-Allow-Origin : *');
include 'connection.php';

You are sending headers to the browser before you include the connection file where you start the session.

On some testing environments, output buffering might be turned on so this would work. However, on your environment it seems it is not so your session_start() in connection.php will fail.

You should not output anything to the browser before the call to session_start() so in this case you should move the header() call to below the include:

include 'connection.php';
header('Access-Control-Allow-Origin : *');

You can probably verify that this is the problem in the server error log.

Sign up to request clarification or add additional context in comments.

1 Comment

I just tested this, but still getting the same issue.
0

You might be have to set header in your ajax request

if your are using jQuery ajax method then add below option

xhrFields: {
    withCredentials: true
}

Or if you send ajax request using XMLHttpRequest object then it should be something like belwo

var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);

XmlHttpRequest responses from a different domain cannot set cookie values for their own domain unless withCredentials is set to true before making the request, regardless of Access-Control- header values.

3 Comments

Just tested this, but I am still getting the same result. I just added an edit with the errors I am getting
try with crossDomain : true, in ajax
Still getting same issue...this is very confusing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.