I can't send PHP variables to JavaScript - javascript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};

The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.

I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.

Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

Related

Posting js variables to PHP not running in any method

In my JS code, I take in 3 inputs on a html page and save them to local storage. I then want to send these variables to php in order to save them to my database. No matter how hard I try no tutorial using ajax, jquery etc allows me to successfully post and echo variables from javascript in my php code. I see no reason why my code below doesn't echo the variables, but it doesn't.
Full code: https://codeshare.io/ayvK9e
Exact PHP elements (just trying to send normal variables right now as it still won't work"
PHP:
foreach($_POST as $post_var){
echo($post_var);
}
JS:
const xhr = new XMLHttpRequest();
xhr.onload = function(){
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText
};
xhr.open("POST", "eDBase.php");
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("name=dominic&message=bumbaclaat");
If $post not work try using input php
$data = json_decode(file_get_contents('php://input'), true);
When calling my function with the inputs onclick=showFunction; I was passing nothing to the function. In order for my values to be echoed in php I had to pass a parameter to the function onclick=function('text or variable'); IDK how I missed that.
Try using the FormData()
let form = new FormData();
form.append('name', 'dominic');
form.append('message', 'bumbaclaat');
const xhr = new XMLHttpRequest();
xhr.open("POST", "eDBase.php");
xhr.onreadystatechange = function(){
if(xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
const serverResponse = document.getElementById("serverResponse");
serverResponse.innerHTML = this.responseText;
}
else console.log('error')
};
xhr.send(form);
Comment out the setRequestHeader to test it.
And at PHP
if(isset($_POST['name'])){
echo $_POST['name'];
echo $_POST['message'];
}
else{
echo 'There was a problem';
}

Calling JavaScript function after updating table with PHP

I have a simple website that uses JavaScript to collect user input and sends data to PHP script (script is an external php file) via AJAX request. PHP script updates database with this information.
Now, i have a JS function on my website that i want to call only after PHP script is sucessfuly run and database updated. I don't need any data from database or PHP script, i only want to make sure that database is updated before calling this Javascript function.
This is what AJAX request looks like:
function ajax_post(){
if (typeof featureId !== 'undefined') {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "parse_file.php";
var fn = featureId;
var vars = "featureId="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
hilites.destroyFeatures();
featureId = undefined;
}
else {
window.alert("Select polygon first");
}
}
What is the best way to do this? Some examples would really help.
Looking at your code, you simply need to call the function around this part:
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
// CALL YOUR FUNCTION HERE
}
}
The best solution is to use a Promise. However, this is not supported in IE 11, so you will need to use a polyfill on some browsers.
Here is an example using jQuery.
// This is the function you want to call after the script succeeds
function callbackSuccess() {
console.log('Done!');
}
// This is the data you want to submit to the PHP script
var myData = {
hello: "world"
};
// This is the actual AJAX request
$.post('/my-script.php', myData).done(function(){
callbackSuccess();
});
Add this to the end of your php save-function:
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('status' => 'SUCCESS'));
Making the call:
$.getJSON('url_to_your_php_file.php', function(data) {
if (data.status == 'SUCCESS') {
console.log('Save complete');
}
else {
console.log('oops, something went wrong!!');
}
});
It's possible to return something like ERROR, this will return:
console.log('oops, something went wrong!!');
You may try the following:
In php you can use return code from sql statement
echo $sqlResult = $conn->query($sqlStatement);
On Javascript, you can try the following
$.ajax({
url: 'file.php',
type: 'POST',
data: {
data1 : data1,
data2: data2
},
success: function(data){
if(data == success_code){
alert("Success")
}
}
Hope this helps!
Completing ajax request without errors does not mean that the data is saved to DB without errors.
Even if your PHP script fails to save the data, it probably echos some error message or even empty output as regular HTTP response, and it would show as success as far as the ajax request goes.
If your intention is to make sure that the data is really saved before calling the JS function, then the PHP script should containg enough error handling.
If you write the PHP script to return response status code based on the real outcome of save operation, then you can rely on those status codes in ajax response handling (success = ok, error = not ok).
Bu what I usually do, is that instead of using HTTP status codes, I echo "OK" or something similar at the end of succesfull PHP execution (and "ERROR" if there are any errors), and then check for those strings in ajax response handler (hr.responseText in your code).
Maby you have to try this:
setTimeout(function(){
//your function here...
}, 500);

Posting plain text on php using JavaScript

I need to use "POST" consisting of value and a variable structure using JavaScript. The plain text should be sent to a PHP page where it will be displayed. How should I get about this?
From what I understand according to my requirement. It needs to be something like a FROM submission, but run only using JavaScript.
document.body.innerHTML += '<form id="content" action="http://10.10.10.10/index.php" method="post"><input type="hidden" name="info" value="'+plainText+'"></form>';
document.getElementById("content").submit();
I tried this code as well.Do you have an Idea on how to display the text sent here on a PHP page?
var request = new XMLHttpRequest();
request.open("POST", "10.10.10.10/index.php", true);
request.onreadystatechange = function () {
if(request.readyState === 4){
if(request.status === 200 || request.status == 0){
request.setRequestHeader("Content-type","text/plain;charset=UTF-8");
request.setRequestHeader("Content-length", plainText.length);
request.send(plainText);
}
}
}
request.send(null);
You need to use ajax, if you need plain javascript then you should do something like this:
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(xhr.responseText);
}
};
request.open('POST', 'script.php', true);
request.send("<YOUR TEXT>");
if you use jQuery then simple:
$.post('script.php', '<YOUR TEXT>', function(response) { });
and then you can read it in php using:
file_get_contents('php://input');
or (deprecated):
$GLOBALS['HTTP_RAW_POST_DATA'];

readystate never reaching 4

In the code below I try to post some data to a table and then retrieve several records from the table afterwards. For testing purposes I have only included a dummy query in the php, which returns a valid xml.
But the Javascript readystate only reach readystate 1 (twice). As the php seems to be working fine I suspect I have scripted the javascript incorrectly. Is it a problem with the "request" variable?
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#name + .throw_error').empty(); //Clear the messages first
var name = $('input[name=name]').val();
var request = !window.XMLHttpRequest ? new ActiveXObject('Microsoft.XMLHTTP') : new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
var xml = request.responseXML;
var dynamiclist = '';
document.getElementById("myLink").innerHTML = '';
var posts = xml.documentElement.getElementsByTagName("post");
for (var i = 0; i < posts.length; i++) {
var Msg = posts[i].getAttribute("Msg");
alert("test");
var dynamiclist = dynamiclist + '<article class="middleContent"><header><h2>' + Msg + '</h2></header> </article>';
document.getElementById("myLink").innerHTML = dynamiclist;
};
};
};
request.open('POST', 'process.php', true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.send('name=' + name);
});
});
Using jQuery makes sense here.
Simple solution however most probably is to simply remove the last "true" in request.open(), which makes the request an asynchronous, non-blocking one (which it really should be anyway). MDN also states at onreadystatechange that you shouldn't be using it with synchronous requests (aka requests that have "true" as third argument for open())
Source: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
Try preventing the default form event from firing:
$('form').submit(function(event) {
event.preventDefault();
This prevents the form element from reloading the browser window.

JavaScript: reading $_POST & $_FILES variables after AJAX submission

I'm submitting a form through AJAX for the express purpose of displaying a pre-selected image. Selecting an image from the local drive will trigger the "onchange" event for the file-type input, and in turn call the AJAX routine. It works fine, and upon a successful "move_uploaded_file", the PHP handler returns the validated file name. The following illustrates how the AJAX submission was effected:
var xhr = new XMLHttpRequest();
var xForm = new FormData(document.forms.namedItem("form"));
xhr.open("POST", "handler.php", true);
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
xhr.send(xForm);
Instead of getting the handler to return the file name, is there any way to access the $_POST and $_FILES variables after returning from an AJAX submission? This is usually possible when returning from a normal form post, using:
<?php echo $_POST['stringInput'];?>
<?php echo $_FILES['imageInput']['fileName'];?>
but I'm not able to get anything in this case.
Thanking you,
Sofia
EDIT: in case it may be relevant, the handler is not in the same HTML script, but in a separate PHP file. Thanks again!
Because you made a mistake in code typing here:-
Old code
x.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
New code
xhr.onreadystatechange = function(){
if(xhr.readyState == 4 && xhr.status == 200){
document.getElementById("imgDiv").src = xhr.responseText;
}
}
Means replace x.onreadystatechange with xhr.onreadystatechange

Categories

Resources