12

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

Colin Martin
  • 469
  • 2
  • 4
  • 7
  • 2
    You may find that using a javascript library like jQuery makes your AJAX a lot easier. Without seeing your current attempts it's hard to know if you are having browser compatibility issues or just everyday code problems. jQuery gets rid of most of the compatibility issues. – dnagirl Mar 14 '11 at 12:15

5 Answers5

16

If you are going to use AJAX I would recommend using jQuery as well. This greatly simplifies the process, is tested cross-browser and has many easy to use wrapper functions.

Its really as easy as creating a PHP page called hello.php

<?php
  echo "Hello World";
?>

Then in your main page you will need to grab the jQuery library and hook it up to the document ready event.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
     $(function(){
       $.get("hello.php", function(data){
           alert(data);
       });
    });
</script>

This in essence is the simplest AJAX hello world tutorial I know :)

The_Butcher
  • 2,440
  • 2
  • 27
  • 38
12

No not really, but I would recommend that you use jQuery if you're going to be doing any ajax at all. It will make your life so much easier.

Especially since all the browsers don't implement the ajax stuff the same way.

example application using jQuery+PHP for ajax calls:

I'm going to assume that you already have some base html document, I'm just going to include the important bits..

receiver.php:

<?php
echo 'you just received me, I\'m some PHP code and ajax is definitely working...';
?>

sender.html:

<p>Hello, click this button: <a id="button" href="receiver.php">Click me</a></p>
<p id="container"><!-- currently it's empty --></p>

<!-- 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>

<script type="text/javascript">
// This is our actual script
$(document).ready(function(){
    $('a#button').click(function(){
        $.ajax({
            url: this.href,
            type: 'GET',
            dataType: 'html',
            success: function (data) {
                $('#container').html(data);
            }
        });
    });
});
</script>

That should be all you need for a basic ajax application...

Community
  • 1
  • 1
arnorhs
  • 10,383
  • 2
  • 35
  • 38
  • Thanks so far. In the program I am working on I don't want to use jquery. The rest of the layout HTML and Javascript is working with my use of AJAX being a button in a row of buttons on one part of the page will selected and display the functional part of the page in a div on another part of the page. As far as I see it this should just need one AJAX script to call the function in a PHP script selected using the button id along with form data in $_POST. If I can write this once it's there and working without having to work out how jquery works it will be easier to maintain in future. – Colin Martin Mar 14 '11 at 15:09
  • @Colin - if you really want to use just plain javascript, you will need to read up on http://www.jibbering.com/2002/4/httprequest.html. The page will also show you how to create objects for IE and Firefox – The_Butcher Mar 14 '11 at 15:53
  • You're going to have a hard time with that. I used to do that before jQuery/prototype came along and I spent most of my time on the ajax implementation, instead of my application / ajax logic – arnorhs Mar 14 '11 at 16:45
  • 1
    There is a problem with your single quotes in your PHP code. – alecail May 06 '14 at 18:44
4

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);
    }

?>
admgvn
  • 41
  • 3
4

I would suggest using jQuery's AJAX methods, which are cross-browser and easy to use.

Alan Haggai Alavi
  • 72,802
  • 19
  • 102
  • 127
-2
if(!$mail->Send()) {
    //echo "Mailer Error: " . $mail->ErrorInfo;
    $data[0]=array('result'=>'Mail not send');
}elseif(!$mail1->Send()){
    //echo "Mailer Error: " . $mail->ErrorInfo;
    $data[0]=array('result'=>'Mail not send');
}else {
    $data[0]=array('result'=>'Mail Send');
}
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103