How to post form data to database using Ajax

I am trying to post the form data to api.php using jQuery Ajax method. We need to use jQuery’s post() method, serialize the form data. Any help will be huge. Thanks in advance. Here are the files the index.php file cannot be formatted:

index.php file:

The Best Musicians and Bands

  <div class="form-container">
    <h2>Add a New Artist:</h2>
    <!-- Note that we're not using the action to submit this form. -->
    <form action="" method="post">

        <label>
          Name:
          <input type="text" name="name">
        </label>
        <label>
          Description:
          <textarea name="description"></textarea>
        </label>
        <label>
          Embed code for player:
          <textarea name="player"></textarea>
        </label>
        <input type="submit" value="submit">

    </form>
  </div>

  <div class="chooser-container">
    <h2>Choose an Artist to Listen to:</h2>
    <ul class="chooser">
      <!-- Populate this using AJAX -->
    </ul>
  </div>

  <div class="band-info">
    <h2></h2>
    <p></p>
    <div class="player-container">
      <!-- Populate this using AJAX -->
    </div>
  </div>
</div>

The api.php file:

<?php

require “db.php”;
$pdo = db_connect();

// Handle form submissions
if($_SERVER[“REQUEST_METHOD”]== “POST”)

{
$sql = ‘INSERT INTO bands (name, description, player) VALUES (:name, :description, :player)’;

  $statement = $pdo->prepare($sql);

  $statement->bindValue(':name', $_POST['name']);
  $statement->bindValue(':description', $_POST['description']);
  $statement->bindValue(':player', $_POST['player']);
  $statement->execute();

  $pdo = null;

}

if($_SERVER[“REQUEST_METHOD”]==“GET”) {

if(isset($_GET[‘bands’]))
{
//TODO get list of bands from database

}

if(isset($_GET[‘id’]))
{
//TODO get band with a particular id from the database
}
}

api.js file:

$(function(){

// output list of bands
the_band_list();

$(‘form’).on(“submit”, function(event){

event.preventDefault();

// TODO use AJAX post request to submit data.

var name = $('.wrapper').find('.form-container form').children().eq(0).children().val();
//var name = $('#name').val();



 $.post('api.php', $('form').serialize(), 

      function(data)
      {
            console.log(data);
            $('.choose-container').html(data);

      }
  );

});

and now? is this a job offer?

No, it is not for job

Sponsor our Newsletter | Privacy Policy | Terms of Service