0

So I have a part of my form has the same 'Name' values that is going to be stored as an Array.

What I'm trying to do is to send the values into an AJAX and then to PHP to update my database.

The problem here is that I'm not sure on how to send the same input name values into the AJAX and allow my PHP to access these values.

Code is shown below.

EDIT: Note, I'm building a phonegap application so I cannot directly send the form to my php script.

EDIT 2: Added my php script explaining how the information is going to be handled.

HTML:

<form method="post">

    .
    . Other Input Forms
    .

    Subject: <br>
    <select id="pref_subject[]" name="pref_subject[]">
    <option value="0">Choose a Subject </option>
    <option value="1">English</option>
    <option value="2">A Math</option>
    <option value="3">E Math</option>
    <option value="4">Combined Science</option>
    </select>

    Subject: <br>
    <select id="pref_subject[]" name="pref_subject[]">
    <option value="0">Choose a Subject</option>
    <option value="1">English</option>
    <option value="2">A Math</option>
    <option value="3">E Math</option>
    <option value="4">Combined Science</option>
    </select>

    Subject: <br>
    <select id="pref_subject[]" name="pref_subject[]">
    <option value="0">Choose a Subject </option>
    <option value="1">English</option>
    <option value="2">A Math</option>
    <option value="3">E Math</option>
    <option value="4">Combined Science</option>
    </select>

    .
    . Other Input Forms
    .

    <button id="submit">Submit</button>
</form>

JQuery/Javascript:

$(document).ready(function(){

  $("#submit").on("click", function(e){
    e.preventDefault();

    $.ajax({
            url: serverURL + "/php/sendRequestProcess.php", 
            type:"POST", 
            data:{
                sd_given_name : $("#sd_given_name").val(),
                sd_family_name : $("#sd_family_name").val(),
                sd_email : $("#sd_email").val(),
                gender : $("#gender").val(),
                pref_edu_level : $("#pref_edu_level").val(),
                pref_subject :  $("#pref_subject[]").val(),
                pref_area : $("#pref_area").val(),
                estate : $("#estate").val(),
                requestPrice : $("#requestPrice").val(),
                lesson_hrs : $("#lesson_hrs").val(),
                lesson_amt : $("#lesson_amt").val()
            }
          })

  });

});

PHP:

Before the posting the values of 'pref_subject' I will be posting the other values in the Request table in order to the 'last_id'.

After getting the last id, I will then post the 'pref_subjects' into a second table.

    $connection = mysqli_connect($servername, $username, $password, $dbname);

  // Check connection
  if ($connection->connect_error) {
    die("Connection failed: " . $connection->connect_error);
  }

  $sd_given_name = addslashes($_POST["sd_given_name"]);
  $sd_family_name = addslashes($_POST["sd_family_name"]);
  $sd_email = $_POST["sd_email"];
  $gender = $_POST["gender"];
  $pref_edu_level = $_POST["pref_edu_level"];
  $pref_area = $_POST["pref_area"];
  $estate = $_POST["estate"];
  $requestPrice = $_POST["requestPrice"];
  $lesson_hrs = $_POST["lesson_hrs"];
  $lesson_amt = $_POST["lesson_amt"];

  $request_id;
  $pref_subject = $_POST["pref_subject"];

  $newRequest = "INSERT INTO Request (SD_Given_Name, SD_Family_Name, SD_Email, Gender, 
                               Pref_Edu_Level_ID, Pref_Area_ID, Estate, 
                               Request_Price, Lesson_Hrs, Lesson_Amt) 
          VALUES ('$sd_given_name', '$sd_family_name', '$sd_email', '$gender', 
                   $pref_edu_level, $pref_area, '$estate',
                   $requestPrice, $lesson_hrs, $lesson_amt)";



  if ($connection->query($newRequest) === TRUE) {
    $request_id = $connection->insert_id;
    //echo "New record created successfully. Last inserted ID is: " + $last_id;
  } 

  else {
    echo "Error: " . $newRequest . "<br>" . $connection->error;
  }

  for ($i = 0; $i < count($pref_subject); $i++) {
    if ($pref_subject[$i] > 0) {
      $addSubject = "INSERT INTO Request_Subject (Request_ID, Subject_ID)
      VALUES ($request_id, $pref_subject[$i])";

      $sendSubject = ($connection->query($addSubject));

      if ($sendSubject === FALSE) {
        echo "Error: " . $addSubject . "<br>" . $connection->error;
      }
    }
  }

  $connection->close();
ahfreak
  • 119
  • 2
  • 4
  • 11
  • Question: why not send the form to your PHP script? PHP runs, then header('Location: http://www.YOURWEBSITE.COM'); – ZenStein Jan 05 '15 at 06:38
  • @ZenStein Edited the post. I will be porting this code to a phonegap application and I don't think I can access the php script directly – ahfreak Jan 05 '15 at 06:42
  • 1
    `id's` should be unique, you could use `pref_subject_1` and so on. Then use the `name` part in the `selector` instead of the `id`(without []). – RST Jan 05 '15 at 06:45
  • you can iterate thorogh elements with the same name as in this question http://stackoverflow.com/questions/2505786/iterating-through-same-form-elements – Ekim Jan 05 '15 at 06:50
  • @Ekim I tried following the solution but how do I store the data in the Ajax for the pref_subject? – ahfreak Jan 05 '15 at 09:52

1 Answers1

0

You can send the same input name values into the AJAX

$("#submit").on("click", function(e){

    var form_data = $('#frm_id').serialize();
    $.ajax({
        type: "POST",
        url: serverURL + "/php/sendRequestProcess.php",
        data: form_data,
        dataType: "json",
        success: function(response){
            //data - response from server
        error: function (jqXHR, textStatus, errorThrown)
        {

        }
    });

});

form_data: can be an array or name value pairs.

success: callback function is called when the AJAX POST is successful

error: callback function is called when the AJAX POST is failed

To handle JSON data, set dataType=”json”

Ved
  • 2,701
  • 2
  • 22
  • 30
  • How do I handle the information that is being sent to the php then? – ahfreak Jan 05 '15 at 13:18
  • On php side get your data like $_POST['sd_given_name']...same like other field also and do process whatever you want. – Ved Jan 05 '15 at 13:24
  • Hi thanks. I somehow manage to make it work. Though can I ask what should I put in the success and error callbacks. Still new with ajax. – ahfreak Jan 06 '15 at 12:32
  • Ok, success you get response from server and if you get any error show alert in error callback. – Ved Jan 06 '15 at 12:42
  • in your php code put json_encode that you will get on client side as success response. – Ved Jan 06 '15 at 12:50