Ajax Jequery Post without Form tag & without refre

2019-06-11 17:16发布

问题:

I have a page to post data via ajax jquery without refresh an without form tag. N validate via snackbar.

I know that this is possible using jQuery and AJAX, but I'm not really experienced in one of these languages. Anyone got an idea how to solve this?

its my button funtion:

<input type="text" id="nikpemohon">
<input type="text" id="namapemohon">
<button id="tombolsimpan" onclick="validate()"></button>`

here my js:

function validate() {
    var regExnamapemohon = /^[a-zA-Z .'-]+$/;

    var values = {
        'nikpemohon': document.getElementById('nikpemohon').value,
        'namapemohon': document.getElementById('namapemohon').value,
    };

    if(document.getElementById('nikpemohon').value == "" || document.getElementById('nikpemohon').value == null || document.getElementById('nikpemohon').value == undefined || document.getElementById('nikpemohon').value.length < 16 ) {
        //get the snackbar
        var notification = document.querySelector('.mdl-js-snackbar');
        //creating data for snackbar notification
        var data = {
            message: 'Isi NIK dengan benar. Contoh: 6108011234567890',
            timeout: 4000
        }
        //pushing the notification to the screen
        notification.MaterialSnackbar.showSnackbar(data);
        document.getElementById('nikpemohon').focus();
    } else if (document.getElementById('namapemohon').value == "" || document.getElementById('namapemohon').value == null || document.getElementById('namapemohon').value == undefined || !regExnamapemohon.test(document.getElementById('namapemohon').value) )  {
        //get the snackbar
        var notification = document.querySelector('.mdl-js-snackbar');
        //creating data for snackbar notification
        var data = {
            message: 'Isi Nama Lengkap hanya dengan huruf abjad saja, tanpa Penulisan Gelar. Contoh: Matius, Markus atau Darius',
            timeout: 4000
        }
        //pushing the notification to the screen
        notification.MaterialSnackbar.showSnackbar(data);
        document.getElementById('namapemohon').focus();
    } else {
        $.ajax({
            url: "ktp_post.php",
            type: "POST",
            data: values,
        }); 
    }
}

this my ktp_post.php:

if(isset($_POST['tombolsimpan'])){ 

$nikpemohon = strtoupper($_POST['nikpemohon']);
$namapemohon = strtoupper($_POST['namapemohon']);

$sql = $con->query("INSERT INTO katimpus (nikpemohon, namapemohon)Values('{$nikpemohon}', '{$namapemohon}')");}

please help here. two days spent for this error. I cannot Post the data to mysql database..

回答1:

Have you used proper value for your button Try like this:

<form method='post'> <input type="text" id="nikpemohon"> <input type="text" id="namapemohon"> <input type="button" id="tombolsimpan" value="tombolsimpan" onclick="validate()"/> </form>



回答2:

i fix by delete if(isset($_POST['tombolsimpan'])){ & } on .php process