开发者

Redirection with JQuery to PHP page not transmitting form content

开发者 https://www.devze.com 2023-03-26 08:55 出处:网络
I\'ve created a webpage which uses JQuery to redirect the content of a form to another webpage using PHP to connect to a database to find some content. Unfortunately the content of the form is not tra

I've created a webpage which uses JQuery to redirect the content of a form to another webpage using PHP to connect to a database to find some content. Unfortunately the content of the form is not transmitted properly because I get "Notice: Undefined index: postal_code in C:\wamp\www\mywebsite\target.php on line 8"

my code :

home.html

<!DOCTYPE html>
<html>
<head>
  <script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
  <form action="/" id="myform">
   <input type="text" name="postal_code" placeholder="Search..." />
   <input type="submit" value="Search" />
  </form>
  <!-- the result of the sear开发者_StackOverflow社区ch will be rendered inside this div -->
  <div id="result"></div>

<script>
$('#myform').submit(function() {
   var url = 'target.php';
   var postal_code = $('#postal_code').val();
   $.post( url, { postal_code: postal_code },
      function( data ) {          
          $( "#result" ).empty().append( data );
      }
    );
   return false;
});

target.php

<?php
try
{
   $pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
   $bdd = new PDO('mysql:host=localhost;dbname=mydatabase', 'root', '', $pdo_options);
   $response = $bdd->prepare('SELECT city FROM city_list where postal_code = ?');
   $response->execute(array($_POST['postal_code']));
   echo '<ul>';
       while ($data = $response->fetch())
       {
   ?>
          <br/>The city you entered the postal code is : <?php echo $data['city'];  
       }
       $response->closeCursor();
}
catch (Exception $e)
{
        die('Error : ' . $e->getMessage());
}
?>


You are searching for $('#postal_code').val();, however the input for postal_code has no ID.

Replace

<input type="text" name="postal_code" placeholder="Search..." />

With

<input type="text" name="postal_code" id="postal_code" placeholder="Search..." />

And it should work fine.

0

精彩评论

暂无评论...
验证码 换一张
取 消