1

I want to add state name in my state mysql table in database using PHP and Ajax but the modal box is not submitting the information. I posted all my code for single button submission in model box and are as follows:

My directory structure is:

Directory structure

Server files

test.html

<!DOCTYPE html>
<html>
<head>
    <title>Test Page</title>
    <link rel="stylesheet" type="text/css" href="./model.css" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.4.1.min.js"> 
    </script>
</head>
<body>
    <button id="add_state">Add State</button>

     <div>
      <?php                                            


         include('server/connection.php');

         $sqlSelect="SELECT * FROM tbl_state_info ORDER By StateName ASC";
         $result = $conn -> query ($sqlSelect);                                           
         $result = $conn -> query ($sqlSelect);                                          
         echo "<select name='StateName'>";
         echo "<option>select</option>";                                            
         while ($row = mysqli_fetch_array($result)) {
         echo "<option value=$row[StateName]> $row[StateName] </option>";
         }
         echo "</select>";
      ?>     


     </div>

    <div id="add_state_model" class="add_state_model">
        <div class="add_state_model_content">
            <span class="state_model_close">&times;</span>
            <form id="state_submit_form" method="post" action="">
                <label>Enter State:</label>
                <input type="text" name="state">
                    <input type="submit" name="state_submit">
                    </form>
                    <div class="message_box" style="margin-left: 60px;"></div>
                </div>
            </div>
            <script src="./model.js"></script>
        </body>
    </html>

and for backend i am using javascript and PHP

model.js


var add_state_model = document.getElementById('add_state_model');
var add_state_button = document.getElementById('add_state');
var add_state_span = document.getElementsByClassName('state_model_close')[0];

add_state_button.onclick = function(){
    add_state_model.style.display = "block";
}

add_state_span.onclick = function(){
    add_state_model.style.display = "none";
}

window.onclick = function(event) {
  if (event.target == add_state_model) {
    add_state_model.style.display = "none";
  }
}


$(document).ready(function(){

  var delay = 1000;

$('[name="state_submit"]').click(function(e){

           e.preventDefault();


           var state = $('#state_submit_form').find('[name="state"]').val();

           if(state === ''){
            $('.message_box').html(
                '<p><span style="color:red;">Please enter state name!</span></p>'
                );
            $('[name="state"]').focus();
            return false;
           }          

           console.log(state);    


          $.ajax({
                type: "POST",                       
                url: "server/addstate.php",
                data: {"state":state},
                beforeSend: function() {
                    $('.message_box').html(
                    '<img src="./tenor.gif" width="40" height="40"/>'
                    );
                }, 
                success: function(data)
                {
                    setTimeout(function() {
                    $('.message_box').html(data);
                    }, 1000);
                }
          });  
    });

});


And also there is server page addstate.php

<?php

if ( ($_POST['state']!="") ){

$state = $_POST['state'];

include('connection.php');

/* check connection */
if ($conn->connect_errno) {
    printf("Connect failed: %s\n", $conn->connect_error);
    exit();
}

//insert query for registration
$insertSql = "INSERT INTO `tbl_state_info`(`StateName`) VALUES ('$state')";

if ($conn->query($insertSql) === TRUE) {

    echo "<span style='color:green;'>
     <p>State added to dropdown</p>
     </span>";     

    }else{        
        printf("Error: %s\n", $conn->error);        
    }  
}

?>

and connection.php file

<?php

    // set the timezone first
    if(function_exists('date_default_timezone_set')) {
        date_default_timezone_set("Asia/Kolkata");
    }

    $conn = new mysqli('localhost', 'root', '');

    //check connection
    if($conn->connect_error){
        die("Connection Failed".$conn->connect_error);
    }

    //connect database
    mysqli_select_db($conn, 'crm');
?>

and the css file model.css, it is used for Model Box pop up


.add_state_model {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  left: 0;
  top: 0;
  width: 100%; /* Full width */
  height: 100%; /* Full height */
  overflow: auto; /* Enable scroll if needed */
  background-color: rgb(0,0,0); /* Fallback color */
  background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content/Box */
.add_state_model_content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 30%; /* Could be more or less, depending on screen size */
}

/* The Close Button */
.state_model_close {
  color: #aaa;
  float: right;
  font-size: 28px;
  font-weight: bold;
}

.state_model_close:hover,
.state_model_close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}

I am getting this below error:

Error

RINKS
  • 71
  • 7

2 Answers2

0

in your ajax request data object accept only json object and you have passed query string try this code

$.ajax({
    type: "POST",                       
    url: "http://localhost/CRM/server/addstate.php",
    data: {"state":state},
    beforeSend: function() {
        $('.message_box').html(
        '<img src="tenor.gif" width="40" height="40"/>'
        );
    }, 
    success: function(data)
    {
        setTimeout(function() {
        $('.message_box').html(data);
        }, 1000);
    }
}); 

and second thing settimeout accept delay in miliseconds which i have specified 1 second

bharat savani
  • 339
  • 5
  • 18
0

Make me correct if I am not wrong

You can visit this URL this will help you to solve your problem How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'?

Or try to change URL path I have tried on my end it's working for me

 url: "http://localhost/CRM/server/addstate.php", 
    to
    url: "server/addstate.php"

enter image description here If any help feel free to ask me

Mannu saraswat
  • 1,061
  • 8
  • 15
  • I tried to combine all relevant file in same folder and also changed all path used earlier but still it not worked – RINKS Dec 26 '19 at 09:16
  • You can visit this URL this will help you to solve your problem https://stackoverflow.com/questions/46522749/how-to-solve-redirect-has-been-blocked-by-cors-policy-no-access-control-allow – Mannu saraswat Dec 26 '19 at 09:20
  • I have updated all my question with directory structure i am using please see on code – RINKS Dec 26 '19 at 10:09
  • Great! make it correct so it can help others... Happy coding... – Mannu saraswat Dec 26 '19 at 10:23
  • I updated the above code can you suggest me that once i add state to database then how it automatically update the dropdown without refereshing page is ajax is used – RINKS Dec 26 '19 at 10:27
  • for this you have to initialize the dropdown again.. like return a variable from your DB file and set it into your options – Mannu saraswat Dec 26 '19 at 10:29
  • can you extend this in chat section i will paste some php code which is fetching the values of state from the database – RINKS Dec 26 '19 at 10:35