1

I hope you can understand my question. I am trying to make a generic ajax function that will send some data to a php file and get the server's response. There is a very similar question here jquery - creating a generic ajax function , however I am having some troubles sending the data in a json format. Let me provide you the JS code:

function CallMethod(url, parameters, successCallback) {
            $.ajax({
                type: 'POST',
                url: url,
                data: JSON.stringify(parameters),
                contentType: 'application/json;',
                dataType: 'json',
                success: successCallback,
                error: function(xhr, textStatus, errorThrown) {
                    console.log(errorThrown);
                }
            });
        }
var pars = {
    id:"1",
    message:"hello world"
};
function onSuccess(data) {
    console.log(data);
}
CallMethod('ajaxGeneric.php', pars, onSuccess);

And now here is my php file 'ajaxGeneric.php':

<?php

$id = $_POST["id"];
$msg = $_POST["message"];

echo $id;
echo $msg;
?>

When I run the page I have this error in the Chrome's console:

SyntaxError: Unexpected token < in JSON at position 0(…)

The php file seems also to have some problems trying to get the post values. What am I doing wrong? sending the data? getting the data back?

Any help will be greatly appreciated.

Community
  • 1
  • 1
Abraham
  • 23
  • 3
  • PHP does not understand JSON request content types, it will not automatically parse the request body into the $_POST global. – Patrick Evans Sep 20 '16 at 18:22
  • 1
    Try removing `JSON.stringify` and pass the parameters directly – Zeeshan Sep 20 '16 at 18:36
  • Hi @Zeeshan , suprisingly it worked, thank you so much. I didn't think the ajax syntax would understand it, but it did =). I wanted to mark your comment as the answer, however it is no possible but if you post it again as an answer I would have no problem to mark it. – Abraham Sep 22 '16 at 03:25
  • Thank you for the explanation @PatrickEvans , it's helped me a lot to understand the main reason of the issue. – Abraham Sep 22 '16 at 03:27
  • Yes i have added it as answer as it will help others in need,Kindly accept it – Zeeshan Sep 22 '16 at 06:51

1 Answers1

0

Try removing JSON.stringify and pass the parameters directly,So that your function will look like this

function CallMethod(url, parameters, successCallback) {
        $.ajax({
            type: 'POST',
            url: url,
            data: parameters,
            contentType: 'application/json;',
            dataType: 'json',
            success: successCallback,
            error: function(xhr, textStatus, errorThrown) {
                console.log(errorThrown);
            }
        });
    }
Zeeshan
  • 803
  • 6
  • 15