Redirect to Page after Post Submit

I have a form that submits post data to PHP function called search, the search function queries a table I added to the WordPress database. After the submit I would like to redirect to a results page that I added in the dashboard. So far I can only redirect using Ajax, but I would like to redirect from the PHP file.

Ajax

$('#finderForm').on('submit', function(e) {
  //e.preventDefault();

  var form = $('#finderForm').serialize();

  $.ajax({
    type: "POST",
    url: "wp-admin/admin-ajax.php?action=search",
    data: form,
    success: function (data) {
      console.log('Submission was successful.');
      console.log(data);
      console.log(window.location.href);
      //window.location.href="https://wordpress.stackexchange.com/questions/294543/?page_id=7=" + data;
    },
    error: function (data) {
      console.log('An error occurred.');
      console.log(data);
    },
  });
});

My Search Function in PHP File, I want to redirect from here:

   add_action("wp_ajax_search", "search");

   function search() {
      $name = $_POST['name'];

      $mydb = new wpdb('root','','i3264185_wp1','localhost');
      $query = "SELECT event_name FROM event WHERE event_name LIKE '$name%'";
      $result = $mydb->get_results($query);

      $result = json_encode($result);
      wp_redirect( home_url('/?page_id=7') ); 
      exit;
      echo $result;
      die();
   }

1 Answer
1

You can’t. If you wish to redirect a user by PHP, you should set the response header. If you output any data, you will not be able to, and you will get a Header already sent error.

Look at this line:

wp_redirect( home_url('/?page_id=7') ); 
exit;

echo $result;
die();

When you use exit ( which is the same as die() ), you are terminating the script. The next lines will never be executed. So my suggestion is to either use AJAX to redirect, or change your form to something like this:

<form action="<?php echo admin_url ( 'admin-ajax.php' ); ?>">

    <!-- This is to set the action of your query args -->
    <input type="hidden" name="action" value="search"/>

    <!-- Rest of your form here -->

</form>

Then, remove the line after exit and also the AJAX script, if you aren’t relying on it for something important.

Leave a Comment