How to call a php function in javascript [duplicate] - javascript

This question already has answers here:
How can I call PHP functions by JavaScript?
(13 answers)
Closed 3 years ago.
i have a function in php .i want to call it inside javascript function .How to do that?
My php function is
<?php
function image_save(){
$img = $_POST['image'];
$folderPath = "C:/xampp/htdocs/";
$image_parts = explode(";base64,", $img);
$image_type_aux = explode("image/", $image_parts[0]);
$image_type = $image_type_aux[1];
$image_base64 = base64_decode($image_parts[1]);
$fileName = '1'. '.jpeg';
$file = $folderPath . $fileName;
file_put_contents($file, $image_base64);
print_r($fileName);
$command = escapeshellcmd("python C:/xampp/htdocs/generate_graph.py");
$output = shell_exec($command);
}
?>

You can call an API from js running on your broswser, not directly a PHP function.

If you want to call a PHP function from Javascript, you need to send an XMLHttpRequest to a server on which this function is running. Javascript is running in the browser, at your client computer. And PHP is running on your server, in some datacenter somewhere. Therefore, it's impossible to call a PHP function from your Javascript directly.
The XmlHttpRequest send an http request ( POST | GET | ... ) to a server and wait for it's output. In your case, you would call a php file on a server and wait for it's response.
From Javascript.info
// 1. Create a new XMLHttpRequest object
let xhr = new XMLHttpRequest();
// 2. Configure it: GET-request for the URL
xhr.open('GET', '/yourPhPfileLocationUrl/');
// 3. Send the request over the network
xhr.send();
// 4. This will be called after the response is received
xhr.onload = function() {
if (xhr.status != 200) { // analyze HTTP status of the response
alert(`Error ${xhr.status}: ${xhr.statusText}`); // e.g. 404: Not Found
} else { // show the result
alert(`Done, got ${xhr.response.length} bytes`); // responseText is the server
}
};
xhr.onprogress = function(event) {
if (event.lengthComputable) {
alert(`Received ${event.loaded} of ${event.total} bytes`);
} else {
alert(`Received ${event.loaded} bytes`); // no Content-Length
}
};
xhr.onerror = function() {
alert("Request failed");
};
There is also numerous libraries out there to do way simpler XMLHttpRequest.
You could also submit a form, it might be easier.
<form action="/yourPHPFunctionUrl">
<!-- some inputs -->
<button type="submit">Send me ! </button>
</form>

Related

I want to receive a JSON (sendend by POST method of JS xmlHttpRequest()) echo from PHP

The code JS is
var xhr = new XMLHttpRequest()
//console.log(xhr)
xhr.onreadystatechange = function(){
if(xhr.readyState==4){
console.log(xhr)
}
}
xhr.open("POST","https://testepr.harpiastudios.com.br/http-receiver.php")
xhr.setRequestHeader('Content-Type', 'application/json')
function sendText(text){
let dataToSend = {
"text": text
}
console.log(dataToSend)
xhr.send(dataToSend)
}
and the PHP Code is:
$dataToSend = json_decode(file_get_contents('php://input'));
echo($dataToSend->text);
The php file returns
Notice: Trying to get property of non-object in
I need to echo this value cause i need to use for other things. I dont know to have acces from this index of JSON

How to call PHP function from Javascript (ideally without AJAX) [duplicate]

This question already has answers here:
Call php function from JavaScript
(5 answers)
Closed 5 years ago.
Don't really know AJAX that well.. Here is the issue.
I am reading a database within the PHP function that populate some global variables, I can access the variables ok, but I need the php function to be called regularly.
<?php
function thatIwant()
{
//read database
return 10;
}
echo("
<script>
function refreshDiv()
{
//// this is where I need to call the above function.
var refresher = setTimeout('refreshDiv()', 2000);
}
</script>
");
?>
You can't call a PHP function regularly from Javascript without the use of an XmlHttpRequest. PHP is executed when the page is first requested. With an XHR, you could do the following:
function refreshDiv() {
setTimeout(function() {
var xhr = new XmlHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
document.getElementById("refreshDiv").innerHTML =
xhr.responseText;
}
};
xhttp.open("GET", "yourPHPEndpoint.php", true);
xhttp.send();
}, 1000);
}
This would allow you to query your PHP file continuously, and update the contents of the div with the result of the query. This can also be done through jQuery with $.ajax or $.get.

Ajax call failing

I am using Ajax to send information to a server and return a JSON string. This is the code I am using:
function getRequests(folder, mode) {
xhr = new XMLHttpRequest();
xhr.onreadystatechange = singleBook(folder, mode);
xhr.open("GET", "bestreads.php?mode=" + mode + "&title=" + folder, true);
xhr.send(null);
}
function singleBook(folder, mode) {
alert(xhr.responseText);
if (mode == "info") {
var json = JSON.parse(xhr.responseText);
}
}
I have tested my PHP script and I am 100% certain that it properly prints out the correct JSON string for every possible folder name. I have validated the JSON string it creates to confirm this.
However, this code leaves xhr completely empty. I have tried checking the status with xhr.stats but it returns 0, which doesn't make sense to me since I thought it is supposed to return 404 or 200.
This is a school project and I am not allowed to use JQuery, so I need a solution to this that does not use it. I make an Ajax call earlier in my call the same way and it works without any issues, but returns an XML string instead of JSON which makes me think I need to do something else to return the JSON string, but I have no idea what that may be.
PHP code:
function createJson($folder) {
$path = "books/" . $folder . "/info.txt";
$infoFile = file($path);
$info = '{"title":"' . $infoFile[0] . '","author":"' . $infoFile[1] . '","stars":"' . $infoFile[2] . '"}';
print $info;
}
You need to assign a function reference to onreadystatechange instead you are invoking the singleBook function and is assigning the value returned by that to onreadystatechange.
Also need to wait for the ajax request before processing it
function getRequests(folder, mode) {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = singleBook(xhr, folder, mode);
xhr.open("GET", "bestreads.php?mode=" + mode + "&title=" + folder, true);
xhr.send(null);
}
function singleBook(xhr, folder, mode) {
return function() {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
console.log(xhr.responseText);
if (mode == "info") {
var json = JSON.parse(xhr.responseText);
}
}
}
}

XMLHttpRequest sometimes doesn't send string

I'm not sure why this is happening but I will try to explain as much as I already know.
I have a website that allows you to log in with an account stored on a database. Each user can update their own set of data that is also in the same database.
When a user changes data Javascript will post an XMLHttpRequest to a php file on the server. The data is JSON encoded and is decoded in the php file and then stores the data on the database.
The problem is whenever I log into a specific account no data is sent. The string is empty after the request is sent. The post works and the php file runs but no data is present. Here is my code for sending the request in JS:
function sendXMLHttpRequest(data, phpfile){
var xhr;
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
}
else {
throw new Error("Ajax is not supported by this browser");
}
xhr.open('POST', phpfile, true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
if (this.responseText !== null)
document.getElementById('saveresponse').innerHTML = xhr.responseText;
else
alert("Ajax error: No data received");
}else alert("Ajax error: " + this.status);
}
};
xhr.send(data);
}
On the php side:
session_start();
$mysql = new Mysql();
$data = json_decode($_POST['stringData']);
echo 'Data: ' . $data . "<br />";
Normally when I echo the data is returns Array which is what I want but it doesn't echo anything when ever I log into this one specific account, the data sent is just a string where stringData is a JSON. Is there a way to see if anything IS stored there? Also if nothing is being sent why could this be? Any suggestions for my code?
Make sure the request doesn't get cached by adding a random parameter:
querystring = 'validate=' + validate+ "&rand=" + new Date().getTime();

JQM - How to get dynamic data when page loads using XMLHttpRequest? [duplicate]

This question already has answers here:
How to return AJAX response Text? [duplicate]
(2 answers)
Closed 9 years ago.
I use pageinit to load page. I call an XMLHttpRequest to send and get request to PHP programs on Linux, using RESTful API on server side. The server side accept an array I send to it and echo an JSON back. It all work well. However, HTTP_GET functions returns back to page and displays content before it finished and got a response from server.
How can I prevent it from going back before it responded?
pageinit
$(document).on("pageinit","#quote_open1",function(){
alert('pageinit quote_open1');
openPage(); });
openPage
function openPage(url, jsontest){
var jsonResponse=HTTP_GET( url, jsontest);
alert('!!!!!!!!!!!!!!!!-->'+jsonResponse);
}
HTTP_GET
function HTTP_GET( url, jsonToSend){
alert('START HTTP_GET');
var jsonResponse;
//send get request to server
xhr = new XMLHttpRequest();
xhr.open("GET",url+"jsonToSend",true); //open server connection
xhr.send();//this is where json string will be sent out
//
//this function send
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4) //read server response
{
alert(xhr.readyState);
jsonResponse=xhr.responseText;
alert("!!!jsonResponse="+jsonResponse);
alert("!!!xhr.responseText"+xhr.responseText);
return "server returned a response 1"; //RETURNS this all the time
}
};
alert('END HTTP_GET');
if (xhr.readyState == 4) return "server returned a response 2"; //want to return this when leaves this function
return "stil in progress returns before it's finished";
};
(this 3 functions are in different js)
Thanks.
what you miss here is the fact that xhr is asynchrone, so your function HTTP_GET returns before the request is done.
You could use a callback function like this :
$(document).on("pageinit","#quote_open1",function(){
console.log('pageinit quote_open1');
openPage(); });
function openPage(){
var doTheJob = function(jsonResponse){ console.log('jsonResponse : '+jsonResponse); }
HTTP_GET( url, doTheJob);
}
function HTTP_GET( url,callBackFunc){
console.log('START HTTP_GET');
var jsonResponse;
//send get request to server
xhr = new XMLHttpRequest();
xhr.open("GET",url,true); //open server connection
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4) //read server response
{
callBackFunc(xhr.responseText);
}
};
xhr.send();//this is where json string will be sent out
//
console.log('END HTTP_GET');
};

Categories

Resources