RuFFCuT
RuFFCuT

Reputation: 317

Posting form data to PHP script and then Posting results back again

The below script fetches meta data on a list of URL's.

The URL's are inputted on my front end, I managed to get the data to another page (this script) but now instead of echo'ing the table onto the same page the script is on I want to feed that data back to my front end and put it in a nice table for the user to see.

How would I make the php script echo the data on another page?

thanks

Ricky

<?php
ini_set('display_errors', 0);
ini_set( 'default_charset', 'UTF-8' );
error_reporting(E_ALL);
//ini_set( "display_errors", 0);
function parseUrl($url){
    //Trim whitespace of the url to ensure proper checking.
    $url = trim($url);
    //Check if a protocol is specified at the beginning of the url. If it's not,     prepend 'http://'.
    if (!preg_match("~^(?:f|ht)tps?://~i", $url)) {
            $url = "http://" . $url;
    }
    //Check if '/' is present at the end of the url. If not, append '/'.
    if (substr($url, -1)!=="/"){
            $url .= "/";
    }
    //Return the processed url.
    return $url;
}
//If the form was submitted
if(isset($_POST['siteurl'])){
    //Put every new line as a new entry in the array
    $urls = explode("\n",trim($_POST["siteurl"]));
    //Iterate through urls
    foreach ($urls as $url) {
            //Parse the url to add 'http://' at the beginning or '/' at the end if not     already there, to avoid errors with the get_meta_tags function
            $url = parseUrl($url);
            //Get the meta data for each url
            $tags = get_meta_tags($url);
            //Check to see if the description tag was present and adjust output     accordingly
            $tags = NULL;
$tags = get_meta_tags($url);
if($tags)
echo "<tr><td>$url</td><td>" .$tags['description']. "</td></tr>";
else 
echo "<tr><td>$url</td><td>No Meta Description</td></tr>";
    }
}

?>

I think its best to use Ajax for this right? So it doesn't refresh

Upvotes: 0

Views: 1398

Answers (2)

NDBoost
NDBoost

Reputation: 10634

i prefer the ajax method as its much cleaner..

Whats important is the $.ajax(); and the echo json_encode()

Documentation

php manual for json_encode() - http://php.net/manual/en/function.json-encode.php

jquery manual for $.ajax(); - http://api.jquery.com/jQuery.ajax/

List of Response Codes - http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html

Example Code

Without seeing your HTML i'm guessing here.. but this should get you started in the right path for using ajax.

form html

<form action="<?= $_SERVER['PHP_SELF']; ?>" method="POST">
    <input type="text" name="siteUrl" id="siteUrl">
    <input type="submit" name="submit" value="submit" class="form-submit">
</form>

example-container

In your case, this is a table, just set the table ID to example-container

ajax

This requires you to use the jquery library.. If you use another library in additon called data tables, you can streamline a lot of this jquery appending of <tr>'s

// On the click of the form-submit button.
$('.form-submit').click(function(){
  $.ajax({
    // What data type do we expect back?
    dataType: "json",
    // What do we do when we get data back
    success: function(d){
      alert(d);
      // inject it back into a table called example-container
      // go through all of the items in d and append 
      // them to the table.
      for (var i = d.length - 1; i >= 0; i--) {
        $('#example-container').append("<tr><td>"+d[i].url+"</td><td>"+d[i].description+"</td></tr>");
      };

    },
    // What do we do when we get an error back
    error: function(d){
      // This will show an alert for each error message that exist
      // in the $message array further down.
      for (var i = d.length - 1; i >= 0; i--) {
        alert(d[i].url+": "+d[i].message);
      };
    }
  });
 // make sure to have this, otherwise you'll refresh the page.
 return false;
});

modified php function

<?php
//If the form was submitted
if(isset($_POST['siteurl'])){
    //Put every new line as a new entry in the array
    $urls = explode("\n",trim($_POST["siteurl"]));
    //Iterate through urls
    foreach ($urls as $url) {
        //Parse the url to add 'http://' at the beginning or '/' at the end if not     already there, to avoid errors with the get_meta_tags function
        $url = parseUrl($url);
        //Get the meta data for each url
        $tags[] = get_meta_tags($url);
     }
    if($tags):
        echo json_encode($tags);
    else:
        $message[] = array(
            'url' => $url,
            'message' => 'No Meta Description'
        );
                    // This sets the header code to 400
                    // This is what tells ajax that there was an error
                    // See my link for a full ref of the codes avail
                    http_response_code(400);
        echo json_encode($message);
    endif;
}

Upvotes: 1

Nick
Nick

Reputation: 6346

You would have to either:

1 - submit to the frontend page, including this PHP code on that page instead.

2 - Use AJAX to post the form, get the output and put it somewhere on the frontend page.

Personally, I'd use the first method. It's easier to implement.

Upvotes: 1

Related Questions