user2896120
user2896120

Reputation: 3282

Ajax Post request not working?

I am trying to build a form where the user fills information in and clicks submit. Upon clicking, the page will never refresh. Form processing and data handling will happen after the user clicks.

I am trying to use jQuery and Ajax to accomplish this, so far this is what I have:

HTML

<form class="article_information_form" action="" method="POST"> 
  <label>Title </label> 
  <input type="text" name="articleTitle"> <br> 
  <label>Article URL: </label> 
  <input type="text" name="articleUrl"> <br>
  <p>Number of pages</p>
  <select name="numPages">
    <option value="" selected></option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
    <option value="6">6</option>
    <option value="7">7</option>
    <option value="8">8</option>
    <option value="9">9</option>
    <option value="10">10</option>
    <option value="11">11</option>
    <option value="12">12</option>
    <option value="13">13</option>
    <option value="14">14</option>
    <option value="15">15</option>
  </select>
  <br>
  <?php echo $message;?> //For Debugging
  <input type="submit" name="article_info_btn" value="Submit">
</form>

PHP

if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
    $message = "Success!"; //For debugging
}

Ajax

$(document).on('submit', '.article_information_form', function(e) {
    e.preventDefault();
  $.ajax({
    type : 'POST', 
    url  : '', 
    success :  function(data) {
        alert("Success!"); 
    } 
  }) 
})

Upon clicking the submit button, the success window popup alert is shown. Though, the $message variable never prints out "success!" This means that its not processing the PHP $_POST.

How do I make it so that Ajax sends the information to the PHP $_POST?

Upvotes: 1

Views: 1653

Answers (6)

Iceman
Iceman

Reputation: 6145

$( ".article_information_form" ).on( "submit", function( event ) {
  event.preventDefault();
  $.post(window.location , $( this ).serialize() , function(result){
        alert(result);
    });
});

You didnt attach the data payload!!

Since you wanted the entire thing to be on a single page, this would be a possible way:

Full code for easy understanding:

<?php
//exececuted only if POST request as in the ajax below.
if($_SERVER[ 'REQUEST_METHOD']==='POST' ){
    //your processing here
    header( 'Content-Type: application/json');
    //lets set the receivedToServer property to what data we got
    $data = array();
    $data['receivedToServer'] = $_POST;
    //output data as json
    echo json_encode($data);
    //kill the page once the data is displayed
    die(); 
} 
?>
<!DOCTYPE html>
<html>
<head>
    <title>TEST</title>
</head>
<body>
    <form class="article_information_form" action="" method="POST">
        <label>Title </label>
        <input type="text" name="articleTitle">
        <br>
        <label>Article URL: </label>
        <input type="text" name="articleUrl">
        <br>
        <p>Number of pages</p>
        <select name="numPages">
            <option value="" selected></option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
            <option value="11">11</option>
            <option value="12">12</option>
            <option value="13">13</option>
            <option value="14">14</option>
            <option value="15">15</option>
        </select>
        <br>
        <input type="submit" name="article_info_btn" value="Submit">
    </form>
</body>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
    $('.article_information_form').on('submit', function(e) {
        e.preventDefault();
        $.ajax({
            type: 'POST',
            url: '',
            data: $(this).serialize(),
            success: function(data) {
                //the processed data available as data variable. 
                //lets log the data received at server property we set before
                console.log(data.receivedToServer);
                alert(data.receivedToServer.articleTitle);
            }
        });
    })
</script>

</html>

Upvotes: 1

Bufaroosha
Bufaroosha

Reputation: 23

1- Your Ajax Code :-

<script>
    $(function() {

        $(".article_information_form").on("submit", function(event) {
            event.preventDefault();

            $.ajax({
                url: "process_page.php",
                type: "post",
                data: $(this).serialize(),

                success: function(html) {
                    $('#msg').html(html);
                }
            });
        });
    });

</script>

2- To print AJAX response add the following "div" under the "body" tag :-

##<div id='msg' ></div>

3- Create a PHP page "process_page.php" to receive the submitted data and then send the result

<?php
$numPages = $_POST['numPages'];
echo $numPages; //anything you echo here will be displayed in the <div id='msg'> at the main page
?>

good luck

Upvotes: 0

Labu
Labu

Reputation: 2582

Like the others have said, you need to add a data parameter to your $.ajax() call.

Your other question - reading the comments - is about how you can get the PHP $message variable to show up without a page load.

That is, unfortunately, impossible without a page-refresh because PHP is rendered on the server side.

What I would suggest, is creating another PHP file that handles the logic that you're trying to create, and then using AJAX to throw the response back onto the current page. Achieving what I believe you want to do.

So! Example time.

first.php

<!doctype html>
<html>
  <head><title>First</title></head>
  <body>
    <form id="myForm">
      <input name="email" type="email" />
      <button>Go!</button>
    </form>
    <div id="message"></div>
    <script>
      $('#myForm').on('submit', function(event){
        event.preventDefault();
        $.ajax({
          type: 'POST',
          data: $().serialize(); // send the form data to..
          url: 'second.php',     // your new PHP page
          complete: function(xhr, status){
            console.log('xhr', xhr);
            console.log('status', status);
            $('#message').text(status);
          }
        });
      });
    </script>
  <body>
</html>

second.php

<?php
  if (isset($_POST["email"]) {
    echo "Success!";
  } else {
    echo "Error!";
  }
?>

Upvotes: 0

Ismail RBOUH
Ismail RBOUH

Reputation: 10450

You need to add data to your ajax call:

$(document).on('submit', '.article_information_form', function(e) {
    e.preventDefault();
    $.ajax({

        type: 'POST',
        //url: '', by default is the current page url.
        data: $('.article_information_form').serialize(),//This line
        success: function(data) {
            $('.article_information_form type["submit"]').before("<div>"+data+"</div>")
        }
    })
})

PHP:

if (isset($_POST["articleTitle"], $_POST["articleUrl"], $_POST["numPages"])) {
    echo "Success!"; //For debugging
    exit();
}

Upvotes: 0

Fil
Fil

Reputation: 8863

On your form add an ID, in our case I put an id="form_submit" and action="action.php", you need to replace it with your own path where the action should do.

<form id="form_submit" class="article_information_form" action="action.php" method="POST"> 

also this line of the form,

<input type="button" id="submit" name="article_info_btn" value="Submit">

change the type type="bumit" to type="button" to prevent default submission.

and the jquery,

$('#submit').click(function() {
  var submit_url = $(this).parent('form').attr('action');
  $.ajax({
    type : 'POST', 
    url  : submit_url, 
    data : $('#form_submit').serialize(),
    dataType : 'json',
    success :  function(data) {
        alert("Success!"); 
    } 
  }) 
})

This line var submit_url = $(this).parent('form').attr('action'); get the path on the action="" and use that path to passed data.

Upvotes: 0

Kalu Singh Rao
Kalu Singh Rao

Reputation: 1697

You are not pass data to your method so it is not working. So first you will check how many argument have in method, then you send same number of string in params.

You should note one thing about argument are same name as use in method argument name.

$(document).on('submit', '.article_information_form', function(e)
             {
                e.preventDefault();
                 $.ajax({

                      type : 'POST',
                      url  : '',
                      params : {articleTitle: 'Titlename', articleUrl : 'URLName',numPages : 'PagesNo'}
                      success :  function(data)
                      {
                        alert("Success!");
                      }
                  })
             });

Upvotes: 0

Related Questions