Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Basic PHP and AJAX

Tags:

ajax

php

We have a large PHP system that I am changing to OOP and want to use AJAX to update the web pages for logged in users. I am completely self taught and good on HTML, CSS and PHP with a basic Javascript understanding.

Trying to learn AJAX with PHP is defeating me. After trying a self made set of scripts to test AJAX which wouldn't work I then went to the Internet for examples and can't get any to work. This is on my development Mac running MAMP and using my host where we keep the current system.

My question is, does anybody have a simple 'hello world' set of HTML and PHP scripts that they know work which I could try to confirm that I can run something known.

Many Thanks Colin

like image 790
Colin Martin Avatar asked Mar 14 '11 12:03

Colin Martin


People also ask

What is PHP and AJAX?

AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Can I write PHP code in AJAX?

No, not directly, as JavaScript ist executed on the client side, and PHP is executed on the server. A workaround would be to send another AJAX-Request from your success-function. But it can only do things on the server side, not on the client side.

What is the difference between AJAX and PHP?

1. AJAX is a group of technologies that allows web applications to retrieve data from the server asynchronously; PHP is a scripting language designed to produce dynamic web pages. 2.

Is AJAX a PHP framework?

It is an open source framework written in PHP, used to develop/create/generate AJAX applications. The fundamental idea behind AJAX (Asynchronous Javascript and XML) is to use the XMLHttpRequest object to change a web page state using background HTTP subrequests without reloading the entire page.


1 Answers

Here's a basic example that uses jQuery, posting values from a form to a separate PHP file validates and returns results.

form.php

<html>

<head>
<title>Simple JQuery Post Form to PHP Example</title>
</head>

<body>

<!-- including jQuery from the google cdn -->
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js">      </script>

<!-- This div will be populated with error messages -->
<div id="example_form_error"></div>

<!-- This div will be populated with success messages -->
<div id="example_form_success"></div>

<!-- Here is your form -->
<div id="example_form_enter">
    <form id="contact_modal_form" method='post' action='form_post.php'>
            <label for="Name">Enter Your Name (Not "Adam"):</label> <input class='textbox' name='Name' type='text' size='25' required />
            <button class='contact_modal_button' type='submit'>Send</button>
    </form>
</div>

<!-- This div contains a section that is hidden initially, but displayed when the form is submitted successfully -->
<div id="example_form_confirmation" style="display: none">
    <p>
        Additional static div displayed on success.
        <br>
        <br>
        <a href="form.php">Try Again</a>
    </p>
</div>

<!-- Below is the jQuery function that process form submission and receives back results -->
<script>
    $(function() {
        $("#contact_modal_form").submit(function(event) {
            var form = $(this);
            $.ajax({
                type: form.attr('method'),
                url: form.attr('action'),
                data: form.serialize(),
                dataType: 'json',
                success: function(data) {
                    if(data.error == true) {
                        var error = $("#example_form_error");
                        error.css("color", "red");
                        error.html("Not " + data.msg + ". Please enter a different name.");
                    } else {
                        $("#example_form_enter").hide();
                        $("#example_form_error").hide();
                        $("#example_form_confirmation").show();

                        var success = $("#example_form_success");
                        success.css("color", "green");
                        success.html("Success! You submitted the name " + data.msg + ".");
                    }
                }
            });
            event.preventDefault();
        });
    });
</script>

</body>

</html>

form_post.php

<?php

    // Request Post Variable
    $name = $_REQUEST['Name'];

    // Validation
    if($name == 'Adam') {
    echo json_error($_REQUEST['Name']);
    } else {
    echo json_success($_REQUEST['Name']);
    };

    // Return Success Function
    function json_success($msg) {
        $return = array();
        $return['error'] = FALSE;
        $return['msg'] = $msg;
        return json_encode($return);
    }

    // Return Error Function
    function json_error($msg) {
        $return = array();
        $return['error'] = TRUE;
        $return['msg'] = $msg;
        return json_encode($return);
    }

?>
like image 56
admgvn Avatar answered Oct 05 '22 15:10

admgvn