0

Good day, ive been reading all the possible questions and answers here in this site all day, i know im almost getting the right answer but it seems some of the suggestions here doesnt work for me. I have a dynamic form where the user can add and remove text fields and submit the request through ajax and php. The form consist of two required text field and buttons to add and remove another field(aside from the two required fields). The user can submit the form even not using another extra field.

My problem is if I press the add button and later on decide to remove it, I am getting a '0' value in corresponding table in database even after pressing the remove button.

Here is my HTML:

   <form method="POST">
    <span class="text-label">Subject:</span>
    <input type="text" name="subject" id="subject-field" placeholder="Subject name here" maxlength="10" class="record-input-forms" /> <span class="text-label">Section:</span>
    <input type="text" name="section" id="section-field" placeholder="Subject section here" maxlength="3" class="record-input-forms" /> <a href="#" class="add-field" title="Add student field">+</a> <a class="remove-field" href="#" title="Remove student field">&#215;</a> <a href="#" id="save-button" title="Save">&#8594;</a>
    <div id="student-box-wrap"></div> <span id="status-message"></span> </form>

Here is my AJAX

 $(document).ready(function() {
    $("#save-button").click(function() {
        var subject = $("input#subject-field").val();
        if (subject == "") {
            $('#status-message').css({
                "color": "#ec3f8c"
            });
            $('#status-message').html('Please fill the subject fields');
            return false;
        }
        var section = $("input#section-field").val();
        if (section == "") {
            $('#status-message').css({
                "color": "#ec3f8c"
            });
            $('#status-message').html('Please fill the section fields');
            return false;
        }
        var studid = [];
        $('input[name="studid[]"]').map(function() {
            studid.push($(this).val());
        });
        var dataString = 'subject=' + subject + '&section=' + section + '&studid=' + studid;
        $.ajax({
            type: "POST",
            url: 'save.php',
            data: dataString,
            dataType: "html",
            success: function(data) {
                $("input#subject-field").val('');
                $("input#section-field").val('');
                $("input#field-wrap").remove();
                $("#status-message").css({
                    "color": "#39b1c6"
                });
                $("#status-message").html('Save successfully');
                $("#status-message").fadeOut(2000);
            },
            error: function(xhr, ajaxOptions, thrownError) {
                alert(thrownError);
            }
        });
        return false;
    });
});

my Jquery counter

    $(document).ready(function() {
    var counter = 0;
    $(".add-field").click(function() {
        counter += 1;
        $("#student-box-wrap").append('<div class="field-wrap-' + counter + '"><span id="number-' + counter + '">' + counter + '.</span> Student ID: <input type="text" name="studid[]" class="record-input-forms" /></div>');
    });

    $(".remove-field").click(function() {
        if (counter == 0) {
            alert("Nothing to remove!");
        } else {
            $(".field-wrap-" + counter + "").remove();
            counter--;
        }
    });
});

And my PHP

    <?php
require 'connection.php';
session_start();
$studid  = (explode(",", $_POST['studid']));
$subject = mysql_real_escape_string(strtoupper($_POST['subject']));
$section = mysql_real_escape_string(strtoupper($_POST['section']));
$adminid = $_SESSION['AdminID'];
mysqli_query($con, "INSERT INTO tbl_subjects(SubjectName, SubjectSection, AdminID) VALUES ('$subject', '$section', '$adminid')");
if (!empty($studid) && !empty($name)) {
    foreach ($studid as $new) {
        $sql_1 = "INSERT INTO tbl_student(StudentID, SubjectID) VALUES ('$new', LAST_INSERT_ID())";
        mysqli_query($con, $sql_1);
    }
}
if (!mysqli_query($con, $sql)) {
    die('Error: ' . mysqli_error($con));
}
?>

i used !empty in my php and im getting same result. If i dont press the add button at all, im not getting any issue. Its just about when pressing it and even after removing it the variable in ajax seems to carry an empty data to database.

3
  • to be more specific, i am getting a 0 value in the tbl_student even i already removed the forms i added. Commented Feb 23, 2015 at 2:35
  • beta.phpformatter.com and jsbeautifier.org can help you format your code. Proper formatting really makes a difference when debugging :) Commented Feb 23, 2015 at 2:54
  • i really apologize with the format of my code, im still new in web programming and it is my first time posting a question here and im using a smartphone :) thank you for the response. Commented Feb 23, 2015 at 4:41

1 Answer 1

0

I think your issue issue is that, in your PHP, you call $studid = (explode(",", $_POST['studid'])); before you check if the value is set.

From the docs for explode()


If delimiter is an empty string (""), explode() will return FALSE. If delimiter contains a value that is not contained in string and a negative limit is used, then an empty array will be returned, otherwise an array containing string will be returned.


Effectively, you are calling explode() on an empty string and getting back your empty string.

In your PHP, try moving explode() inside the if statement, after you check if it is set like:

<?php
require 'connection.php';
session_start();
$subject = mysql_real_escape_string(strtoupper($_POST['subject']));
$section = mysql_real_escape_string(strtoupper($_POST['section']));
$adminid = $_SESSION['AdminID'];
mysqli_query($con, "INSERT INTO tbl_subjects(SubjectName, SubjectSection, AdminID) VALUES ('$subject', '$section', '$adminid')");
if ( isset( $_POST['studid'] )) {  
    $studid  = (explode(",", $_POST['studid']));
    foreach ($studid as $new) {
        $sql_1 = "INSERT INTO tbl_student(StudentID, SubjectID) VALUES ('$new', LAST_INSERT_ID())";
        mysqli_query($con, $sql_1);
    }
}
if (!mysqli_query($con, $sql)) {
    die('Error: ' . mysqli_error($con));
}
?>

Also, in your jquery, change:

var dataString = 'subject=' + subject + '&section=' + section + '&section=' + section;

To:

// only add  `studid` if there is one or more present
var studidStr = studid != '' ? '&studid=' + studid : '';
var dataString = 'subject=' + subject + '&section=' + section + studidStr;
Sign up to request clarification or add additional context in comments.

2 Comments

thank you for the response. im going to try this one later and update you about it. The other thing is it seems i cant use the mysql_real_escape_string in the variable $studid because it is not posting any value in the data if i do it this way : $studid = mysql_real_escape_string(explode(",", $_POST['studid']));
When you call explode(",", $_POST['studid']) the result is an array. You are then trying to call mysql_real_escape_string() on that array but mysql_real_escape_string() expects a string not an array. Try array_map('mysql_real_escape_string', explode(",", $_POST['studid']) ); instead. That should escape all the values in the array

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.