简体   繁体   中英

What is the equivalent of this in a pure JavaScript structure? This sends values to the server side

This script is designed to get the values from the inputs and send it by ajax to x.php as POST data to be echo by x.php. This works perfectly but I want to convert

this jQuery structure to a pure JavaScript structure so in other words how can I send a basic JS Object contents as POST data by AJAX to be echo by x.php

jQuery structure(works*)

index.php

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script>

$(document).ready(function(){

  $('#send').click(function(){
//Var structure
var first_name= $('#first_name').val();
var last_name= $('#last_name').val();

//Data var
var data={
      first_name: first_name,
      last_name: last_name
}


//Success var
var success= function(response){
   $('.output-container').html(response);
}

//Request
    $.ajax({
      data: data,
      method: 'POST',
      url: 'x',
      success: success
    });
  });
});

</script>

<input id='first_name' type='text' value='John'>
<input id='last_name' type='text' value='Doe'>

<button id='send'>Send</button>

<div class='output-container'><div>

JavaScript structure(Failed attempt*)

index.php

<script>
document.addEventListener('DOMContentLoaded', function(){

var execute_sendAjax = document.getElementById('send');
  execute_sendAjax.addEventListener("click", executeAjax);

var xhr= new XMLHttpRequest();
xhr.onreadystatechange = function(){
    if(xhr.readyState === 4){
        document.getElementsByClassName('output-container')[0].innerHTML= xhr.responseText;
    }
};

function executeAjax(){

  //Var structrue
  var first_name=  document.getElementById('first_name').value;
  var last_name=  document.getElementById('last_name').value;

//Data var
var data={
  first_name: first_name,
  last_name: last_name
}

    xhr.open('POST','x');
    xhr.send();
}
});
</script>

<input id='first_name' type='text' value='John'>
<input id='last_name' type='text' value='Doe'>

<button id='send'>Send</button>

<div class='output-container'><div>

x.php

<?php

$first_name=$_POST['first_name'];
$last_name=$_POST['last_name'];

?>

<h1><?php echo $first_name; ?></h1>
</h1><?php echo $last_name; ?></h1>

In the pure JS structure I don't know where to go from there that's where I'm getting stuck at.

Recent findings UPDATED*

After doing some more research( Link ) I found out that application/x-www-form-urlencoded is another way to encode as POST data but I had to avoid using a JS object because it does not work with a normal JS object. I'm still looking for a way that I can use as a JS object.

<script>
document.addEventListener('DOMContentLoaded', function(){

var execute_sendAjax = document.getElementById('send');
  execute_sendAjax.addEventListener("click", executeAjax);

var xhr= new XMLHttpRequest();
xhr.onreadystatechange = function(){

    if(xhr.readyState === 4){
        document.getElementsByClassName('output-container')[0].innerHTML= xhr.responseText;
    }
};

function executeAjax(){

  //Var structrue
  var first_name=  document.getElementById('first_name').value;
  var last_name=  document.getElementById('last_name').value;

//Data var
var data = "first_name="+first_name+"&last_name="+last_name;

/*var data={
  first_name: first_name,
  last_name: last_name
}*/

    xhr.open('POST','x');
    xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //<--I notice this makes it encoded to be used as POST data
    xhr.send(data);
}
});
</script>

<input id='first_name' type='text' value='John'>
<input id='last_name' type='text' value='Doe'>

<button id='send'>Send</button>

<div class='output-container'><div>

JQuery is marshaling the Javascript object into form data. There are lots of ways to do this, but I think the easiest way is to use a FormData object like so:

function executeAjax(){
    var data = new FormData();
    // FormData.append(name, value) - appends a new value onto an 
    //  existing key inside a FormData object, or adds the key if 
    //  it does not already exist.
    data.append("first_name", document.getElementById('first_name').value;);
    data.append("last_name", document.getElementById('last_name').value;


    xhr.open('POST','x.php');
    xhr.send(data);
}

Then you don't have to edit any PHP or set the content-type in the request header.

If you don't like the FormData object (for whatever reason):

function executeAjax(data) {
    var data = [
        "first_name="+encodeURIComponent(document.getElementById('first_name').value),
        "last_name="+encodeURIComponent(document.getElementById('last_name').value)
    ].join('&').replace(/%20/g, '+');

    xhr.open('POST', 'x.php');
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xhr.send(data);
}

Learn more here .

Sorry was not at the computer before.

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