简体   繁体   English

使用JavaScript或AJAX从带有输入的HTML表单中提取数据,然后将其传递给PHP

[英]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. 我有一个似乎无法解决的问题,我有一个带有一堆文本字段的表单,但是我需要通过AJAX或仅通过一个简单的JavaScript函数提取它们的信息。 I need this data to be extracted, string by string into an array which should then be passed to PHP. 我需要将这些数据逐个字符串提取到一个数组中,然后将其传递给PHP。 If understood this correctly, AJAX can be used with JQuery or JavaScript, now I'm not sure I understand JQuery very well. 如果正确理解了这一点,那么AJAX可以与JQuery或JavaScript一起使用,现在我不确定我对JQuery的理解是否很好。 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. 如果我理解正确,则应该通过提交输入按钮使用“ OnClick”调用所需的函数。 This is the first time I've done web development, and understanding CSS and HTML was difficult for me. 这是我第一次完成Web开发,对我来说,理解CSS和HTML十分困难。 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. 我基本上是使用MVC来组织它,以HTML和JavaScript作为View,以PHP为控件,以Oracle SQL为模型。 I'm using PHP precisely for that reason, I need to connect to the database, and send the information through PHP. 正是出于这个原因,我正在使用PHP,我需要连接到数据库,并通过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. 您需要弄清楚$ .ajax函数。 It easy to implement, and posting the values into your php file, then from there you can processing inserting data into database. 它易于实现,并将值发布到您的php文件中,然后您可以从那里处理将数据插入数据库的过程。 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(); 您还可以使用$("form" ).serialize(); to fetch all the form element value using the name that you provided on each html form element. 使用您在每个html表单元素上提供的名称获取所有表单元素值。 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
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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