CodeSolved

A comprehensive source of programming questions and exercises

Send request with AJAX

Practice Easy 46/ Download 1394 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

1 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

Submit answer

Submitting answers is currently unavailable.

Related content

Detection using AI
×
×
Close