-2

I have a php generated form with multiple input fields the number of which is determined by user select. I would like to use an ajax function to enter all the data to database. The problem is that I am new to ajax and not sure ho to go about it. The ajax javascript function below is a sample of what I would like to achieve and I know it is not correct. Can someone point me in the right direction. I have looked around and from what I see, Json may be a solution but I know nothing about it and reading up on it I still don't get it.

sample ajax:

function MyFunction(){

var i = 1;
var x = $('#num_to_enter').val();
   while (i <= x){
    var name = $('#fname[i]').val();
    var lname = $('#lname[i]').val();
    var email = $('#Email[i]').val();
    i++;
 }
    $('#SuccessDiv').html('Entering Info.<img src="images/processing.gif" />');
     $.ajax({url : 'process.php',
    type:"POST",
   while (i <= x){
    data: "fname[i]=" + name[i] + "&lname[i]=" + lname[i] + "&email[i]=" + email[i],
    i++;
 }
     success : function(data){
    window.setTimeout(function()
    {
    $('#SuccessDiv').html('Info Added!');
    $('#data').css("display","block");
    $('#data').html(data);
    }, 2000);
        }
});
        return false;
          }

A sample of form :

<?php

   echo "<form method='post'>";

   $i=1;

    while($i <= $num_to_enter){

    $form_output .= "First Name:

    <input id='fname' type='text' name='fname[$i]'><br />

     Last Name:

    <input id='lname' type='text' name='lname[$i]'><br />

    Email:

    <input id='Email' type='text' name='Email[$i]'><br />

    $i++;

   }

   echo"<input type='button' value='SUBMIT' onClick='MyFunction()'></form>";

   ?>

Then DB MySQL Sample


   <?php
       while ($i <= $x){

    $x = $_POST['num_to_enter'];
    $fname = $_POST['fname[$i]'];
    $fname = $_POST['fname[$i]'];
    $fname = $_POST['email[$i]'];

        $sql = "INSERT INTO `mytable` 
    (`firstname`, `lastname`, `email`) VALUES ('$fname[$i]', '$lname[$i]', '$email[$i]');";

    $i++;

    }

   ?>
2
  • Check out this jquery plugin ... jquery.malsup.com/form Commented Nov 22, 2013 at 16:49
  • Christopher Morrissey not what I'm looking for! Commented Nov 22, 2013 at 16:52

2 Answers 2

3

Here is a simple demo of AJAX:

HTML

<form method="POST" action="process.php" id="my_form">
    <input type="text" name="firstname[]">
    <input type="text" name="firstname[]">
    <input type="text" name="firstname[]">
    <input type="text" name="firstname[custom1]">
    <input type="text" name="firstname[custom2]">
    <br><br>
    <input type="submit" value="Submit">
</form>

jQuery

// listen for user to SUBMIT the form
$(document).on('submit', '#my_form', function(e){

    // do not allow native browser submit process to proceed
    e.preventDefault();

    // AJAX yay!
    $.ajax({
        url: $(this).attr('action') // <- find process.php from action attribute
        ,async: true // <- don't hold things up
        ,cache: false // <- don't let cache issues haunt you
        ,type: $(this).attr('method') // <- find POST from method attribute
        ,data: $(this).serialize() // <- create the object to be POSTed to process.php
        ,dataType: 'json' // <- we expect JSON from the PHP file
        ,success: function(data){

            // Server responded with a 200 code

            // data is a JSON object so treat it as such
            // un-comment below for debuggin goodness
            // console.log(data);

            if(data.success == 'yes'){
                alert('yay!');
            }
            else{
                alert('insert failed!');
            }
        }
        ,error: function(){
            // There was an error such as the server returning a 404 or 500
            // or maybe the URL is not reachable
        }
        ,complete: function(){
            // Always perform this action after success() and error()
            // have been called
        }
    });
});

PHP process.php

<?php
/**************************************************/
/* Uncommenting in here will break the AJAX call */
/* Don't use AJAX and just submit the form normally to see this in action */

// see all your POST data
// echo '<pre>'.print_r($_POST, true).'</pre>';

// see the first names only
// echo $_POST['firstname'][0];
// echo $_POST['firstname'][1];
// echo $_POST['firstname'][2];
// echo $_POST['firstname']['custom1'];
// echo $_POST['firstname']['custom2'];

/**************************************************/

// some logic for sql insert, you can do this part

if($sql_logic == 'success'){

    // give JSON back to AJAX call
    echo json_encode(array('success'=>'yes'));
}
else{

    // give JSON back to AJAX call
    echo json_encode(array('success'=>'no'));
}
?>
Sign up to request clarification or add additional context in comments.

10 Comments

MonkeyZeus Thanks for the response! I think you missed the part where there will be more then 1 fname field and so on hence fname[I]. Am I wrong??
AJAX will have no issue posting the input fields you need. It is up to you to handle them properly once PHP gets the data. Please see the edit
MonkeyZeus Can we go to chat and I will show you more of what I am working with??
Depends on what time zone you are in, I am in New York. I am also on my phone right now and won't be at a computer until tomorrow sometime
I am in NY also I'll try to catch you 2moro
|
0
var postdata={};
postdata['num']=x;
   while (i <= x){
    postdata['fname'+i]= name[i];
    postdata['lname'+i]= lname[i];
    postdata['email'+i]= email[i];

    i++;
}
 $.ajax({url : 'process.php',
    type:"POST",
    data:postdata,
    success : function(data){
    window.setTimeout(function()
    {
    $('#SuccessDiv').html('Info Added!');
    $('#data').css("display","block");
    $('#data').html(data);
    }, 2000);
        }
});

PHP

$num=$_POST['num'];
for($i=1;i<=$num;i++)
{
 echo $_POST['fname'.$i];
 echo $_POST['lname'.$i];
 echo $_POST['email'.$i];
}

5 Comments

Patato, give me some time to work with this. Thanks for the response, will get back to you.
Patato I think you are on the right track, I used your code with a few changes because I have more fields then shown here. Put the code through jsLint and it is saying too many errors to continue after 30%. Also, with the code in the file none of the other javascript will work. Can we go to chat and I'll show you what I have??
@CornHoleLI sorry for late, cause Im in china that's almost midnight
Palato are you there?
sorry, you can Email me [email protected]

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.