1

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.

4
  • 1
    If this is the first time you've done web development I'd leave AJAX until you have a good grasp of the basics and use a normal form post for now. Set your form tag to <form class="registration" method="post" action="/somepath/tosomephp.php" > Commented Mar 26, 2015 at 4:00
  • I understand that, but I don't really have a choice, I have to use it. Aside from that I've been told that if it is not used, I will end up with a lot of files and pages that might be unnecessary and confusing. Commented Mar 26, 2015 at 4:17
  • If you've been told you have to use it, fine. However I strongly disagree with what you have been told regarding "clutter". Also if the same person that told you that is telling you that the way you are doing things is "MVC" then I'd question that too. EG the Oracle Database isn't really a model. A true model would be a class that represents entities stored in the database Commented Mar 26, 2015 at 5:03
  • No, that person didn't tell me that, but if you are saying that the real model tables, I'd see how that would work. Regardless, I don't have a choice in the matter, I will have to use it. I can tell you that this person does not program the way I do, and I don't really know how he did things. Regardless, this is not the first time that I have had to learn something beyond my level, the last time it was NASM which I had to learn on my own because my professor didn't even know it himself. Commented Mar 26, 2015 at 5:33

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

This seems like the sort of thing I'm looking for. I guess I will figure this out, but I get the idea. Thank you for the example.
0

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);
          }
        });
    });
});

1 Comment

I don't know why these ppl downvote even if my code is similar and given first. Shame
0
//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
  }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.