Question regarding insert into mySQL using Ajax

soulblader_86

Supremacy Member
Joined
Sep 28, 2007
Messages
9,012
Reaction score
0
Code:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <title>Javascript Create Div Element Dynamically</title>

    <style type="text/css">
.ex
{
width:auto;
position: relative;
height:auto;
margin:5px;
float :left;
border: 1px solid #000;
}


.square
{
 width: 200px;
 height:200px;
 background-color:#F99; 
 margin:15px;
}
.myimage {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
}

#newdiv
{
    width:800px;
    height:800px;
 border:1px solid #000;     
}

.table
{
    position:absolute;
    margin-top:100px;
    margin-left:20px;

}
    </style>
<script>


function changeimage(image)
{

if (image.cc==0) 
  {
  image.cc=1;
  $(image).attr('src', 'images/white_contact.png');
  }
else if (image.cc==1)
  {
  image.cc=2;
  $(image).attr('src', 'images/yellow_contact.png');
  }
  else if (image.cc==2)
  {
  image.cc=3;
    $(image).attr('src', 'images/green_contact.png');
  }
    else
  {
  image.cc=0;
    $(image).attr('src', 'images/red_contact.png');
  }
}
</script>
 <script type="text/javascript" language="javascript">
var i=0;
    function createDiv()
    {


  if(i < 6) {


  $('#newdiv').append('<div id="div"'+i+'" class="ex" style="text-align: left;"><div id="div"'+i+'" class= "square"><table border="0" class = "table" ><tr><td width="51">Name:</td><td width="141"><input type="text" size="10" class = "name"></td></tr><tr><td>Title:</td><td><input type="text" size="10" class = "title"></td></tr><tr><td>Contact:</td><td><input type="text" size="10"  class = "contact"></td></tr></table></div><img class="myimage" ondblclick="changeimage(this)" border="0"src="http://forums.hardwarezone.com.sg/images/white_contact.png" width="60" /></div>');




      }
$.ajax({
                url: 'savecontact.php',
                type: 'POST',           
                success:function (data) {

                    if (data == '1')
                    {
                    $("#star")
                    .html("Data saved successfully")
                    }
                   else
                   {
                     $("#star")
                    .html("error")  
                   }
                }
            });   
   i++;
   $( ".ex" ).draggable({containment:'parent',cursor:'pointer',opacity:0.6});
 $( ".ex" ).droppable();

    }





    </script>
</head>
<body>

    <p align="left">
        <b>Click this button to create div element dynamically:</b>
        <input id="btn1" type="button" value="create div" onClick="createDiv();" />
       <div id = "star"></div>
        <div id = "newdiv">

</div>
    </p>

</body>
</html>

I want to insert 6 empty record into my contact table while I click on the same button 6 times instantly, so it is like, I click on the button 5 times, 5 record is inserted. I am using Ajax

this is my PHP file for SQL query, savecontact.php

Code:
<?php
include('config.php') ;


$sql = "INSERT into contact(FirstName,LastName,Email,OfficePhone,MobilePhone, Position, Department, CustomerID, CreatedBy, DateCreated)values ('', '' , '', '', '', '', '','','','')";

    if (mysql_query($sql))
    {
        echo 1;
    }
?>

I not sure what wrong, now I can create 6 new record, ONLY IF I click one by one SLOWLY, if I click 6 times on the button, only 4 records is inserted, or when I am slower, I can created 5 records

Is it Insert new record need time?
 

davidktw

Arch-Supremacy Member
Joined
Apr 15, 2010
Messages
13,547
Reaction score
1,301
Code:
<!doctype html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
    <title>Javascript Create Div Element Dynamically</title>

    <style type="text/css">
.ex
{
width:auto;
position: relative;
height:auto;
margin:5px;
float :left;
border: 1px solid #000;
}


.square
{
 width: 200px;
 height:200px;
 background-color:#F99; 
 margin:15px;
}
.myimage {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 10;
}

#newdiv
{
    width:800px;
    height:800px;
 border:1px solid #000;     
}

.table
{
    position:absolute;
    margin-top:100px;
    margin-left:20px;

}
    </style>
<script>
function changeimage(image)
{

if (image.cc==0) 
  {
  image.cc=1;
  $(image).attr('src', 'images/white_contact.png');
  }
else if (image.cc==1)
  {
  image.cc=2;
  $(image).attr('src', 'images/yellow_contact.png');
  }
  else if (image.cc==2)
  {
  image.cc=3;
    $(image).attr('src', 'images/green_contact.png');
  }
    else
  {
  image.cc=0;
    $(image).attr('src', 'images/red_contact.png');
  }
}
</script>
<script type="text/javascript" language="javascript">
var i=0;
function createDiv() {

 if(i < 6) {
    $('#newdiv').append('<div id="div"'+i+'" class="ex" style="text-align: left;"><div id="div"'+i+'" class= "square"><table border="0" class = "table" ><tr><td width="51">Name:</td><td width="141"><input type="text" size="10" class = "name"></td></tr><tr><td>Title:</td><td><input type="text" size="10" class = "title"></td></tr><tr><td>Contact:</td><td><input type="text" size="10"  class = "contact"></td></tr></table></div><img class="myimage" ondblclick="changeimage(this)" border="0"src="http://forums.hardwarezone.com.sg/images/white_contact.png" width="60" /></div>');
  }
  
  $.ajax({
    url: 'savecontact.php',
    type: 'POST',
    success:function (data) {
      if (data == '1') {
        $("#star").html("Data saved successfully")
      }
      else {
        $("#star").html("error")  
      }
    }
  });   
  
  i++;
  
  $( ".ex" ).draggable({containment:'parent',cursor:'pointer',opacity:0.6});
  $( ".ex" ).droppable();
}
</script>
</head>
<body>

    <p align="left">
        <b>Click this button to create div element dynamically:</b>
        <input id="btn1" type="button" value="create div" onClick="createDiv();" />
       <div id = "star"></div>
        <div id = "newdiv">

</div>
    </p>

</body>
</html>

I want to insert 6 empty record into my contact table while I click on the same button 6 times instantly, so it is like, I click on the button 5 times, 5 record is inserted. I am using Ajax

this is my PHP file for SQL query, savecontact.php

Code:
<?php
include('config.php') ;


$sql = "INSERT into contact(FirstName,LastName,Email,OfficePhone,MobilePhone, Position, Department, CustomerID, CreatedBy, DateCreated)values ('', '' , '', '', '', '', '','','','')";

    if (mysql_query($sql))
    {
        echo 1;
    }
?>

I not sure what wrong, now I can create 6 new record, ONLY IF I click one by one SLOWLY, if I click 6 times on the button, only 4 records is inserted, or when I am slower, I can created 5 records

Is it Insert new record need time?

Of course, Javascript is a single threaded engine in current browsers implementation, that's why the asynchronous concept is used here. Ajax is implemented using the underlying XMLHttpRequest or others depending on browsers implementation. While the UI will return almost immediately, the requests will be executed asynchronously in the background, that's why it's called async in the first place. When multiple ajax calls are made, there is no assurance which will return first.

Of course everything takes time. From the point you click on any UI to initiate an action. It takes time for the javascript call to be made. It takes time for the ajax call to be processed by the browser and to be fire off. It takes time to reach the server end. On the server end, it takes time to execute the script and it takes time to connect to the database and also takes time to initiate a database query. It certainly takes a lot of time for the database to response. Then it takes time to have the results interpreted by the script and then pass back to the client.

If there is contention at any point, which there are, the order may not be guaranteed especially in the realm of asynchronous behaviour.

Supposedly all the requests will be fired, not sure how your code run in the server side that may result in only partial data set, you might want to look at how you are inserting data, is there any key conflicts, are you using auto-increment for key columns ? It is not apparent from your PHP code how you are inserting data since they are all filled into empty string.

The way you are coding your PHP also is very unsound, so what happened when there is any error ? How should your client side react ? Please be mindful that your call back for the ajax call is only for success execution. If the PHP script should fail with anything besides HTTP 2XX, your ajax code will not involve the success callback.

As more information for your consideration, your changeimage may be further enhanced in the function enhanced_changeimage that I have included with this post below.

Code:
// can you observe how much simpler the function is with the usage of modulo operator and array.
function enhanced_changeimage(image) {
  var src_arr = new Array(
    'images/red_contact.png',
    'images/white_contact.png',
    'images/yellow_contact.png',
    'images/green_contact.png'
  );
  
  image.cc = (image.cc + 1) % 4;
  $(image).attr('src', src_arr[image.cc]);
}

The whole concept on how you handle multiple insertion of contacts is incorrect. Your webpage should be split into 2 portion. The top portions shows what is currently in the data and is READ-ONLY. The bottom portion is a form for you to add in more contacts. All retrieval of data can be using ajax to show information after the webpage is loaded.

You might want to rethink or have a more in-depth discussion on how you are approaching the problem.
 
Last edited:
Important Forum Advisory Note
This forum is moderated by volunteer moderators who will react only to members' feedback on posts. Moderators are not employees or representatives of HWZ Forums. Forum members and moderators are responsible for their own posts. Please refer to our Community Guidelines and Standards and Terms and Conditions for more information.
Top