Ahmadz Issa Ahmadz Issa - 2 years ago 92
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">


<script type = "text/javascript">


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

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





//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.";

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

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

$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.";
//if unable to create new record
echo "Database Error: Unable to create record.";
//close database connection


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 Source


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




Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download