0

I'm new in php ajax and get two problem. The first problem, I want to save pairs of values (consist of value in text and it attribute) in an array every I click button. Is my method to push in array true? and the second, how I can access the array in php and insert to database? below is my HTML code

   <script>
        var a=0;
        var b=1;
        var tanya= new Array();
        var object = {};
        var pilgan= new Array();
        function question(){
            var x = $('#jenis').val();
            a++;
            if (x=="Multiple Choice") {
                $("select").css("display","none");
                alert("Pilihan :"+a);
                $('ol').append('<li><input type="text" name="tanya" id="thequestion" uruts="'+a+'" class="thequestion" style="color: black; width: 50%;"><button style="margin-left:10px;" id="tambah" class="tambah">Choice</button><div id="thechoice" class="thechoice"><input type="radio" id="pilihan"><input type="text" name="text" urutp="'+a+'" class="text" id="text"><br/></div></li>');
            }else if(x=="Essay"){
                $("select").css("display","none");
                $("#jenis").css("display:none;");
                $('ol').append('<li><textarea name="text" uruts="'+a+'" id="thequestion" style="color: black; width: 50%;"></textarea>');
            }
        }
        function uploadQuestion(){
            $.ajax({
                url     : "questionDosenAjax.php",
                type    : "POST",
                async   : false,
                data    : {
                    upload  : 1,
                    question : tanya,
                    choice : pilgan
                }, 
                success : function(res){
                    $('#coba').html(res);
                }
            });
        }
        $(document).ready(function(){
            $("#backMakeAss").click(function(){
                changePage("pilihanAssignAjax.php");
            });
            $('ol').on('click','button',function(){
                alert("Pilihan :"+a);
                //$pilgan.push(pilihan:$('#thechoice').val(), id:$('#thechoice').attr('urutp'))
                $(this).siblings('#thechoice').append('<input type="radio" id="pilihan"><input type="text" name="text" class="text" id="text" urutp="'+a+'"><br/>');
            });
            $("#kumpul").click(function(){
                object[$('#thequestion').attr('uruts')] = $('#thequestion').val();
                tanya.push(object);
                //$pilgan.push(pilihan:$('#thechoice').val(), id:$('#thechoice').attr('urutp'))
                uploadQuestion();
            });
            $('#add').click(function(){
                var id = $('#thequestion').attr('uruts');
                var value = $('#thequestion').val();
                object["id :"+id] ="value :"+value;
                tanya.push(object);
                //$.each(tanya, function (index, value) {
                    //alert({"id: "+value.id +" and value: "+ value.value});
                //});
                //$pilgan.push(pilihan:$('#thechoice').val(), id:$('#thechoice').attr('urutp'))
            });
        });
    </script>    

This is my php code, I don't know why it doesn't work.

<?php
    $con = mysqli_connect("localhost", "root", "", "lantern");
    if(isset($_POST['upload'])) {
        $pertanyaan = count($_POST['question']);
        $pilihan = $_POST['choice'];
        for($i=0;$i<sizeof($pertanyaan);$i++){
            echo $_POST['question'][$i+1]."\n";
        }
    }
?>

Thank you and sorry if my english not good.

HDJEMAI
  • 9,436
  • 46
  • 67
  • 93

1 Answers1

0

There are several issues with your code.

Firstly, you're generating multiple elements with the same ID (#thequestion). IDs are supposed to be unique. When you try to access the elements through jQuery later on it is not clear which element it is that you want. You could reference the elements by their (unique) uruts attribute like so:

$('.thequestion[uruts="' + number + '"])

, but it would probably be a better idea to give each thequestion element a unique ID like

<input type="text" name="tanya" id="thequestion_' + a + '" uruts="' +  a +'" class="thequestion" style="color: black; width: 50%;">

and then reference them as

$('#thequestion_' + number)

But since you never seem to be calling the question() function, it's not really clear to me where those elements are coming from in the first place. (It could be helpful if you also posted your HTML.)

Next, what you probably want in the event listener for #add instead of

object["id :"+id] ="value :"+value;

is just

object[id] = value;

or maybe (but I doubt it, because it's neither the way you do it in the #kumpul event listener (where you do it differently from here) nor does it seem to be what your php expects):

object[id] = {
    'id':       id,
    'value':    value
};

However, since you extend the object object every time the event is fired and then push the extended object into the tanya array, you push a new copy of the entire object in there every time, when what you really want is more likely just the new value. So

tanya[id] = value;

should be sufficient. Also it's not really clear to me why you do the pushing again in the event listener for #kumpul. Actually, it seems like you could just get rid of the object object altogether.

Then in your PHP, you could drop the $pertanyaan variable and rewrite

for($i=0;$i<sizeof($pertanyaan);$i++){
    echo $_POST['question'][$i+1]."\n";
}

as

foreach($_POST['question'] as $question){
    echo $question ."\n";
}

Your method is not necessarily wrong, it's just that there's an easier way to achieve the same thing. (Edit: actually it is wrong, I didn't look properly before. With $pertanyaan = count($_POST['question']); you already have an integer in $pertanyaan. You do not need to use sizeof on that. count and sizeof are aliases, they do exactly the same thing.)

(Also, google "PHP SQL injection" sometime. You really do not want to send user input to the database as-is, but I'll leave it at that for the moment. You mention a database so I'm assuming that's what you want to do with the $_POST data eventually.)

Then, in these two lines:

$("select").css("display","none");
$("#jenis").css("display:none;");

, the first line is the correct way to do this with jQuery, while the second one is incorrect and won't work.

Finally, is there any reason why your AJAX call needs to be synchronous (async: false in the settings)? This is generally discouraged these days (see https://stackoverflow.com/a/6685294/1901379).