Advertisement
Help Keep Boards Alive. Support us by going ad free today. See here: https://subscriptions.boards.ie/.
If we do not hit our goal we will be forced to close the site.

Current status: https://keepboardsalive.com/

Annual subs are best for most impact. If you are still undecided on going Ad Free - you can also donate using the Paypal Donate option. All contribution helps. Thank you.
https://www.boards.ie/group/1878-subscribers-forum

Private Group for paid up members of Boards.ie. Join the club.

PHP response

  • 15-07-2013 10:05PM
    #1
    Registered Users, Registered Users 2 Posts: 302 ✭✭


    Hi guys,

    I'm new to PHP and I'm stuck on something which seems quite simple.

    After entering data into an input field I have to generate a response for the ajax request. I have the ajax code down but the php has me confused as I am not exactly sure what I am supposed to see in the console log on firebug.

    Here's my code:
    AJAX:

    var email = $('#subscribe-textarea').val();

    var varData = 'email: ' + email;
    console.log(varData);

    $.ajax({
    type: "POST",
    url: 'example.php',
    data: varData,
    success: function() {
    alert("It was a success");
    }
    });

    PHP:

    $email = $_POST;
    $url = 'example@example.com';

    $request = new httpRequest($url, HTTP_METH_POST);
    $request->setRawPostData ($email);
    $request->send();
    $response = $request->getResponseBody();

    The url is just a page with "Hello world" in the body.

    What exactly should I expect the result to be and how will I know if the request was successful?

    Any help is appreciated!


Comments

  • Registered Users, Registered Users 2 Posts: 17 dxter


    what do you get for $response. Just use var_dump($reponse); on the last line.


  • Registered Users, Registered Users 2 Posts: 1,127 ✭✭✭smcelhinney


    Ok, a few things..

    Im assuming you're trying to send an email? Not sure that PHP script will work for that, you normally need to use a mail transport protocol, or a library such as sendmail. That aside, however..

    Assuming the PHP works fine, you can echo a string on the page, using "echo 'Success'". My understanding of the $.ajax jQuery lib is that it only processes a success callback when the Http response code is 200 (OK). If there are errors with your script, this should fail. You can capture the fail outcome too, and do something else. Also, if you use
    success: function(res){
       console.log(res);
    }
    
    this might give you more info about the data sent back from the script.

    However, you might want to take it further, and in the PHP, pass back a JSON-encoded object, that you can then query on the client side. This allows you more flexibility with error handling, success messages etc.

    HTH
    Stephen


Advertisement