-5

I have a select input with another submit input. i want to store selected value in a php array with every click on submit input without page reload. on clicking on add every time it will store the value of select input in an array of php. on 1st click the array will have only one value then in 2nd click on add the php array will have 2 value.

since I tried it with ajax, but when i clicking twice then only 2nd value is storing, 1st value is replacing by 2nd one. but i want both the values in the array. Here is my code: Html:

<select id = "exam-list" name = "exam_name">
   <option value="1">Opt 1</option>
   <option value="2">Opt 2</option>
   <option value="3">Opt 3</option>
 </select>

<input class="btn btn-primary" onclick="save_exam()" type="submit" name="submit" value="add"/> 

Js Code:

function save_exam() {var val = document.getElementById('exam-list').value;$.ajax({type: "POST",url: "store_exam.php",datatype: "json",data: 'exam_id=' + val,success: function (data) { }});} 

PHP code:

<?php $count = count($_POST['exam']);for ($i = 0; $i < $count; $i++)     {print_r($_POST['exam']);}?>
Matt
  • 74,352
  • 26
  • 153
  • 180

3 Answers3

2

Make an array in session put value after every click on that array. no other way i think is possible to store every value after click event.

 <?php 
$count = count($_POST['exam']);
for ($i = 0; $i < $count; $i++)   
  {
$_SESSION['exam'] = $_POST['exam']; 
}
?>

Something like this.

1

To save selected values without page refresh you have to use AJAX and the process will be something like:

HTML:

<form id="form_id">
    <select id = "exam-list" name = "exam_name">
       <option value="1">Opt 1</option>
       <option value="2">Opt 2</option>
       <option value="3">Opt 3</option>
    </select>
    <input class="btn btn-primary" type="submit" name="submit" value="add"/>
</form>

Note: wrap your select within a form tag

JavaScript:

<script>
    $('.btn').on('click',function(e) {
        e.preventDefault();

        var form_date=$('#form_id' ).serializeArray();

        $.ajax({
            url: "ajax.php",
            method: 'GET',
            data: form_date,
            success: function(response) {
                console.log(response);
            }
        });
    });

</script>

On ajax.php or whatever you name it, you will receive a $_GET array of passed data (actually, form data).

ajax.php

<?php
$data=$_GET;

 # You will receive a array like this
 #Array(
 #   [exam_name] => 1
 #)

//Do something with the data
Meathanjay
  • 2,023
  • 1
  • 18
  • 24
0

To store more than one value you should store value in array of session or cookie.

Shahadat Atom
  • 314
  • 2
  • 13