简体   繁体   中英

Js, Ajax, Json - How not to insert “Array” into db from autocomplete

im building a little script that will automatically fill few input fields based on autocomplete of the first input field.

I have the script working, but when i hit submit button everything seems to be ok, But when i look into the db to see what was inserted, All fields are inserted with "Array" instead of what supposed to be inserted. on the autocomplete, I can see that field are being field with the right info, But i guess php doesn't understand what it is, and inserts "Array" instead.

Any ideas how to fix it?

my form:

<form action="job_post.php" method="post">
                    <div class="form-group has-success col-md-3">
                    <label class="control-label" for="inputSuccess1">First Name: </label>
                    <input type='text' id='firstname' name='firstname[]'/>
                </div>
                <div class="form-group has-success col-md-3">
                    <label class="control-label" for="inputSuccess1">Last Name: </label>
                    <input type='text' id='lastname' name='lastname[]'/>
                </div>
                <div class="form-group has-success col-md-3">
                    <label class="control-label" for="inputSuccess1">Age: </label>
                    <input type='text' id='age' name='age[]'/>
                </div>
                <div class="form-group has-success col-md-3">
                    <label class="control-label" for="inputSuccess1">Company Name: </label>
                    <input type='text' id='CoName' name='CoName[]'/>
                </div>

<input type="submit">
</form>

My job_post.php

<?php

require_once 'db_connect.php';

$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$age=$_POST['age'];
$CoName=$_POST['CoName'];

$qry=mysql_query("INSERT INTO jobs (FirstName, LastName, Age, CoName)
VALUES ('$firstname', '$lastname', '$age', '$CoName')", $con);
if(!$qry)
{
mysql_close($con);
die("Query Failed: ". mysql_error());
}

else
{
mysql_close($con);
header("Location:index.php");
}

mysqli_close($con);
?>

My Js:

$('#firstname').autocomplete({
                    source: function( request, response ) {
                        $.ajax({
                            url : 'ajax.php',
                            dataType: "json",
                            data: {
                               name_startsWith: request.term,
                               type: 'firstname',
                               row_num : 1
                            },
                             success: function( data ) {
                                 response( $.map( data, function( item ) {
                                    var code = item.split("|");
                                    return {
                                        label: code[0],
                                        value: code[0],
                                        data : item
                                    }
                                }));
                            }
                        });
                    },
                    autoFocus: true,            
                    minLength: 2,
                    select: function( event, ui ) {
                        var names = ui.item.data.split("|");
                        console.log(names[1], names[2], names[3]);                      
                        $('#lastname').val(names[1]);
                        $('#age').val(names[2]);
                        $('#CoName').val(names[3]);
                    }               
                  });

My Ajax:

<?php
/*
Site : http:www.smarttutorials.net
Author :muni
*/
require_once 'db_connect.php';

if($_GET['type'] == 'firstname'){
    $row_num = $_GET['row_num'];
    $result = mysql_query("SELECT FirstName, LastName, Age, CoName FROM jobs where FirstName LIKE '".strtoupper($_GET['name_startsWith'])."%'");    
    $data = array();
    while ($row = mysql_fetch_array($result)) {
        $name = $row['FirstName'].'|'.$row['LastName'].'|'.$row['Age'].'|'.$row['CoName'].'|'.$row_num;
        array_push($data, $name);   
    }   
    echo json_encode($data);
}


?>

It does pull data, but im looking to insert it to the db with submit button.

Any help highly appreciated.

Updated info

Then place the variables in the query you have now.

Page redone:

 <?php

    require_once 'db_connect.php';

    $firstname = $_POST["firstname"][0];
    $CoName = $_POST["CoName"][0]; 

    /*
     * Last Name and Age are not in the array, I removed them from the query 
     * however you need to place them in the array if you wish to add them
     */

    $qry=mysql_query("INSERT INTO jobs (FirstName, CoName)
        VALUES ('$firstname', '$CoName')", $con);

    if(!$qry) {
        mysql_close($con);
        die("Query Failed: ". mysql_error());
    } else {
        mysql_close($con);
        header("Location: index.php");
    }

    ?>

Updated again, misread array.

make sure that you are getting single record, for this use limit 1 in your sql(not good idea). otherwise loop through return array for multiple insertion. before inserting use print_r($_POST); and see what you are trying to insert.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM