Hello, the functions are called in the XHR (status 200) but dont return anything as it should,. Even when i put an echo it doesnt return the echo. The path is correct

example

javascript

function userDetails(uid,apiBaseUrl,baseUrl,public_username,msgID,groupID)
{
    var encodedata=JSON.stringify({"uid": uid,"public_username":public_username,"msgID":msgID});
    var url;
    url=apiBaseUrl+'api/publicUserDetailsTest';

    ajaxPost(url,encodedata, function(data) {

        if(data)
        {
         some code....
        }
    });
}

When i put an alert before ajaxPost(url,encodedata, function(data) it alerts, if i put it after this line it DOESNT

PHP

function publicUserDetailsTest() {
  echo 'xxxx';
}

Dani AI

Generated

Short summary of the likely causes and a focused checklist based on ’s observations and ’s suggestion to test the endpoint externally.

The most common root cause here is a mismatch between what the client expects (JSON) and what the server actually sends. jQuery’s dataType: "json" will attempt to parse the response as JSON and will call the error handler if parsing fails; Postman’s “JSON Unexpected ' '” plus a 2‑byte body strongly suggests the response is either empty, contains stray whitespace or non‑JSON text, or the PHP handler isn’t being reached at all. A 304 on unrelated assets simply indicates caching and can hide edited JS during debugging.

Practical, ordered checks and fixes:

  • Inspect the Network panel and view the raw response text (not the parsed view). Confirm exact bytes returned.

  • Temporarily remove dataType: "json" (or set it to "text") so the raw response can be examined client‑side.

  • Replace the current AJAX error handler with one that logs everything so the real error and responseText are visible:

    error: function(jqXHR, textStatus, errorThrown) {
      console.log('AJAX error', textStatus, errorThrown, jqXHR.status, jqXHR.responseText);
    }
  • Call the endpoint from the command line to see raw headers/body:

    curl -v -X POST -H "Content-Type: application/json" -d '{"uid":1}' http://host/api/publicUserDetailsTest
  • On the PHP side, return well-formed JSON and no leading/trailing output (no BOM, no stray newlines). Example of a minimal response:

    <?php
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(['ok' => true]);
    exit;

Additional notes: if the server expects form data, sending raw JSON will leave $_POST empty — use file_get_contents('php://input') and json_decode on the PHP side. Check server error logs and remove any closing ?> and extra whitespace in included files. Once the raw response is valid JSON and visible via curl/Postman, restore dataType: "json" and re-enable normal error handling.

Recommended Answers

All 12 Replies

Your post doesn't make a lot of sense. What functions don't return anything? Where is ajaxPost defined? Does your API call actually work? Try accessing your API via another program like Postman or HTTPie.

Every single function doesnt return
I call a js file that contains this to call the ajaxPost

function ajaxPost(url, encodedata, success)
{
$.ajax({
type:"POST",
url:url,
data :encodedata,
dataType:"json",
contentType: 'application/json',
cache:false,
timeout:50000,
beforeSend :function(data) 
{ 
$(".scrollMore").attr("rel","0"); 
$("#networkError").slideUp("slow"); 
},
success:function(data){

success.call(this, data);
$(".scrollMore").attr("rel","1"); 
},
error:function(data){
$("#networkError").show().html($.networkError);
}
});
}

API call? You mean if the path is correct? I dont hav anything on the php function just an echo xxx;

Ok, so if you run this with your browser's developer tools open, what errors do you see in the console?

Nothing not one error or even a warning...

I think that the problem is that it never reaches the php functions. Otherwise it would returt the response right?

BUT THEN AGAIN IT A 200 OK STATUS

/ i am getting a 304 status on some of the files that i call Why is that

Like I said, access your API (even if it is only one function that returns {"hello": "world"}) using something less complicated. The tools I mention above are a good start. When you know that is working correctly and your url param is right, your server is listening on the right port etc, then integrate your JS.

I am getting nothing on Postman too. Response nothing. What should i do?

JSON Unexpected ' '

Access-Control-Allow-Origin →*
Cache-Control →no-store, no-cache, must-revalidate, post-check=0, pre-check=0
Connection →Keep-Alive
Content-Length →2
Content-Type →text/html; charset=UTF-8
Date →Sun, 27 Aug 2017 13:44:19 GMT
Expires →Thu, 19 Nov 1981 08:52:00 GMT
Keep-Alive →timeout=5, max=100
Pragma →no-cache
Server →Apache/2.4.17 (Win32) OpenSSL/1.0.2d PHP/5.6.20
Set-Cookie →PHPSESSID=rkjiogq3c49dku2usukt176bs0; path=/
X-Powered-By →PHP/5.6.20

Hard to tell what's going on without knowing what your server is doing and that you're sending requests to the port it's listening on.

Here's what I'd do, substitute my Ruby for your PHP. First, create a standalone, super-simple API. Here's an example

require 'sinatra'
require 'json'

# world's simplest API
get '/hello' do
  {hello: "world"}.to_json
end

Now, when I run that file in Ruby, it tells me where it's listening.

== Sinatra (v2.0.0) has taken the stage on 4567 for development with backup from Puma

Finally, I just need to make a sensible request:

http get localhost:4567/hello

And here's the response.

HTTP/1.1 200 OK
Connection: Keep-Alive
Content-Length: 17
Content-Type: application/json
Date: Sun, 27 Aug 2017 17:22:05 GMT
Server: WEBrick/1.3.1 (Ruby/2.4.1/2017-03-22)
X-Content-Type-Options: nosniff

{
    "hello": "world"
}

Now, the browser hasn't been involved at all. Everything's simple and visible. If something goes wrong I'll get the feedback right in my terminal window. PHP supports this approach too.

i am getting an error "/hello"' (T_CONSTANT_ENCAPSED_STRING) in your code on line 5

function publicUserDetailsTest() {
  require 'sinatra';
    require 'json';
    # world's simplest API
    get "/hello" do
      {hello: "world"}.to_json
    end
    }

The code I provided is in an entirely different language, you can't just paste Ruby into PHP!

Maybe ignore JavaScript for a while and learn PHP first.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.