1

I have 4 tables namely stud, country_master_academic,master_state and master_city. The main problem is that my form consists of many different fields like textbox, radio buttons, dropdown and an image file, so i am getting really confused. I can't insert data in database. Please help me. I tried many times but its not working. Thanks for the help in advance. Modal in home.php page

 <div class="container">
<div class="modal fade" id="add_data_modal" role="dialog">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-heading" style="margin-top:30px;text-align:center">
                <button class="close" data-dismiss="modal" style="margin-right:20px;font-weight:bold;">x</button>
                <h4 class="modal-title"><span class="glyphicon glyphicon-user"></span> Add Student</h4>
            </div>
            <div class="modal-body">
                <div class="form-group">
                <form class="form-horizontal" name="form" id="form" method="post" action="<?php $_PHP_SELF?>" enctype="multipart/form-data">
                    <label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>
                    <input type="text" class="form-control" name="name" id="name" pattern="[a-zA-Z]{3,}" title="Name should only contain letters and atleast 3 letters" required />
                </div>
                <div class="form-group">
                    <label for="no"><span class="glyphicon glyphicon-phone"></span><b> Mobile No: </b></label><label id="p2">*</label>
                    <input type="text" class="form-control" name="mob_no" id="mob_no" pattern="[0-9]{10}" title="Mobile number should be of 10 digits" required />
                </div>
                <div class="form-group">    
                    <label for="dob"><span class="glyphicon glyphicon-calendar"></span><b> Birth Date: </b></label><label id="p3">*</label>
                    <input type="date" class="form-control" name="dob" required />
                </div>
                <div class="form-group">
                    <label for="add"><span class="glyphicon glyphicon-map-marker"></span><b> Address: </b></label><label id="p4">*</label>
                    <textarea rows="4" cols="33" class="form-control" name="add" id="add" required></textarea>
                </div>
                <div class="form-group">
                    <label for="photo"><span class="glyphicon glyphicon-camera"></span><b> Photo: </b></label><label id="p5">*</label>
                    <input type="file" name="photo" id="photo" required />
                </div>
                <div class="form-group">
                    <label for="gen"><b> Gender: </b></label><label id="p6">*</label><br/>
                    <input type="radio" name="gender" id="gender" value="M" required="required">Male
                    <input type="radio" name="gender" id="gender" value="F" required="required">Female
                </div>
                <div class="form-group">
                    <label for="cntry"><span class="glyphicon glyphicon-map-marker"></span><b> Country: </b></label><label id="p7"> *</label>
                        <?php
                            $country="SELECT * from country_master_academic";
                            $res= $conn->query($country);
                            if($res->num_rows>0)
                            {
                                echo '<select name="country" id="country" class="form-control" required>';
                                echo '<option value="">Select</option>';
                                while($row=$res->fetch_assoc())
                                {
                                echo '<option value='.$row["country_code"].'>'.$row['country_name'].'</option>';
                                }
                                echo '</select>';
                            } else {
                            echo "0 result";
                        }
                        ?>

                </div>
                <div class="form-group">
                    <label for="state"><span class="glyphicon glyphicon-map-marker"></span><b> State: </b></label><label id="p8">*</label>
                    <?php
                        $state = "SELECT * from master_state";
                        $res=$conn->query($state);
                        if($res->num_rows>0)
                        {
                            echo '<select name="state" id="state" class="form-control" required>';
                            echo '<option value="">Select</option>';
                            while($row=$res->fetch_assoc())
                            {
                                echo '<option value='.$row["state_code"].'>'.$row["state_name"].'</option>';
                            }
                            echo '</select>';
                        } else {
                            echo "0 result";
                        }
                    ?>
                    </div>
                <div class="form-group">
                    <label for="city"><span class="glyphicon glyphicon-map-marker"></span><b> City: </b></label><label id="p9">*</label>
                    <?php
                        $city="SELECT * from master_city";
                        $res=$conn->query($city);
                        if($res->num_rows>0)
                        {
                            echo '<select name="city" id="city" class="form-control" required>';
                            echo '<option value="">Select</option>';
                            while($row=$res->fetch_assoc())
                            {
                                echo '<option value='.$row["city_code"].'>'.$row["city_name"].'</option>';
                            }
                            echo '</select>';
                        } else {
                            echo "0 result";
                        }
                    ?>
                </div>

                <div class="form-group">
                    <button type="submit" name="save" id="save" class="btn btn-info" onclick="validate()">Save</button>
                </div>
                </form>
            </div>
            <div class="modal-footer">
            <button class="btn btn-danger" type="button" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div> 

My jquery in home page

    $('.insert_data').click(function(){
                    var vname = $("#name").val();
                    var vmob = $("#mob_no").val();
                    var vdob = $("#dob").val();
                    var vadd = $("#add").val();
                    var vphoto = $("#photo").val();
                    var vgender = $("#gender").val();
                    var vcountry = $("#country").val();
                    var vstate = $("#state").val();
                    var vcity = $("#city").val(); 

                    $.ajax({
                        url:"insert.php",
                        method:"post",
                        data: {
                            name:vname,
                            mob_no:vmob,
                            dob:vdob,
                            add:vadd,
                            photo:vphoto,
                            gender:vgender,
                            country:vcountry,
                            state:vstate,
                            city:vcity
                        },
                        success: function(data){
                            $('#form')[0].reset();  
                            $('#add_data_Modal').modal('hide');  
                            $('#stud_insert').html(data);
                        }
                    });
                });

my insert.php page

<?php
include("connection.php");
if(!empty($_POST))
{
    $output = '';
    $name = $_POST['name']);
    $mob = $_POST['mob_no']);
    $dob = $_POST['dob']);
    $add = $_POST['add']);
    $photo = $_FILES['photo']['name']);
    $gender = $_POST['gender']);
    $cn = $_POST['country']);
    $st = $_POST['state']);
    $ct = $_POST['city']);

    $qrycn= mysqli_query($conn,"select country_code from country_master_academic where country_name=' ".$cn." ' ");
    $row = mysqli_fetch_array($qrycn);
    $country = $row['country_code'];

    $qryst=mysqli_query($conn,"select state_code from master_state where state_name='".$st."'");
    $row = mysqli_fetch_array($qryst);
    $state = $row['state_code'];

    $qryct= mysqli_query($conn,"select city_code from master_city where city_name='".$ct."'");
    $row = mysqli_fetch_array($qryct);
    $city = $row['city_code'];

    $query = "INSERT INTO stud (stud_name, mobile, dob,address,photo,gender,country,state,city) VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$country', '$state', '$city')";
    if (mysqli_query($conn, $query)) {

                $target_dir="images/";
        $target_file=$target_dir.basename($_FILES["photo"]["name"]);
        $imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
        if(move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file)){
            echo '<script language="javascript">';
            echo 'alert("Image and data Inserted Successfully")';
            echo '</script>';
        }  else {
            echo '<script language="javascript">';
            echo 'alert("Cannot upload")';
            echo '</script>';
        }
    }
    else {
        echo '<script language="javascript">';
        echo 'alert("Cannot insert record")';
        echo '</script>';
    }
    $output .= '<label class="text-success">Data Inserted</label>';
     $output .= '
            <table class="table table-bordered">  
                <tr>  
                     <th>No</th>
                    <th>Name</th>
                    <th>Mobile</th>
                    <th>Birthdate</th>
                    <th>Address</th>
                    <th>Photo</th>
                    <th>Gender</th>
                    <th>Country</th>
                    <th>State</th>
                    <th>City</th>
                </tr>

 ';
    $result=  mysqli_query($conn,"select * from stud s, country_master_academic c, master_state st, master_city ct where s.country=c.country_code and s.state=st.state_code and s.city=ct.city_code");
    while($row = mysqli_fetch_array($result))
 {
  $output .= '
        <tr>  
            <td><a href="update.php?no='.$row["stud_no"].'"><button name="edit" value="Edit" style="font-weight:bold;" class="btn btn-warning"><span class="glyphicon glyphicon-edit"></span> Edit</button></a></td>
            <td><button type="submit" style="font-weight:bold;" name="delete" id='.$row["stud_no"].' class="btn btn-danger delete_data"><span class="glyphicon glyphicon-trash"></span> Delete</button></td>
            <td><button type="submit" style="font-weight:bold;" name="view" id='.$row["stud_no"].' class="btn btn-success view_data" data-target="#modalDelete" data-toggle="modal"><span class="glyphicon glyphicon-user"></span> View</button></td>

        </tr>
  ';
 }
 $output .= '</table>';
}
echo $output;
    }

?>

5
  • So do you get any errors? What part doesn't work? At first glance your code seems like it should work. Commented Nov 22, 2018 at 10:03
  • what you mean from 'not working'? Do you get any error in console? Script error or PHP error? no error? Commented Nov 22, 2018 at 10:03
  • @DirkScholten no sir... It's not showing any errors.. Commented Nov 22, 2018 at 10:07
  • @AliSheikhpour no errors... Just after i click on save , modal gets closed Commented Nov 22, 2018 at 10:08
  • Data is not getting inserted, I think problem with my jquery or i am not inserting properly Commented Nov 22, 2018 at 10:08

4 Answers 4

4

Please use your form id submit and get you to form data and pass through ajax and debug with alert(data).

$(document).ready(function(){
    $("#form").submit(function(event){
        event.preventDefault();
        var formData = new FormData(this);
          $.ajax({
             url: 'insert.php',
             type: 'POST',
             data: formData,
             async: false,
             success: function(data) {
               alert(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
     });
});
Sign up to request clarification or add additional context in comments.

2 Comments

thank u so much, but I want to say one thing, in database i have stored country code, not country name, so while inserting i have to store country code and while displaying it should show country name. Rest all records are getting inserted. Only country,state and city not getting inserted
Please check with the database table stud datatype and length.
2

ok let me list all errors in your html

<label for="name" id="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>

remove id like this

<label for="name"><span class="glyphicon glyphicon-user"></span><b> Student Name: </b></label><label id="p1">*</label>

and add id to this

<input type="date" class="form-control" name="dob" required />

add id

<input type="date" class="form-control" name="dob" id="dob" required />

in your php

$output = '';
$name = $_POST['name']);
$mob = $_POST['mob_no']);
$dob = $_POST['dob']);
$add = $_POST['add']);
$photo = $_FILES['photo']['name']);
$gender = $_POST['gender']);
$cn = $_POST['country']);
$st = $_POST['state']);
$ct = $_POST['city']);

change it to

$output = '';
$name = $_POST['name'];
$mob = $_POST['mob_no'];
$dob = $_POST['dob'];
$add = $_POST['add'];
$photo = $_FILES['photo']['name'];
$gender = $_POST['gender'];
$cn = $_POST['country'];
$st = $_POST['state'];
$ct = $_POST['city'];

then remove

$qrycn= mysqli_query($conn,"select country_code from country_master_academic where country_name=' ".$cn." ' ");
$row = mysqli_fetch_array($qrycn);
$country = $row['country_code'];

$qryst=mysqli_query($conn,"select state_code from master_state where state_name='".$st."'");
$row = mysqli_fetch_array($qryst);
$state = $row['state_code'];

$qryct= mysqli_query($conn,"select city_code from master_city where city_name='".$ct."'");
$row = mysqli_fetch_array($qryct);
$city = $row['city_code'];

and change insert to

$query = "INSERT INTO stud (stud_name, mobile, dob,address,photo,gender,country,state,city) VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$cn', '$st', '$ct')";

in you js you should use FormData() like this

$('.insert_data').click(function(){
            var vname = $("#name").val();
            var vmob = $("#mob_no").val();
            var vdob = $("#dob").val();
            var vadd = $("#add").val();
            var vphoto = $("#photo").val();
            var vgender = $("#gender").val();
            var vcountry = $("#country").val();
            var vstate = $("#state").val();
            var vcity = $("#city").val(); 
            var fd=new FormData();
            fd.append('name',vname);
            fd.append('mob_no',vmob);
            fd.append('dob',vdob);
            fd.append('add',vadd);
            fd.append('photo',vphoto);
            fd.append('gender',vgender);
            fd.append('country',vcountry);
            fd.append('state',vstate);
            fd.append('city',vcity);
            $.ajax({
                url:"insert.php",
                method:"post",
                data: fd,
                success: function(data){
                    $('#form')[0].reset();  
                    $('#add_data_Modal').modal('hide');  
                    $('#stud_insert').html(data);
                }
            });
        });

3 Comments

in your insert.php you don't need to search data base for country code, state code or city code because you already pass them to php, so remove the 3 queries and in your insert statement use the post values and save them to database
$query = "INSERT INTO stud (stud_name, mobile, dob,address,photo,gender,country,state,city) VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$cn', '$st', '$ct')";
see the edited post, its working and all data are stored in database
0

New code for Insert: Thank u every one for helping me.

<?php
include("connection.php");
if(!empty($_POST))
{
    $output = '';
    $name = $_POST['name'];
    $mob = $_POST['mob_no'];
    $dob = $_POST['dob'];
    $add = $_POST['add'];
    $photo = $_FILES['photo']['name'];
    $gender = $_POST['gender'];
    $cn = $_POST['country'];
    $st = $_POST['state'];
    $ct = $_POST['city'];

    $query = "INSERT INTO stud(stud_name, mobile, dob,address,photo,gender,country,state,city)VALUES('$name', '$mob', '$dob', '$add', '$photo', '$gender', '$cn', '$st', '$ct   ')";
    if (mysqli_query($conn, $query)) {

        $target_dir="images/";
        $target_file=$target_dir.basename($_FILES["photo"]["name"]);
        $imageFileType=pathinfo($target_file,PATHINFO_EXTENSION);
        if(move_uploaded_file($_FILES["photo"]["tmp_name"],$target_file)){
            echo '<script language="javascript">';
            echo 'alert("Image Inserted Successfully")';
            echo '</script>';
        }  else {
            echo '<script language="javascript">';
            echo 'alert("Cannot upload")';
            echo '</script>';
        }
        echo '<script language="javascript">';
            echo 'alert("Data Inserted Successfully")';
            echo '</script>';
    }
    else {
        echo '<script language="javascript">';
        echo 'alert("Cannot insert record")';
        echo '</script>';
    }   
} 

?>

Comments

0

This is my code to submit form data in my Laravel project looks like:

//Save new category
$(".frm-add-category").submit(function(event){
    event.preventDefault();
    var formData = new FormData(this);
    $.ajax({
        type:'POST',
        url: '/dashboard/category',
        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
        data: formData, 
        success:function(data){
            //Refresh the grid
            alert(data.success);
        },
        error: function(e){
          alert(e.error);
        }
    });
});

Comments

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.