SitePoint Sponsor

User Tag List

Results 1 to 14 of 14

Thread: Ajax and PHP

  1. #1
    SitePoint Zealot
    Join Date
    Apr 2007
    Location
    New London, CT
    Posts
    172
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Ajax and PHP

    I am trying to get a page to accept a javascript onclick event. When you click the link, the page will dynamically update and bring up a form. You can then enter data into the form which will in turn update a section of the page.

    I have so far been able to get the page to bring up the form, however when you enter the data into the form and submit it, NADA! Can someone please take a look and tell me what I am missing?

    My New event for is this -- and I do plan on getting rid of the tables for the layout, which shouldn't affect the functionality:

    PHP Code:
    <?php

        
    if($_GET['error'] == 1) {
            echo 
    "<p><strong>There is an error in the form. Please correct it and re-submit.</strong></p>";
        }

    ?>
    <h1>Add a new event</h1>
    <form action="processnewevent.php?date=<?php echo $_GET['date']; ?>" method="POST">
    <table>
    <tr>
        <td>Date</td>
        <td>
        <?php echo "<strong>" date("D jS F Y"strtotime($_GET['date'])) . "</strong>"?>
        <input type="hidden" name="date" value="<?php echo $_GET['date']; ?>">
        </td>
    </tr>
    <tr>
        <td>Name</td>
        <td><input type="text" name="name" size="15"></td>
    </tr>
    <tr>
        <td>Start Time</td>
        <td>
        <select name="starthour">
        <?php
            
    for($i=0;$i<=23;$i++) {
                echo 
    "<option value=" sprintf("%02d"$i) . ">" sprintf("%02d"$i) . "</option>";
            }
        
    ?>
        </select>

        <select name="startminute">
        <?php
            
    for($i=0;$i<=60;$i++) {
                echo 
    "<option value=" sprintf("%02d"$i) . ">" sprintf("%02d"$i) . "</option>";
            }
        
    ?>
        </select>

        </td>
    </tr>
    <tr>
        <td>End Time</td>
        <td>
        <select name="endhour">
        <?php
            
    for($i=0;$i<=23;$i++) {
                echo 
    "<option value=" sprintf("%02d"$i) . ">" sprintf("%02d"$i) . "</option>";
            }
        
    ?>
        </select>

        <select name="endminute">
        <?php
            
    for($i=0;$i<=60;$i++) {
                echo 
    "<option value=" sprintf("%02d"$i) . ">" sprintf("%02d"$i) . "</option>";
            }
        
    ?>
        </select>

        </td>
    </tr>
    <tr>
        <td>Description</td>
        <td><textarea cols="15" rows="10" name="description"></textarea></td>
    </tr>
    <tr>
        <td></td>
        <td><input type="submit" name="submit" value="Add Event"></td>
    </tr>
    </table>
    </form>
    This is my form processing script:

    PHP Code:
    <?php
        
    require("dbConnect.php");

        if(empty(
    $_POST['name'])) {
            
    $error 1;
        }

        if(empty(
    $_POST['description'])) {
            
    $error 1;
        }
        
        if(
    $_POST['starthour'] > $_POST['endhour']) {
            
    $error 1;
        }

        if(
    $_POST['starthour'] == $_POST['endhour']) {
            
    $error 1;
        }

        if(
    $error == 1) {
            
    header("Location: " $basedir "view.php?error=1&eventdate=" $_GET['date']);

            exit;
        }

        
    $elements explode("-"$_POST['date']);
        
    $redirectdate $elements[1] . "-" $elements[0];

        
    $finalstart $_POST['starthour'] . ":" $_POST['startminute'] . ":00";
        
    $finalend $_POST['endhour'] . ":" $_POST['endminute'] . ":00";
            
        
    $inssql "INSERT INTO events(date, start, end, name, description) VALUES("
        
    "'" $_POST['date']
        . 
    "', '" $finalstart
        
    "', '" $finalend
        
    "', '" addslashes($_POST['name'])
        . 
    "', '" addslashes($_POST['description'])
        . 
    "');";

        
    mysql_query($inssql);
        
        
    header("Location: " $basedir "view.php?date=" $redirectdate);        

    ?>
    I know this is probably gonna be a huge code wall, and I am sorry for that but, I would still appreciate any help.

    Thanks in advance,

  2. #2
    SitePoint Wizard lorenw's Avatar
    Join Date
    Feb 2005
    Location
    was rainy Oregon now sunny Florida
    Posts
    1,100
    Mentioned
    2 Post(s)
    Tagged
    0 Thread(s)
    http://impliedbydesign.com/super-aja...ming-seed.html

    play with this, it is the http request that makes it work, you can totally rework it to do what you want.

  3. #3
    SitePoint Zealot
    Join Date
    Apr 2007
    Location
    New London, CT
    Posts
    172
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for the response lorenw. I already have an XHRequest.
    Code JavaScript:
    // JavaScript Document
     
    function createXHRObject() {
     
    	var req;
    	var browser = navigator.appName;
     
    	if (browser == "Microsoft Internet Explorer") {
     
    		req = new ActiveXObject("Microsoft.XMLHTTP");
     
    	} else {
     
    		req = new XMLHttpRequest();
     
    	}
     
    	return req;
     
    }
     
    var http = createXHRObject();
     
    function getEvent(eventid) {
     
    	http.open('get', 'internal_request.php?action=getEvent&id=', + eventid);
     
    	http.onreadystatechange = handleEvent;
     
    	http.send(null);
     
    }
     
    function handleEvent() {
     
    	if (http.readyState == 4) {
     
    	var response = http.responseText;
     
    	document.getElementById('eventBox').innerHTML = response;
     
    	}
     
    }
     
    function newEvent(eventdate, error) {
     
    	http.open('get', 'neweventform.php?date=' + eventdate + '&error=' + error);
     
    	http.onreadystatechange = handleNewEvent;
     
    	http.send(null);
     
    }
     
    function handleNewEvent() {
     
    	if(http.readyState == 4) {
     
    	var response = http.responseText;
     
    	document.getElementById('eventBox').innerHTML = response;
     
    	}
     
    }

    I don't mean to sound ungrateful but the link you gave returned a bunch of errors on the demo page.

  4. #4
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Why don't you post your form via AJAX? And where are you sending the values of your form? I still suggest you to post your form.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  5. #5
    SitePoint Addict CVPer's Avatar
    Join Date
    Sep 2007
    Location
    Vancouver, BC, Canada
    Posts
    233
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    in file view.php
    PHP Code:
    <form action="processnewevent.php?date=<?php echo $_GET['date']; ?>" method="POST">
    you don't need the part ?date=<?php echo $_GET['date']; ?> because you already set date as a hidden input in the form.

    in file processnewevent.php:
    PHP Code:
    header("Location: " $basedir "view.php?error=1&eventdate=" $_GET['date']); 
    you should use $_POST['date'], not $_GET['date']
    * @location Vancouver, BC, Canada
    * @name Steve
    * @job PHP/MySQL, Drupal, WordPress Developer

  6. #6
    rajug.replace('Raju Gautam'); bronze trophy Raju Gautam's Avatar
    Join Date
    Oct 2006
    Location
    Kathmandu, Nepal
    Posts
    4,013
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Steve:
    Did you see the request method in ajax is "get"
    Code javascript:
    http.open('get', 'internal_request.php?action=getEvent&id=', + eventid);
    ???
    So i think the form is to be posted.
    Mistakes are proof that you are trying.....
    ------------------------------------------------------------------------
    PSD to HTML - SlicingArt.com | Personal Blog | ZCE - PHP 5

  7. #7
    SitePoint Zealot
    Join Date
    Apr 2007
    Location
    New London, CT
    Posts
    172
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    @Steve

    I am still getting the same thing. Nothing happens when I submit the form. The events don't update on the page and the database doesn't receive any new data.

    @rajug

    I believe the form is using the method POST to send the data. Are you saying I should be using the $_POST variable in my internal request processing script? If not then I am unclear as to what you mean. Could you clarify a bit more for me?

  8. #8
    SitePoint Addict
    Join Date
    Aug 2007
    Location
    GR
    Posts
    352
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Give me a minute to eat :S and I will post a working example of ajax/php post. I use it in all my ajax things.

  9. #9
    SitePoint Zealot
    Join Date
    Apr 2007
    Location
    New London, CT
    Posts
    172
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    What you are hungry? No time for food this is programming dammit!!! LOL j/k thanks for taking the time to help me, as I appreciate any help and knowledge you are willing to give me.

  10. #10
    SitePoint Addict
    Join Date
    Aug 2007
    Location
    GR
    Posts
    352
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    OK, I set up a quick minimal example. Uses 3 pages and implies that all of them exist in the same level directory.

    • Page 1, the HTML (new_event.php)

    HTML Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script type="text/javascript" src="ajax.js"></script>
    </head>
    <body>
    <form name="form1" method="post" action="" id="event_form">
    	<input type="text" name="fname" value="" /><br />
        <input type="text" name="comment" value="" /><br />
        <input type="button" name="action" value="Send" onclick="SubmitNewEvent('event_form', 'output');" />
    </form>
    <div id="output"></div>
    </body>
    </html>
    • Page 2, javascript (ajax.js)

    PHP Code:
    // JavaScript Document
    function InitAjax() {
        
    RequestObject false;
        if(
    window.XMLHttpRequest) {
            try {
                
    RequestObject = new XMLHttpRequest();
            } catch(
    e) {
                
    RequestObject false;
            }
        } else if(
    window.ActiveXObject) {
            try {
                
    RequestObject = new ActiveXObject("Msxml2.XMLHTTP");
            } catch(
    e) {
                try {
                    
    RequestObject = new ActiveXObject("Microsoft.XMLHTTP");
                } catch(
    e) {
                    
    RequestObject false;
                }
            }
        }
        return 
    RequestObject;
    }
    // -------------------------------------------------------------
    function SubmitNewEvent(form_iddiv_id)
    {
        
    xmlHttp InitAjax(form_iddiv_id);
        
    form document.getElementById(form_id);
        
    elem document.getElementById(div_id);
        
    xmlHttp.open("POST""processnewevent.php"true);
        
    xmlHttp.setRequestHeader("Content-type""application/x-www-form-urlencoded");
        
    xmlHttp.send(BuildPostVars(form));
        
    xmlHttp.onreadystatechange = function()
        {
            if(
    xmlHttp.readyState == 4)
            {
                
    elem.innerHTML xmlHttp.responseText;
                
    xmlHttp.close;
                
    xmlHttp null;
            }
         }
    }
    // -------------------------------------------------------------
    function BuildPostVars(form)
    {
        return 
    str 'fname=' form.fname.value '&comment=' form.comment.value;

    • Page 3, the PHP (processnewevent.php)

    PHP Code:
    <?
    // just return the values!
    echo 'First name: '.$_POST['fname'].'<br />';
    echo 
    'Comment: '.$_POST['comment'];
    ?>
    It's a simple ajax call that just returns to the calling page the post vars.

    Cheers

  11. #11
    SitePoint Zealot
    Join Date
    Apr 2007
    Location
    New London, CT
    Posts
    172
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you Steve. So my understanding of this code, is that it is not too dissimilar from what I have now.

    The main difference is that you are using the POST method to send the data to be processed by processnewevent.php. Also, I am not building this for browsers older than IE6 so I am guessing it is not necessary for me to generate a request object for those browsers, which I do not.

    Lastly, on the processnewevent.php page I should be able to send a query to my database to input the data received from the form.

    Am I correct in my assumptions?

  12. #12
    SitePoint Addict
    Join Date
    Aug 2007
    Location
    GR
    Posts
    352
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Yes, the processnewevent.php file works like the file that you would post with the form.

    For the other browser, there is not a problem checking it. You can leave it there for portability.

  13. #13
    SitePoint Zealot
    Join Date
    Apr 2007
    Location
    New London, CT
    Posts
    172
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Ok, thanks. I will give this a shot and post back with any further questions.

  14. #14
    SitePoint Zealot
    Join Date
    Apr 2007
    Location
    New London, CT
    Posts
    172
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Hey thanks alot Steve. I got it working.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •