I Need To Send A Request Through Js To A Php File Via Api
Help me please. There are two php files Data.php and Status.php. When you enter data in the zip field, you need to send a request to the Data.php file, and if zip is available, se
Solution 1:
You need to send an AJAX call from the first php to second php. Include following script inside first php file. test1.php
<?php// other content
<script>
(function() {
var httpRequest;
document.getElementById("ajaxButton").addEventListener('click', makeRequest);
functionmakeRequest() {
httpRequest = new XMLHttpRequest();
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
returnfalse;
}
httpRequest.onreadystatechange = alertContents;
httpRequest.open('GET', 'test2.php');
httpRequest.send();
}
functionalertContents() {
if (httpRequest.readyState === XMLHttpRequest.DONE) {
if (httpRequest.status === 200) {
alert(httpRequest.responseText); // your response
} else {
alert('There was a problem with the request.');
}
}
}
})();
</script>
?>
Then return your content data from the next php file as follows. test2.php
<?php$x = "content data";
echo$x;
?>
For more details about AJAX, follow below link https://developer.mozilla.org/en-US/docs/Web/Guide/AJAX/Getting_Started
Solution 2:
javaScript Code
const data = { name: 'scott' }; // data for postfetch('url', {
method: 'POST',
headers: {
'Content-Type': 'application/json', // type
},
body: JSON.stringify(data),
})
.then(response => response.json())
.then(data => {
console.log(data);
})
.catch((error) => {
console.error(error);
});
Post a Comment for "I Need To Send A Request Through Js To A Php File Via Api"