2

I'm having this headache now, since I've been having this problem the whole day and, still, can't fix it. I've looked on Google and StackOverflow for hours, tried many methods (including changing from JSON to JSONP, checking headers on PHP, localhost tests), asked friends, etc., and I'm still stuck. Maybe it's but a detail, I don't know.

I'm working on an Android mobile app, and for it, I have a PHP webservice on a hosting (let's say, example.com) that's working OK since I tested with with a PHP WS JSON client. Problem is I'm calling this WS now from a JS file on my computer using jQuery, JSON and Ajax, and I get the following response from Google Chrome's debugger console:

  • readyState: 4
  • statusText: "OK"
  • responseText: (what I need, no errors)

But on the response from the server, I always receive the Error callback, never the Success. I read it's because the server couldn't parse JSON correctly, but I don't really know.

I leave you my code.

From CLIENT.JS:

$.ajax({
    type: "POST",
    crossDomain: true,
    contentType: "application/json utf-8",
    dataType: "json",
    url: "http://www.example.com/ws/webservice.php/" + methodName,
    data: JSON.stringify(window.parameterArray),

    success: function (response)
        {
            alert('Success!');
            window.resultVar = "Success! " + response;
            console.log(response);
        },
    error: function (response)
        {
            alert('Error');
            window.resultVar = "Error: " + response;
            console.log(response);
        }
});

From SERVER.PHP:

<?php
header('Access-Control-Allow-Origin: *');  //I have also tried the * wildcard and get the same response
header("Access-Control-Allow-Credentials: true");
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Max-Age: 1000');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');
header('Content-type: application/json; charset=utf-8');

require_once "mobilefuncts.php";

$methodName = str_replace($_SERVER["SCRIPT_NAME"]."/", "", $_SERVER["REQUEST_URI"]);

if (isset($methodName))
{
   $param = (array)json_decode($HTTP_RAW_POST_DATA);

   $access = new MobileAccess();  //From mobilefuncts.php
   $result = call_user_func_array(array($access,$methodName), $param);   //Calls the method

   echo json_encode($result);
}
?>

Does anyone knows what can be done? Maybe, as I said before, the problem is but a detail. I don't know really, I'm kinda new to this kind of things.

Thanks in forehand!

UPDATE:

I just realized the Chrome console tells me this:

GET http://localhost:81/.../cordova_plugins.json 404 (Not Found)

Could it be the cause of the problem?

UPDATE 2:

Look here, I have a clue. I added more parameters to the error function, and got myself this result:

(The change in error is from function(response) to function(jqXHR, textStatus, errorThrown))

jqXHR.responseText: [an array with the info I'm asking]
errorThrown: "SyntaxError: Unexpected token"
Ignacio Téllez
  • 451
  • 4
  • 14

4 Answers4

0

Change

contentType: "application/json utf-8",

to

contentType: "application/json; charset=utf-8",

The malformation of your contentType header is causing your server to incorrectly interpret the content of your POST request.

Brad M
  • 7,857
  • 1
  • 23
  • 40
  • I'm sorry, Brad M, but this solution doesn't work. In fact, I changed that instruction trying to fix the problem, for I had it like that a couple of days ago. Thanks anyway! You gave me hope for a moment :) – Ignacio Téllez Dec 19 '13 at 16:12
0

Try to change the JQuery URL from :

http://www.example.com/ws/webservice.php/methodName

To:

http://www.example.com/ws/webservice.php?method=methodName

And then try to read it from the $_GET['method'] from PHP, I think this should be your problem

  • Nope, same result. Thing is the WS is acquiring the method correctly, but the callback is having trouble. The responseText is working, as it gets what I'm wanting, but it's coming on "error" callback instead of "success". Thanks anyway, Elhussein Hashem. – Ignacio Téllez Dec 19 '13 at 17:55
0

Just change your response to text and then parse the text as JSON, example:

var json = JSON.parse(data);

T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • I don't understand this approach. The only thing I can think about is to use JSON.parse (that, indeed, I must use somewhere) on the response, but problem is that parsing should be called inside success or error callback, isn't it? Thus it won't work, for whatever I do on success callback won't be happening. Am I getting this right? – Ignacio Téllez Dec 19 '13 at 19:00
  • I'm not following... do this in baby steps... if you can't get your SERVER to return JSON then I would simply move on and get the results as text and then parse to JSON, an error is an error is going to be text... I had similar issue where my ashx handler wasn't returning as JSON so I received it as a string and parsed it. – T McKeown Dec 19 '13 at 19:05
  • getting a 404 error means that some resource is not found.... is that cordova.json something you are loading??? – T McKeown Dec 19 '13 at 19:40
  • or is that URL that you are calling via AJAX? – T McKeown Dec 19 '13 at 19:41
  • Indeed it is, on the main file of the mobile app. It must be part of the file: – Ignacio Téllez Dec 19 '13 at 19:42
  • I just noticed something... is your ajax call going to a different server than the source? If yes I've done a lot of cross domain coding... you should should specify JSONP in your call. http://stackoverflow.com/questions/6809053/simple-jquery-php-and-jsonp-example – T McKeown Dec 19 '13 at 19:50
  • Yeah, indeed I am calling a different server. I never used JSONP because I was told it wasn't necessary. I'll take a look to it, then, but... if JSON isn't the right tool for this, why is it returning a valid responseText from the server? Thanks McKeown :D – Ignacio Téllez Dec 19 '13 at 19:54
  • oh, i thought it wasn't returning a valid response... ok, if you are getting a server generated message then you don't need jsonp. so now i'm confused, what is not working then? – T McKeown Dec 19 '13 at 19:56
  • Hmmm.... I'm getting an object from PHP WS, that includes, among other things, the correct responseText, status, etc. That response should make my JS client to launch the "success" callback, but it doesn't (launches "error" callback instead, always). And, as I put a while ago on my "Update 2" on the main post, the errorThrown in error callback acuses a "SyntaxError: Unexpected token". – Ignacio Téllez Dec 19 '13 at 20:00
  • well in your server are you generating a response that looks like: callback( yourJsonHere ); – T McKeown Dec 19 '13 at 20:01
  • T McKeown, you've given me the right answer, though I needed help from a friend to understand the JSONP logic, hehe. I'd like you to post the correct answer to give the proper reputation and thanks, as you deserve. Can you please do it? Otherwise is that I post what I just did to correct it, and somehow tag you on the answer... is that possible? – Ignacio Téllez Dec 19 '13 at 21:19
0

because you are doing cross domain calls you need to use JSONP. The PHP server must form a response that looks like this: callback( jsonSyntax);

T McKeown
  • 12,971
  • 1
  • 25
  • 32
  • Thanks, T McKeown! Indeed this was the solution to the problem. I'll give you the proper vote as soon as I get the 15 reputation points needed, hehe. Thanks again, and I hope I learned the lessson. – Ignacio Téllez Dec 19 '13 at 21:31