Brett
Brett

Reputation: 3316

Beginner to JSON and PHP

Sorry about the simple question.

I am posting a JSON object to a PHP page using the following code:

    $.get("ProcessName.php", { name: "John" },
        function(data){
            alert("Data Loaded: " + data);
        });

What code do I need to write in ProcessName.php to have the alert show the name is John?

I realise I could process the JSON object on the client but this is a simple example to help me understand how PHP pages read JSON objects sent from the client. I have ready many questions and beginner tutorials but they all seem to skip this simple step or maybe I am missing something.

Thanks,

Upvotes: 1

Views: 218

Answers (3)

Salman
Salman

Reputation: 1380

In Javascript/JQuery if you want to access JSON you can write

data.name

if you want to get the posted value on the page you can get it 2 ways

$_POST['name'];

and

$_REQUEST['name'];

you can also include the following statement

if(isset($_POST['name']))
    echo "Name is ".$_POST['name'];

some people consider using $_REQUEST is bad practice, basically $_REQUEST checks the name in both $_POST and $_GET. To clear your concept you can click here.

Upvotes: 0

johniek_comp
johniek_comp

Reputation: 322

js:

 $.get("ProcessName.php", { name: "John" },
        function(data){
            alert("Data Loaded: " + data);
        });

ProcessName.php:

<?php

if($_GET['name'] == "John") {
    echo "This work!";
}

?>

or sleep

<?php

sleep(200); 

if($_GET['name'] == "John") {
    echo "This work!";
}

?>

or

<?php

echo $_GET['name'] == "John" ? "At works" : null;

?>

for example :) if you need append response to html use

$.get("ProcessName.php", { name: "John" },
        function(data){
            $("#append").html(data);
        });

your need create div id=append, for example! good luck!

Upvotes: 0

Kris
Kris

Reputation: 6112

In your ProcessName.php page, to alert John all you would need is

echo $_GET['name'];

Upvotes: 6

Related Questions