Q:

How to call a php function using JQuery/AJAX

The following is in the head of my html file, in script tags : 
$(document).ready(function(){ 
                 $("#Submit").click(function(){
                     var name = $("#name").val();
                     $.ajax({
                         url : "function.php", 
                         type : "POST",
                         data : {"firstname":name},
                         success : function(n){
                            //more code here                         } 
                     });
                 });
 }

This is the HTML form : 
<div class="myForm">
                <input name="name" id="name" value="name" onfocus="if (this.value == 'Name') {this.value = '';}" onblur="if (this.value == '') {this.value = 'Name';}" type="text"  />
                <input type="button" value="Submit" id="Submit">
            </div>

Here is my PHP, saved in a file called function.php :
<?php
$con=mysqli_connect( "test", "", "", "test");
// Check connection
$name = $_POST['firstname'];
if (mysqli_connect_errno())
  {
  echo "Failed to connect to MySQL: " . mysqli_connect_error();
  }

mysqli_query($con,"INSERT INTO customers (name) VALUES (" + $name + ")");

mysqli_close($con);
?>

The function takes an age to call, and nothing is saved in my database. I am new to JQuery/Ajax. What are my debugging options here? What is the problem likely to be ?

A:

Try this code. I've edited your code and added PDO which is the new approach to connect to databases..
This is more secure and automatically escapes the data.
You had many syntax errors in your php. like string appending operator in php is . not +.
<?php
$name = $_POST['firstname'];
try {
    // Prepare our connection string and execute it
    $con = new PDO("mysql:host=".HOST.";dbname=".DBNAME, USER, PASS);
} catch(PDOException $e) {  
    // Connection error jumps here
    echo $e->getMessage();  
}
// Define our query here
$query = $con->prepare("INSERT INTO customers (name) VALUES (:name)");
// Define our query data here. the name here maps to the :name in the query.
$data = array("name" => $name);
try {
    // Try to execute our query
    $query->execute($data);
} catch(PDOException $e) {
    // Insert error jumps here
    echo $e->getMessage(); 
}
?>

Just put in your host, database name, user and pass in the places mentioned in the code and you're good to go.
For debugging the php code install Firebug on your firefox and in the html page open the firebug by right-clicking on the page and selecting Inspect element with firebug. open the Net panel and there you can see the request going. see the response and you will see any likely errors on your php page.
Good Luck!

