How exactly does '$ .ajax ({type, post, data})' work in this connection?

2

Good morning, I am a student entering the world of programming trying to figure out how exactly the script works and I could use a help please, thank you.

<script type="text/javascript">

$(document).ready(function() {

$('.error').hide();

$("#enviar-btn").click(function() {

    //Obtenemos el valor del campo nombre
    var name = $("input#name").val();

    //Validamos el campo nombre, simplemente miramos que no esté vacío
    if (name == "") {
        $("label#name_error").show();
        $("input#name").focus();
        return false;
    }

    //Obtenemos el valor del campo password
    var password = $("input#password").val();

    //Validamos el campo password, simplemente miramos que no esté vacío
    if (password == "") {
        $("label#pass_error").show();
        $("input#password").focus();
        return false;
    }

    //Construimos la variable que se guardará en el data del Ajax para pasar al archivo php que procesará los datos
    var dataString = 'name=' + name + '&password=' + password;

    $.ajax({
        type: "POST",
        url: "register.php",
        data: dataString,
        success: function() {
            $('#register_form').html("<div id='message'></div>");
            $('#message').html("<h2>Tus datos han sido guardados correctamente!</h2>")
            .hide()
            .fadeIn(1500, function() {
                $('#message').append("<a href='index.php?action=see'>Ver usuarios registrados</a>");
            });
        }
    });
    return false;
});
});

runOnLoad(function(){
$("input#name").select().focus();
});

Exactly what is this ' $.Ajax '? I understood that it was used to register in a database and replace the insert of the php, but it seems that it is not like that. In url, I see that this ' register.php ', but then we are calling the document where the script is as if it were an include? Because I do not see that he is passing any information there with the AJAX.

In data, it is equal to a declared variable, but the same structure of the variable (var dataString = 'name=' + name + '&password=' + password;) I can not understand it, in other examples I have seen are much more different, as this (var data= 'valor': valor1) or the structure I find it very different , when you use one and when the other or why?

/// register.php
<?php
$name = utf8_decode($_POST['name']);
$password = md5($_POST['password']);


$con = mysql_connect('localhost', 'usuario', 'password');
mysql_select_db("tu_base_de_datos", $con);

$insert = "INSERT INTO tu_tabla (name, password, date_add) VALUES 
('$name', '$password', now())";
mysql_query($insert);
?>

First time I see the mysql_query($insert); in a php file, does this have to do something with ajax?

    
asked by Hoozuki 15.08.2018 в 17:48
source

2 answers

1

I will try to answer your questions:

Exactly what is this '$ .Ajax'?

$. ajax (and not $ .Ajax) is the implementation of ajax made with jquery , which is a JavaScript library. In a nutshell ajax is a technique that uses the Javascript XMLHttpRequest object to make http (POST, GET, etc ..) asynchronous requests, in practical terms it means that it allows you to make requests without reloading the page (the DOM technically). In this particular case that ajax is making a POST request to register.php and is sending information to it.

Are we calling the document where the script is as if it were an include?

We are calling the document as the browser would for example, we are executing the file, but sending parameters in this case.

The data variable

The variable data is encoding two variables, which would be name and password of the form querystring, which is the way in which variables are passed internally by http and is variable1=valor1&variable2=valor2 sometimes the structure is different because jquery accepts other types, it could be JSON for example, as data : {propiedad:valor} that depends on what suits or what is more maintainable.

register.php

The php file is capturing the sent values because they are saved in the superglobal variable $_POST and inserted into the database (without validating, which is a very bad practice)

    
answered by 15.08.2018 в 19:55
1

Let's go in parts:

When one learns php normally the first things that are usually taught usually send a form to another fichro .php or to itself and interpret this data, if you have already done this you will have noticed that every time this happens the page will be refresh or redirect, therefore a question arises:

  

How to send or receive data without the need to refresh the page ??   
-Where is the procedure AJAX

To put it simple: Ajax is an asynchronous procedure that allows us to receive or send information in the background on a page. Which brings many benefits:

  • Reload specific data from a page without refreshing it
  • Load the page and request the rest of the data after
  • Send data in the background

In each language it has a structure, which you indicate is the general request that implements jQuery since you can do it in 3 general ways:

  • $ .post () Function used for an ajax request to send data
  • $ .get () Function used for an ajax request to receive data
  • $ .ajax () General request in which you indicate within the parameters whether it will be POST or GET
  • For a request GET basic you need to indicate 2 parameters:

    • url : The address of the .php file or the url of the server from which you will receive information
    • type : In which you indicate if POST or GET

    If it is a request POST you need to use the parameter data in which you send the information, example:

    data: {"username": "juan"}
    
     success: function() {};
    

    It is used to perform an action if everything has been done correctly.

    In this post You have examples of how you can execute AJAX type GET or POST requests to your PHP files and the ways to pass data between them.

    With regard to register.php it is simply a php file prepared to receive request POST , collect the data of said request and insert it into a database. Yes, the only thing that has to do with AJAX is that it has been prepared to be used for that purpose because inside it has nothing of AJAX

        
    answered by 15.08.2018 в 20:08