简体   繁体   中英

Extracting data from HTML form with inputs with JavaScript or AJAX and then passing it on to PHP

I have an issue I can't seem to solve, I have a form with a bunch of text-fields but I need to extract their information through AJAX or just through a simple JavaScript function. I need this data to be extracted, string by string into an array which should then be passed to PHP. If understood this correctly, AJAX can be used with JQuery or JavaScript, now I'm not sure I understand JQuery very well. Anyway I've been searching google for good examples, and I really can't find anything good.

<form class="registration" method="POST">
                <ul class="registration">
                    <li><label>Nombre de Usuario:</label></li>
                    <li><input type="text" name="username" title="Nombre de Usuario"/></li>
                    <li><label>Contrase&ntilde;a:</label></li>
                    <li><input type="text" name="password" title="Contrase&ntilde;a"/></li>
                    <li><label>Correo Electr&oacute;nico:</label></li>
                    <li><input type="text" name="email" title="Correo Electr&oacute;nico"/></li>
                    <li><label>Nombre:</label></li>
                    <li><input type="text" name="name" title="Nombre"/></li>
                    <li><label>Primer Apellido:</label></li>
                    <li><input type="text" name="first last name" title="Primer Apellido"/></li>
                    <li><label>Segundo Apellido:</label></li>
                    <li><input type="text" name="second last name" title="Segundo Apellido"/></li>
                    <li><input type="submit" name="create user" title="Crear Usuario" value="Crear Usuario"></input></li>
                </ul>
            </form>

This is my form, some of the values are in Spanish, the website I'm supposed to make has to be in that language. If I understood things right, I should call the function I want with an "OnClick" through my submit input button. This is the first time I've done web development, and understanding CSS and HTML was difficult for me. I was wondering if someone could help me out with an example or something. I'm basically using MVC to organize this, with HTML and JavaScript as the View, PHP as the control and Oracle SQL as the model. I'm using PHP precisely for that reason, I need to connect to the database, and send the information through PHP.

I'm not looking for anyone to fix my thing or anything of the sort, all I need is an example and small explanation if possible.

You need to figure out $.ajax function. It easy to implement, and posting the values into your php file, then from there you can processing inserting data into database. Here is sample of code :

        $('input[type=submit]').on('click',function(e)
        {
             e.preventDefault();

             var my_username = $('input[name=username]').val();
             .....
             ..... more here 

              $.ajax({
                  type : 'POST', //<--- GET or POST
                  url  : 'url_of_insert_process.php',
                  data : { 
                           username: my_username,
                           .....
                           ..... more here
                         }
                  success : function(data){
                     // Here you can populate the view whatever you want 
                     // like showing message success
                  }
                });

       });

That is the illustration sending the data. You also can use $("form" ).serialize(); to fetch all the form element value using the name that you provided on each html form element. So many sources out there that you can put into your table.

Please try

$(document).ready(function(){
    $('input[type="submit"]').click(function(e){
        e.preventDefault();
        $.ajax({
          url: "YOUR_URL",
          type: 'POST',
          data:$("form#registration").serialize(),
          success: function( response ) {
            console.log(response);
          }
        });
    });
});
//jsfile.js
//THIS METHOD RETURN THE name : value PAIR FROM
//A SPECIFIED FORM ID OR FORM IN THE CURRENT SPHERE
function formHandler(formID="") {
    try {
        if (formID === "") {
            //PICK UP THE FORM IN THE CURRENT SPHERE
            formElms  document.querySelectorAll("input,select,textarea");
        } else if(formID !== "") {
            //PICK UP THE NAMED FORM
            var formsElms = document.querySelectorAll("form");
            formsElms.forEach(function(formElm) {
                if (formElm.id === formID) {
                    formElms = document.querySelectorAll("#"+formID+" input, #"+formID+" select, #"+formID+" textarea");
                }
            });
        }
        if (formElms) {
            var retObjs = new Array();
            if (formElms) {
                formElms.forEach(function(param) {
                    retObjs.push({name : param.name, value: param.value});
                });
            }
        }
        return retObjs;
    } catch (e) {
        console.log(e);
    }
}

serverSideHandler(inda={}) {
    try {
        indata   = inda;
        complUrl = "url.php";
        $.ajax({
            method: "POST",
            url: complUrl,
            data: indata
        })
        .done(function(retData) {
            serverResponseHandler(retData);//Function To Callback
        });
    } catch(ev) {
        console.log(ev);
    }
}


//url.php
<?php
  header("Access-Control-Allow-Origin: *");
  header('Content-Type: text/json');
  ini_set('memory_limit','1024M');

  if (!empty($_POST)) {
    //Extract your form Inputs as follow
    $name = doSomeValidation($_POST['name']);

    //Do DB connections
    //Do your CRUD
    //DO OTHER ACTIONS
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM