1

I am developing a phonegap application where i need to send a some data from a html file to a server and get a output in response. When i have all my files in save server they work. When i split the files into client and server machines they dont work and as far i understood it has to do with CROSS DOMAIN POST REQUEST. Here is my code below:

Client side: something.html

$(document).ready(function() {
$("#login").click(function(e){

 var formData = $("#loginForm").serialize();

 $.ajax({
        type: "POST",
        url: "http://testserver.bscheme.com/rss/login.php",
        crossDomain: true,
    cache: false,
        data: formData,
        success: function(txt){
            if(txt !=""){               
                    localStorage.setItem("background", txt);
                    //alert(localStorage.getItem("background"));
                    document.location.href="logged.html";
            }
            else
            alert("Badly Failed");          
            }
        });

        e.preventDefault();
    });   });

Server Side: login.php

<?php

include('inc/db.php');

try
{
$userName       = mysql_real_escape_string($_POST['username']);
$passcode        = mysql_real_escape_string($_POST['passcode']);

if(empty($feedName)!="" && empty($feedUrl)!="") {

    $result = mysql_query("SELECT id,email,password FROM user WHERE email = '".$userName."'");
    $row = mysql_fetch_array($result);
    //echo $userName . $row['email'];
//  echo $passcode . $row['password'];
    if($row['email']== $userName && $row['password'] == $passcode && $row['email']!= "" && $row['password'] != "")  {
        echo $row['id'];

    }else{
        echo "fail";
    }
} else {
echo "All fields are mandatory!";
}
}
catch(Exception $e)
{
// normally we would log this error
echo $e->getMessage();
} 

How do i allow CROSS DOMNAIN POST, i know i have to edit my server php file and i have added the following code but i dint work either

switch ($_SERVER['HTTP_ORIGIN']) {
case 'http://localhost/rss': case 'https://localhost/':
header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']);
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');
break;
}

Using Firebug i say my $.POST and this is that i have

ResponseHeaders RequestHeaders Content-Type application/x-www-form-urlencoded; charset=UTF-8 Accept /

Parametersapplication/x-www-form-urlencoded passcode asd username qwe Source username=qwe&passcode=asd

Response

The response is always blank. It works when all the html and php is in the localhost or in my test server. My php and jquery skills are lacking atm so finding it very hard to understand also if someone else has already asked the question i am sorry for repeating. Ty for you help

Vao Tsun
  • 47,234
  • 13
  • 100
  • 132
Surja
  • 83
  • 1
  • 1
  • 7
  • Maybe you can use getJSON from jQuery as crossdomain request. – machineaddict May 30 '13 at 08:24
  • How can i send data with getJSON i need to send username and password (Got it) – Surja May 30 '13 at 08:30
  • Don't do that! Now I see what you are trying to do. Make the ajax post to your own server, then that script makes a request to the remote server. – machineaddict May 30 '13 at 08:49
  • Alternatively, try [this](http://stackoverflow.com/questions/2510049/cross-domain-login-what-to-store-in-the-database) or [this](http://www.jasny.net/articles/simple-single-sign-on-for-php/) – machineaddict May 30 '13 at 08:51
  • I cant use any php in client side. The client-side is a phonegap application(Google phonegap). It shouldn't be that difficult i am sending a request from my cellphone app to my server which stores user login information. – Surja May 30 '13 at 10:01
  • This is exactly what I said before. Let me explain again: your website is www.mywebsite.com. client bob enters your website www.mywebsite.com and clicks the login. the form posts the data with ajax to your website www.mywebsite.com. the website www.mywebsite.com send the data as a request to the server www.myusers.com which contains the user data, then the server www.myusers.com responds that the user has entered the correct credentials, then your website www.mywebsite.com logs in the user. the end. If any doubt, read the links I provided above. – machineaddict May 30 '13 at 11:28
  • Ty machineaddict i finally understand what you mean. I am trying to incorporate it in my solution. BTW i finnaly got my thing to work here is how: – Surja May 31 '13 at 09:45

1 Answers1

1

Changes i had to make: Client Side: something.html

$(document).ready(function() {
$("#login").click(function(e){      
    var formData = $("#loginForm").serialize();      

var username;
var passcode;
username= document.getElementById('username').value;
passcode = document.getElementById('passcode').value;



    if (window.XMLHttpRequest)
    {// code for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp=new XMLHttpRequest();
    }
    else
    {// code for IE6, IE5
        xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
    }
        xmlhttp.onreadystatechange=function()
    {
    if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
        var txt;
        txt=xmlhttp.responseText;
        //alert(txt);
        localStorage.setItem("background", txt);
        document.location.href="logged.html";
    }
}
xmlhttp.open("GET","http://testserver.bscheme.com/rss/login.php?username="+ username +"&passcode="+ passcode,true);
xmlhttp.send();

});




});   

Changes to file on Server: Login.php

<?php


header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type');


include('inc/db.php');

try
{
$userName       = mysql_real_escape_string($_GET['username']);
$passcode        = mysql_real_escape_string($_GET['passcode']);

if(empty($feedName)!="" && empty($feedUrl)!="") {

    $result = mysql_query("SELECT id,email,password FROM user WHERE email = '".$userName."'");
    $row = mysql_fetch_array($result);
    //echo $userName . $row['email'];
//  echo $passcode . $row['password'];
    if($row['email']== $userName && $row['password'] == $passcode && $row['email']!= "" && $row['password'] != "")  {
        echo $row['id'];

    }else{
        echo "fail";
    }
} else {
echo "All fields are mandatory!";
}
}
catch(Exception $e)
{
// normally we would log this error
echo $e->getMessage();
}

All i had to do was make sure the server accepted all kinds of header and the client sends a XMLHttpRequest and get the html response back instead of $.Ajax();

Surja
  • 83
  • 1
  • 1
  • 7