hameed badawy hameed badawy - 5 months ago 18
PHP Question

how to handle parameters passed with getJSON to json file

can I ask about the structure for check-email-address.json file, ajax request and the php file that will handle the emailAddress parameter

$.getJSON("/check-email-address.json", { emailAddress: $("#newEmailAddress").val() })

Answer

To allow PHP to do something, such as treating request parameters, you need a file with .php extension. However, this is not a problem. In your jQuery you can specify that PHP file as the source for your JSON. It does not need have the .json extension.

In PHP you would use the $_GET array to access the arguments like would do for any other page that receives arguments.

The script would look something like this -- this is just an example:

<?php
$email = $_GET['emailAddress'];
// We have some data...
$array = [ "address" => '1 baconstreet', "name" => 'John' ];
// Do something that influences the output based on argument
$array['mail'] = $email;
// Output JSON
header("Content-Type: application/json;charset=utf-8");
echo json_encode($array);
?>

If you save this file as check-email-address.php, you can call it like that in jQuery. You'll want to capture the response created by PHP, by providing a success callback function as third argument:

$.getJSON(
     "/check-email-address.php",
     { emailAddress: $("#newEmailAddress").val() },
     function (response) {
         // do something with the JSON:
         console.log(response);
     }
);