0

Hello I have a form with some data what I want is when I click a button a jQuery function executes and print all that data in the console so here is my form code:

<form>
    <div class="row">           
        <div class="col-md-3">
            <div class="form-group">
                <label for="fecha">Fecha:</label>
                <input type="text" name="fecha" id="fecha" class="form-control" placeholder="dd/mm/yyyy">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <label for="total">Total:</label>
                <input type="number" min="0" name="total" id="total" class="form-control">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <label for="abono">Abono:</label>
                <input type="number" min="0" name="abono" id="abono" class="form-control">
            </div>
        </div>
        <div class="col-md-3">
            <div class="form-group">
                <label for="resta">Restante:</label>
                <input type="text" name="resta" id="resta" class="form-control" readonly>
            </div>  
        </div>
    </div>
    <div class="row">
        <div class="col-md-6 col-md-offset-5">
            <button type="submit" value="actualizar" class="btn btn-info" id="actualizar">Actualizar Datos
                <span class="glyphicon glyphicon-refresh"></span>
            </button>
        </div>
    </div>
</form>

and this is my script include

<script src="js/jquery-1.12.2.min.js"></script>
<script type="text/javascript" src="js/actualizar_orden.js"></script>

this is actualizar_orden.js file:

//Al clickear boton actualizar ordenes
$('#actualizar').click(function(){
    var orden = parseInt($('#norden').val());
    var id_tecnico = parseInt($('#id_tec').val());
    var memoria = $('#memoria').val();
    var chip = $('#chip').val();
    var tapa = $('#tapa').val();
    var falla = $('#falla').val();
    var observacion = $('#observacion').val();
    var estado = $('#estado').val();
    var fecha = $('#fecha').val();
    var total = parseInt($('#total').val());
    var abono = parseInt($('#abono').val());
    var ajaxUrl = 'actualizar_ordenes.php';

    data = { 'norden': orden, 'id_tec': id_tecnico, 'memoria': memoria, 'chip': chip, 'tapa': tapa, 
            'falla': falla, 'observacion': observacion, 'estado': estado, 'fecha': fecha, 
            'total': total, 'abono': abono };


    console.log(data);
    /*$.post(ajaxUrl, data, function(response){
        if(response.empty)
            alert("Datos no actualizados");
        else{
            alert("Datos Actualizados.");
            location.reload();
        }
    })   */ 
});

I just want to log that data into console to check if I'm getting it right.. but instead of log that to console my page is refreshing automatically so I can't see the output in the console... I've tried with both mozilla and chrome but still nothing

Cory Danielson
  • 14,314
  • 3
  • 44
  • 51
Carlos Delgado
  • 159
  • 1
  • 2
  • 15

2 Answers2

2

I see You want to submit form using jquery, without refreshing screen.

simply do following in Your js file:

$(function() {
  $('form.ajax').submit(function(e) { // catch submit event on form with ajax class
    e.preventDefault(); // prevent form act as default (stop default form sending)
    var $form = $(this); // caching form object to variable
    var data = $form.serializeArray(); // getting all inputs from current form and serializing to variable
    var url = $form.attr('action'); // reading forms action attribute
    console.log('DATA:', data);

    $.post(url, data, function(response) { // posting form data to url (action)
        console.log('RESPONSE:', response);
        if(response.empty) {
          alert("Datos no actualizados");
          return;
        }

        alert("Datos Actualizados.");
        $form.find('input, select').val(''); // resets form inputs
    }); 
  }); 
});

and change Your form tag to be like this:

<form class="ajax" action="actualizar_ordenes.php" method="post">

this example shows You that:

1) You can catch all form submits that has ajax class defined

2) no need to set exact url in js code (before it was hardcoded ajaxUrl variable). now it gets form action url from form attributes.

3) it does ajax post and if success, so You can redefine some wise behavior to make really flexible solution, and forget about writing custom code for each form submitting

isn't it flexible? (:

num8er
  • 18,604
  • 3
  • 43
  • 57
-2

Everyform need some default action to do on submitting. When it's not set it reloads the page by default. So to prevent the refreshing, you should add some empty action to your <form> tag, like this:

<form action="javascript:void(0);">
Telman
  • 1,444
  • 1
  • 9
  • 12
  • so in this case when user will click button browser will try to navigate to: javascript:void(0); url. because action is not that parameter that can handle event. but, in summary user want's working thing, look at js, as You see user wants to post form data to backend script without acting as default form submit. so for this case jquery has nice features like: .serializeArray() that gets form elements and builds json object from them. so one thing is lasting is to catch form submission and .preventDefault() – num8er Jun 09 '16 at 22:46