SitePoint Sponsor

User Tag List

Results 1 to 4 of 4

Hybrid View

  1. #1
    SitePoint Enthusiast
    Join Date
    Jul 2012
    Posts
    69
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    understanding how ajax works

    Hey guys! This is my first time trying my hand at ajax and im just putting my foot in the water first. i'm trying to make it so when the form is submitted, the data is shown on the page. Here's the code:
    Code:
    $('document').ready(function () {
    
        $('form #submit').click(function(e){
            e.preventDefault();
            var formdata = $('form').serialize();
    
            $.ajax({
                type: 'POST',
                url:'ajax_recieve.php',
                data: formdata,
                dataType: 'html',
                success: function(data){
                    data.appendTo('footer');
                }
            });
        });
    
    });
    the php code:
    PHP Code:
    <?php
    if($_POST){
        return 
    "post sdssd";
    }
    ?>
    can someone help me with this code please?

  2. #2
    SitePoint Wizard bronze trophy chris.upjohn's Avatar
    Join Date
    Apr 2010
    Location
    Melbourne, AU
    Posts
    2,197
    Mentioned
    17 Post(s)
    Tagged
    1 Thread(s)
    When we use Ajax the golden rule for returning data is to echo it out like a normal PHP script as an Ajax connection doesn't see returned values, so in your case you would use the following:

    PHP Code:
    if (isset($_POST) && sizeof($_POST)) {
        exit(
    'Post was sent');

    You can also use echo as well but I personally like to use exit and it ends the script right there and then where as echo continues to use memory until the script exits itself or you tell it to, hope that helps.

  3. #3
    padawan silver trophybronze trophy markbrown4's Avatar
    Join Date
    Jul 2006
    Location
    Victoria, Australia
    Posts
    4,116
    Mentioned
    28 Post(s)
    Tagged
    2 Thread(s)
    Hi, does that script throw any errors?

    This looks wrong to me as data in your callback will be a HTML string in this case, so 'a string'.appendTo($('footer')) isn't valid javascript.
    Use console.log to debug what is happening along the way.
    Code:
    success: function(data){
      console.log(data);
      $('footer').append(data);
    }

  4. #4
    SitePoint Enthusiast
    Join Date
    Jul 2012
    Posts
    69
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    thanks guys! it works now.


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
  •