Ahmadz Issa Ahmadz Issa - 7 months ago 33
Javascript Question

insert data to database using Jquery/ajax&php

I have been trying to submit data to database using ajax, but I I keep getting stuck.

I took simple code to test it, but it didn't work no matter what I do.

HTML/ajax code

<?php include("osb.php");?>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<!--we have our html form here where user information will be entered-->
<form action='osb.php' method='post' border='0' id="form1">
<div id = "container"> <br>
<label>Name: </label> <input type='text' id="name" name='name' /><br> <br>
<label>E-mail: </label> <input type='text' id="email" name='email' /><br><br><br>

<input type='hidden' name='action' value='create' />
<input type='button' value='Submit' id="submit" />
<input type="reset" value="Reset" class="reset-org">
<div>

</form>

<script type = "text/javascript">
$(function(){

$('#submit').click(function(){


$('#container').append('<img src = "img/ajax/ajax-loader.gif" alt="Currently loading" id = "loading" />');
$.ajax({

url: 'osb.php',
type: 'POST',
data: $('#form1').serialize(),
success: function(result){
$('#response').remove();
$('#container').append('<p id = "response">' + result + '</p>');
$('#loading').fadeOut(500);

}

});

});
});
</script>


PHP CODE

<?php
//set connection variables




$host = "localhost";
$username = "";
$password = "";
$db_name = "";

//connect to mysql server
$mysqli = new mysqli($host, $username, $password, $db_name);



//check if any connection error was encountered
if(mysqli_connect_errno()) {
echo "Error: Could not connect to database.";
exit;
}

$action = isset($_POST['action']) ? $_POST['action'] : "";



if($action=='create'){ //the the user submitted the form

$data=$_POST['serialize'];
$name=$data['name']; //access data like this
$email=$data['email']; //access data like this
//include database connection

//our insert query query
//$mysqli->real_escape_string() function helps us prevent attacks such as SQL injection
$query = "insert into 'user' VALUES ($name,$email)";
mysqli_query($mysqli, $query);

//execute the query
if( $mysqli ->query($query) ) {
//if saving success
echo "User was created.";
}else{
//if unable to create new record
echo "Database Error: Unable to create record.";
}
//close database connection
$mysqli->close();
}



?>


I get these errors each time I submit the form:


Undefined index: serialize in C:\xampp\htdocs\php1\osb.php on line 29

Database Error: Unable to create record.

Answer

remove

$data=$_POST['serialize'];
$name=$data['name'];  //access data like this
$email=$data['email'];  //access data like this

Add

$name=$_POST['name']; 
$email=$_POST['email'];

Regards

Comments