How to save data using JQuery Ajax - Ybus
post-template-default,single,single-post,postid-4686,single-format-standard,ajax_fade,page_not_loaded,,side_area_uncovered_from_content,qode-child-theme-ver-1.0.0,qode-theme-ver-10.0,wpb-js-composer js-comp-ver-4.12,vc_responsive

How to save data using JQuery Ajax

How to save data using JQuery Ajax

Captura de Tela 2015-04-13 às 08.53.52

Continuing from the post yesterday, this time we are saving data from the form using AJAX without actually leaving the html page.

1) So for the PHP file called json.php, we have:


$server = “localhost”;
$username = “deepl541_ajax”;
$password = “test123”;
$database = “deepl541_ajax”;

$json = ‘[‘;

$con = mysql_connect($server, $username, $password) or die (“Could not connect: ” . mysql_error());
mysql_select_db($database, $con);
$name = $_POST[“name”];
$points = $_POST[“points”];

//echo $name;
//echo $points;
//echo “INSERT INTO user (username, points) VALUES (‘$name’,’$points’)”;
$insert = “INSERT INTO user (username, points) VALUES (‘$name’,’$points’)”;

$sql = ‘SELECT * FROM user’;
$query = mysql_query($sql);

while ($row = mysql_fetch_array($query, MYSQL_NUM)) {

if (strlen($json) >1){
$json = $json . “,”;
//echo $row[1];
$json = $json . ‘{“firstName”:”‘ . $row[1] . ‘”,”points”:’ . $row[2] . ‘}’;


$json = $json . ‘]’;
echo $json;

//echo ‘[{ “firstName”: “User 1”, “points”:10},{“firstName”: “User 2″,”points”:10}]’;


And finally, for the HTML, we have:

<!DOCTYPE html>

<script src=””></script>
$.getJSON(‘json.php’, function(data) {
$.each(data, function(index) {
$(“.table1″).append(‘<tr><td>’ + data[index].firstName + ‘</td><td>’ + data[index].points + ‘</td></tr>’);

// process the form
$(‘form’).submit(function(event) {

// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
‘name’ : $(‘input[name=name]’).val(),
‘points’ : $(‘input[name=points]’).val(),


// process the form
type : ‘POST’, // define the type of HTTP verb we want to use (POST for our form)
url : ‘json.php’, // the url where we want to POST
data : formData, // our data object
dataType : ‘json’, // what type of data do we expect back from the server
encode : true
// using the done promise callback
.done(function(data) {

// log data to the console so we can see

// here we will handle errors and validation messages

// stop the form from submitting the normal way and refreshing the page

<h2>HTML Tables</h2>

<div id=”div1″>JSON GOES TO <table></div>

<button>Get External Content</button>

<h2>AJAX JSON</h2>

<table class=”table1″>

First name:<br>
<input type=”text” name=”name”>
Last name:<br>
<input type=”number” name=”points”>
<button type=”submit” class=”btn btn-success”>Submit <span class=”fa fa-arrow-right”></span></button>



3) Last step: check the values you received before using it to avoid SQL Injection.