chris3spice
chris3spice

Reputation: 183

PHP MYSQL Through Jquery Ajax: "Notice: Undefined index"

I have an administration form and when you click on a button it adds more answer fields that you can fill out. When the user clicks the add question it updates two tables the 'kumiquestions' table and the 'kumianswers' table.

It does this through ajax in jquery. It works to insert the question but as soon as I added the code to insert the answers I get these errors:

Notice: Undefined index: 
kid in Z:\xampp\htdocs\Kumihangul\admin\addquestion.php on line 4

Notice: Undefined index: 
kans in Z:\xampp\htdocs\Kumihangul\admin\addquestion.php on line 5

This is my Jquery:

$('#add-question-form').click(function() {
  //Varables to store form data
  var q_cat = $('#qtype').val();
  var q_lvl = $('#qlevel').val();
  var q_txt = $('#qtext').val();
  var q_quest = $('#qquest').val();
  var q_audio = $('#qaudio').val().replace("C:\\fakepath\\", "");
  var q_info = $('#qinfo').val();

  $.ajax({
    type: 'POST',
    url: 'addquestion.php',
    data: {qcat: q_cat, qlevel: q_lvl, qtext: q_txt, qquestion: q_quest, qaudio: q_audio, qinfo: q_info },
    success: function(data) {
        $('#temp').html(data);
    }
  });

    //insert answers and questions    
    var k_id = $(document).find('#lastautoinc').val();

    //loop through answer fields
    for (var i = 1; i <= answercounter; i++) {
        var k_ans = $(document).find('#qanswer'+i).val();
        $.ajax({
            type: 'POST',
            url: 'addanswer.php',
            data: {kid: k_id, kans: k_ans },
            success: function(data) {

            }

        });
    }
});

This is my addquestions.php

<?php
include '../conn/connect.php';
//Get Variables from AJAX POST
$k_id = $_POST['kid'];
$k_ans = $_POST['kans'];

//Make sure proper variables are INTs
(int) $k_id;

//SQL INSERT Statement
$sql = "INSERT INTO kumianswers (kumiquestionsid, answer) VALUES ('$k_id', '$k_ans');";

//Run QUERY
$lquery = $conn->prepare($sql);
$lquery->execute();
?>

Upvotes: 0

Views: 568

Answers (2)

Krish R
Krish R

Reputation: 22721

In your url: 'addquestion.php' ajax section, you have not passed the kid, kans parameters, rather you have passed in addanswer.php ajax section call. Thats is the reason you got the undefined index error.

data: {qcat: q_cat, qlevel: q_lvl ...

Upvotes: 1

GuyT
GuyT

Reputation: 4426

You have to check if the $_POST variables are filled. So, to correct your code:

In the addquestion.php:

$k_id = (isset($_POST['kid']) && $_POST['kid'] != null) ? $_POST['kid'] : '';
$k_ans = (isset($_POST['kans']) && $_POST['kans'] != null) ? $_POST['kans'] : '';

Upvotes: 0

Related Questions