Javascript ajax with data

AJAX Database Example

The following example will demonstrate how a web page can fetch information from a database with AJAX:

Example

Example Explained — The showCustomer() Function

When a user selects a customer in the dropdown list above, a function called showCustomer() is executed. The function is triggered by the onchange event:

showCustomer

function showCustomer(str) <
if (str == «») <
document.getElementById(«txtHint»).innerHTML = «»;
return;
>
const xhttp = new XMLHttpRequest();
xhttp.onload = function() <
document.getElementById(«txtHint»).innerHTML = this.responseText;
>
xhttp.open(«GET», «getcustomer.php?q=»+str);
xhttp.send();
>

  • Check if a customer is selected
  • Create an XMLHttpRequest object
  • Create the function to be executed when the server response is ready
  • Send the request off to a file on the server
  • Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The AJAX Server Page

The page on the server called by the JavaScript above is a PHP file called «getcustomer.php».

The source code in «getcustomer.php» runs a query against a database, and returns the result in an HTML table:

$sql = «SELECT customerid, companyname, contactname, address, city, postalcode, country
FROM customers WHERE customerid = ?»;

$stmt = $mysqli->prepare($sql);
$stmt->bind_param(«s», $_GET[‘q’]);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($cid, $cname, $name, $adr, $city, $pcode, $country);
$stmt->fetch();
$stmt->close();

echo «

«;
echo ««;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

«;
echo «

CustomerID » . $cid . « CompanyName » . $cname . « ContactName » . $name . « Address » . $adr . « City » . $city . « PostalCode » . $pcode . « Country » . $country . «

«;
?>

Источник

How to send GET and POST AJAX request with JavaScript

AJAX is a web de­velopment technique­ that facilitates the exchange­ of data between the­ website visible on a use­r’s browser and its server-side­ database. This enables se­amless communication for optimal performance and use­r experience­.

JavaScript libraries or frame­works are commonly utilized by people­ to conveniently transmit AJAX reque­sts. Although it’s essential to recognize­ the significance of transmitting AJAX reque­sts with plain JavaScript as well.

To communicate with the server, use an object called XMLHttpRequest. It helps in sending and receiving data between the client-side and server-side.

In this tutorial, I show how you can send GET and POST AJAX requests with JavaScript and handle the request with PHP.

How to send GET and POST AJAX request with JavaScript

Contents

1. Create a Table

Create employee table and added some records.

CREATE TABLE `employee` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `emp_name` varchar(80) NOT NULL, `salary` varchar(20) NOT NULL, `email` varchar(80) NOT NULL );

2. Database Configuration

Create a config.php for the database connection.

3. Create HTML layout

Create 3 input text elements for entering the name, salary, and email. And a button element.

Added onclick event on the button which calls insertNewEmployee() function.

List records in the using JavaScript and AJAX.

 Name: Salary: Email:  
Name Salary Email

4. Create a PHP file to handle AJAX request

Create ‘ajaxfile.php’ file to handle AJAX request.

For example purpose, I am handling both GET and POST requests in a single file.

GET request (fetch records)

Check if $_GET[‘request’] is set or not if set then assign $_GET[‘request’] to $request .

If $request == 1 then fetch all records from employee table and assign to $employeeData . Loop on the fetched records.

Initialize $response with id, emp_name, salary, and email keys.

Return $response Array in JSON format.

POST request (insert record)

If $request == 2 then read POST values using json_decode(file_get_contents(«php://input»)) .

Assign values to variables and prepare INSERT query.

If the INSERT query is executed successfully then return 1 otherwise 0 .

 // Fetch records if($request == 1) < // Select record $sql = "SELECT * FROM employee"; $employeeData = mysqli_query($con,$sql); $response = array(); while($row = mysqli_fetch_assoc($employeeData))< $response[] = array( "id" =>$row['id'], "emp_name" => $row['emp_name'], "salary" => $row['salary'], "email" => $row['email'], ); > echo json_encode($response); exit; > // Insert record if($request == 2)< // Read POST data $data = json_decode(file_get_contents("php://input")); $name = $data->name; $salary = $data->salary; $email = $data->email; // Insert record $sql = "insert into employee(emp_name,salary,email) values('".$name."',".$salary.",'".$email."')"; if(mysqli_query($con,$sql))< echo 1; >else < echo 0; >exit; >

5. How to make an AJAX request with JavaScript

Use XMLHttpRequest object to send AJAX request.

  1. Request method – GET or POST.
  2. AJAX file path. Pass parameter with URL on GET request – ajaxfile.php?name=yogesh&city=bhopal .
  3. It is an optional parameter that takes Boolean value true or false . Default value is true . Pass true for asynchronous and false for synchronous request.

.setRequestHeader() – This method is used to set Content-Type . By default, ‘application/x-www-form-urlencoded’ content-type is set. You can change its value e.g. – application/json , multipart/form-data , etc.

.onreadystatechange – This property calls on request state change. Assign an anonymous function to process the response. If this.readyState == 4 && this.status == 200 means the server response is ready for processing.

.send() – This method send AJAX request. It is also used to send data.

AJAX GET request JavaScript

var xhttp = new XMLHttpRequest(); xhttp.open("GET", "ajaxfile.php?request=1", true); xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); xhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < // Response var response = this.responseText; >>; xhttp.send();

Above syntax with jQuery

AJAX POST request JavaScript

application/x-www-form-urlencoded; charset=UTF-8 is a default Content-Type but you can use any other type e.g. – application/json , multipart/form-data , etc.

var xhttp = new XMLHttpRequest(); xhttp.open("POST", "ajaxfile.php", true); xhttp.setRequestHeader("Content-Type", "application/json"); xhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < // Response var response = this.responseText; >>; var data = ; xhttp.send(JSON.stringify(data));

Above syntax with jQuery

$.ajax(< url: 'ajaxfile.php', type: 'post', data: , success: function(response) < >>);

Create object of XMLHttpRequest . Specify GET request and AJAX file path with parameter ( ‘ajaxfile.php?request=1’ ) in .open() method. Set Content-type and handle server response with onreadystatechange property.

Loop on the response to read values. Create a new table row element and assign a response value in cell.

Read values from the textboxes and assign them in variables. If variables are not empty then create a data JSON object. Initialize data object with the textbox values.

Create XMLHttpRequest object and specify POST request and AJAX file path ( ‘ajaxfile.php’ ) in .open() method. Set Content-type to ‘application/json’ and handle server response with onreadystatechange property.

Assign this.responseText in response . If response == 1 then alert a message and call loadEmployees() function to fetch records.

loadEmployees(); // Send AJAX GET request with JavaScript function loadEmployees() < var xhttp = new XMLHttpRequest(); // Set GET method and ajax file path with parameter xhttp.open("GET", "ajaxfile.php?request=1", true); // Content-type xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded'); // call on request changes state xhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < // Parse this.responseText to JSON object var response = JSON.parse(this.responseText); // Select var empTable = document.getElementById("empTable").getElementsByTagName("tbody")[0]; // Empty the table empTable.innerHTML = ""; // Loop on response object for (var key in response) < if (response.hasOwnProperty(key)) < var val = responseJavascript ajax with data; // insert new row var NewRow = empTable.insertRow(0); var name_cell = NewRow.insertCell(0); var username_cell = NewRow.insertCell(1); var email_cell = NewRow.insertCell(2); name_cell.innerHTML = val['emp_name']; username_cell.innerHTML = val['salary']; email_cell.innerHTML = val['email']; >> > >; // Send request xhttp.send(); > // Send AJAX POST request with JavaScript (Insert new record) function insertNewEmployee() < var name = document.getElementById('txt_name').value; var salary = document.getElementById('txt_salary').value; var email = document.getElementById('txt_email').value; if(name != '' && salary !='' && email != '')< var data = ; var xhttp = new XMLHttpRequest(); // Set POST method and ajax file path xhttp.open("POST", "ajaxfile.php", true); // call on request changes state xhttp.onreadystatechange = function() < if (this.readyState == 4 && this.status == 200) < var response = this.responseText; if(response == 1)< alert("Insert successfully."); loadEmployees(); >> >; // Content-type xhttp.setRequestHeader("Content-Type", "application/json"); // Send request with data xhttp.send(JSON.stringify(data)); > >

6. Output

7. Conclusion

To have gre­ater control and flexibility in the imple­mentation of AJAX requests, it is crucial to unde­rstand how to send them without relying on JavaScript librarie­s or frameworks. While using such libraries may simplify the­ process, having a solid foundation in plain JavaScript enables a de­eper comprehe­nsion of the underlying mechanisms and boosts the­ capability to develop customized solutions.

The XMLHttpRe­quest object allows sending GET and POST re­quests to the serve­r, handling responses effe­ctively. This feature cre­ates endless possibilitie­s for developing dynamic user inte­rfaces, real-time data update­s, and seamless expe­riences for the use­r.

The ability to se­nd both GET and POST AJAX requests with JavaScript constitutes a crucial skill for any we­b developer. It e­nables them to create­ dynamic, interactive applications that seamle­ssly communicate with servers, the­reby heightening the­ overall user expe­rience. There­fore, keep honing this valuable­ skill by practising and exploring different possibilitie­s in your web developme­nt ventures.

Источник

Читайте также:  Html coloring one word
Оцените статью