CodeSolved

Solved Programming Questions & Exercises

Send request with AJAX

Practice Easy 46/ Download 1763 Views

Send a request with the following details using JavaScript

method = post
URL = /Test.php

Information

FNAME =?
lNAME =?
Age =?

Get the information above through Prompt from the user

3 Answers

const fname = prompt("لطفاً نام خود را وارد کنید:");
const lname = prompt("لطفاً نام خانوادگی خود را وارد کنید:");
const age = prompt("لطفاً سن خود را وارد کنید:");

# Create an object to send to the server
const data = {
    fname: fname,
    lname: lname,
    age: age
};

# Send POST request using Fetch API
fetch('/test.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json' # Specifies the type of content
    },
    body: JSON.stringify(data) # Converts data to json format
})
.then(response => {
    if (!response.ok) {
        throw new Error('Network response was not ok');
    }
    return response.json(); # Expect the JSON reply
})
.then(data => {
    console.log('Success:', data); # Display of success in the console
})
.catch((error) => {
    console.error('Error:', error); # Display the error in the console
});
Mma123 Download JavaScript
const fname = prompt("Enter first name:");
const lname = prompt("Enter last name:");
const age = prompt("Enter age:");

fetch('/test.php', {
    method: 'POST',
    headers: {
        'Content-Type': 'application/json'
    },
    body: JSON.stringify({ fname, lname, age })
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
Ai Download JavaScript
<!DOCTYPE html>
<html lang="fa" dir="rtl">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Practice</title>

    <style>

    </style>
</head>
<body>

  <script>
    let fname = prompt("Please Enter Name :")
    let lname = prompt("Please Enter Last Name :")
    let age = prompt("Please Enter Age :")
    let userData = {
      fname:fname,
      lname:lname,
      age:age
    }

    fetch('/test.php',{method:'POST',
  body: JSON.stringify(userData)
})

  </script>
</body>
</html>

Submit answer

Submitting answers is currently unavailable.

×
×
Close