Insert into DB using ajax without refreshing page

Create a new file call ajax.php and add js-script to an index file or add a new js file.

index.php

<form>

<input class=”form-control” type=”text” id=”name” />

<input class=”form-control” type=”text” id=”contact”  />

<button class=”btn btn-primary” type=”button”  onclick=”insert()”>Add Details</button>

</form>

// show the result

.js script

 

function insertm() {

var mnm = $(‘#name’).val();

var mcon = $(‘#contact’).val();

if(mnm == “” || mcon == “”)

{

alert(‘Fill all the data!’);

}

else{

if (window.XMLHttpRequest) {

// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

} else { // code for IE6, IE5

xmlhttp=new ActiveXObject(‘Microsoft.XMLHTTP’);

}

xmlhttp.onreadystatechange=function() {

if (xmlhttp.readyState==4 && xmlhttp.status==200) {

document.getElementById(‘gid’).innerHTML=xmlhttp.responseText;

}

}

xmlhttp.open(‘GET’,’ajax.php?n=’+mnm +’&c=’+mcon ,true);

xmlhttp.send();

}

$(‘#name’).val(“”);

$(‘#contact’).val(“”);

}

ajax.php

 

<?php

session_start();

include(‘function/db.php’);

global $conn;

$name = $_GET[‘n’];

$contact = $_GET[‘c’];

$stmt = $conn->prepare(“INSERT INTO profile(name,cont) VALUES (?, ?)”);

$stmt->bind_param(“ss”, $nm, $con);

//set parameters and execute

$nm = $name;

$con = $contact;

$stmt->execute();

$last_id = $conn->insert_id;

if($stmt)

{

echo “<span class=’sucsses’>Added Successfully with id</span> $last_id</span>”;

}

else

{

echo “Somthing Went Wrong!”;

}

$stmt->close();

?>

Published by Sushant Sharma

Technologist. Software Developer. Tech Analyst ।।।

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Design a site like this with WordPress.com
Get started