Showing posts with label ajax. Show all posts
Showing posts with label ajax. Show all posts

Thursday, 15 May 2014

jQuery: Send form by ajax

Hello,

Sometimes we want to send form data but we don't want to reload page. In this case best option is send data by ajax and jQuery. In this example we used version 1.10.2 of jQuery.

HTML code:

<form id="FORMID" accept-charset="UTF-8" action="action.php" method="POST"> <input type="text" name="username" id="username" placeholder="Write username"> </form>;

Javascript code:

$('#FORMID').on('submit', function(e)  {
$.post(
$(this).prop('action'),
{
"username": $(this).find('input[name=username]').val()
},
function(data) {
alert(data.result);
},
'json'
); return false;
});


php (action.php) code:

<?php
$username = $_POST['username'];
$ret = array();
$ret['result'] = 'OK';
return json_encode($ret);

Best regards!