AJAX in javascript does not communicate with php mailer after SSL upgrade - javascript

OK, so I have many quizzes which previously worked fine on my http:// website, using AJAX javascript calls to a php mailer program to send data about the quiz and mail it to the recipient.
I have upgraded the site to https:// and now none of the scripts work. The bones of the javascript are contained in the following function:
function postIt() {
var http = new XMLHttpRequest();
var url = "../mail/summary.php";
var params = "realname="+myName+"&rightAnswers="+correct+"&percentageScore="+percentage+"&wrongArray="+wstore+"&asked="+numq+"&mins="+minutes+"&secs="+seconds+"&deliver="+destination+"&testName="+test;
http.open("GET", url+"?"+params, true);
http.onreadystatechange = function() { //Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
//alert(http.responseText);
}
}
http.send(null);
}
The php mailer receives the variables and mails them. Again the bones of the php are below:
$data1=$_GET["realname"];
$data2=$_GET["rightAnswers"];
$data3=$_GET["asked"];
$data4=$_GET["mins"];
$data5=$_GET["secs"];
$data6=$_GET["percentageScore"];
$data7=$_GET["deliver"];
$data8=$_GET["testName"];
$myWrongArray = explode(',', $_GET["wrongArray"]);
$sendTo = "results#ibchem.com".", ".$data7;
$subject = $data8." summary results for ".$data1;
The code is fine for http:// websites (I have tested it again on http://mypchem.com/test) but fails on https://ibchem.com/test.
My level of understanding is pushed to the limit as I can code (average) in javascript, html, css, php etc. but have no idea how to solve this problem.
Any help please?
Charco

Related

PHP not detecting POST JSON data from JavaScript request

I am in need of a little help with a small bit of my code that is essential to my application. I am making a small clicker game, and I want users to be able to save and load data via PHP to my server. I do not want to use Local Storage to make it harder for anyone to edit their economy and "cheat". When the user clicks on a save button I have, it fires my vue method which initializes the saving. I have had no problem getting the data into a JSON format, however I cannot get PHP to read this data via POST. I have checked for network headers, and it shows that stuff is being sent, it seems that PHP just isn't catching it. I'll include the code for the JS part and PHP part below. The PHP is only set to echo if the array_key_exists right now, as after getting this sorted out I will easily be able to handle the rest. Any help would be greatly appreciated!
I have tried to follow this, which has not worked so far Send JSON data from Javascript to PHP?
JS
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
console.log(saveData);
}
PHP
<?php
if (array_key_exists("saveData", $_POST)) {
echo "<p>SALO Ready!</p>";
}
?>
Decode the JSON string at the PHP end before accessing values, like this:
<?php
if(isset($_POST['saveData'])){
$result = json_decode($_POST['saveData'], true);
// use $result['saveMoney'] and $result['saveCrystals'] accordingly
}
?>
Update# 1:
As OP commented below, I expect that it will print "SALO Ready" but it is instead doing nothing
That's because you are not using responseText property of XMLHttpRequest object to see the text received from the server. Use below snippet to see the response text.
saloOut: function() {
var saveData = {
saveMoney: this.money,
saveCrystals: this.crystals,
};
saveData = "saveData=" + (JSON.stringify(saveData));
var sendData = new XMLHttpRequest();
sendData.open("POST", "salo.php", true);
sendData.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
sendData.send(saveData);
sendData.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
}
};
}
Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/responseText

XMLHTTPRequest between Python and Javascript

Here is a function in javascript which is currently being used to update a database. Currently when it is run, the entire python script is outputted to the javascript function intead of just the print statement. Is it possible, without importing any extra modules, for data to be sent between these two sections of code? if so, how would I do it?
Javascript:
function sendmsg(){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
console.log(xhttp.responseText)
document.getElementById("name").innerHTML = '';
}
};
xhttp.open("GET", URL+'/SendMsg.py', true);
xhttp.send();
}
Python:
import cgi
import cgitb; cgitb.enable()
import sqlite3
mydb = 'messenger.db'
conn = sqlite3.connect(mydb)
cursor = conn.cursor()
print('alex')
"""
form = cgi.FieldStorage()
Sender = form.getvalue('UserName')
Reciever = form.getvalue('Class')
message = form.getvalue('Message')
val = {"Sender":Sender, "Reciever":Reciever, "message":message}
cursor.execute('''INSERT INTO Message (Message, SenderID, ClassID) VALUES (:message, :Sender, :Reciever)''',val)
conn.commit()
cursor.close()
"""
Many thanks in advance
Ive fixed this problem, There was a error in the config file of apache which didnt allow python cgi to run how it is created to run. For future, make sure that the required lines of code in the config files are uncommented.
I would suggest to take a look at Flask or Django. You can implement a RESTful API using Django or Flask, read the HTTP request there, extract parameter and send back appropriate response.
Right now you are requesting the server to send xhttp.open("GET", URL+'/SendMsg.py', true); SendMsg.py and it's sending that.

Sending PHP variables to JavaScript through AJAX

I'm writing a program that will generate random numbers on both JavaScript and PHP pages and display them on the JavaScript/Html page.
So far I have both pages successfully generating the numbers, but I don't know how to reach out from the JavaScript page to the external PHP page to retrieve the number and store it into a JS variable.
Here's what I have so far.
JavaScript:
function roll()
{
var rollOne; //= Math.floor((Math.random() * 6) + 1);
var rollTwo;
var request = new XMLHttpRequest();
request.open("GET", "filename.php", true);
request.send();
}
I know the JS random is commented out, that's not important right now.
PHP:
<?php
sleep(5);
$random =(rand(1,6));
echo $random;
?>
So how do I take $random from the php document, send it over to the JavaScript page, and store it into a variable to access later?
I'm sure a similar question has been asked thousands of times before on this site, but from what I have searched I haven't found anything that made sense to me.
The Mozilla docs on AJAX explain it well. Before calling .open and .send, set up a function for XMLHttpRequest to run when the response comes back from the server:
request.onreadystatechange = function() {
if (request.readyState === XMLHttpRequest.DONE) {
// The request is complete
if (request.status === 200) {
// Server responded with HTTP status code 200 (OK)
// Here's your server's random value
random = request.responseText;
} else {
alert('There was a problem with the request.');
}
}
}
You can access the responseText value of the returned data. In other words, the data that you echo from php can be accessed in your javascript using responseText and stored in a variable.

POST data with ajax

I'm trying to save a few lines of text in a textarea with ajax targeting a classic asp file.
I'm not sure how to use ajax when when it comes to sending data with POST method and NOT using jQuery, didn't find any questions concerning this here either, no duplicate intended.
Ajax function:
function saveDoc() {//disabled
var xhttp = new XMLHttpRequest();
var note = document.getElementById("note");
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("0").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "saveNote.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(note);
ASP Classic:
set fs=Server.CreateObject("Scripting.FileSystemObject")
set f=fs.OpenTextFile("c:\inetasp\1.txt",8,true)
dim note
note = RequestForm("note")
f.Write(note)
f.Close
Response.Write("Works.");
set f=nothing
set fs=nothing
I'm aware there might be a lot wrong with the .asp since i couldn't find any specific info about how to handle ajax requests with Classic ASP correctly.
Any suggestions on how to make this work without jQuery are welcome.
I cannot test your code as I don't have a backend running on my machine right now. But I can already tell you a few things:
you are calling xhttp.send(note); but your note is a DOM element. It should be a string with a querystring format.
in your server side code you call RequestForm is it a custom function you have previously defined ? The usual syntax is Request.Form
Hope it can help

accessing php variables using javascript

I've done created a webpage, set up appache2 on ubuntu server so I can view this page over the internet. I've installed php5 and MySQL and would like to access information in the database on the webpage that I've created.
Right now, I've got a file test.php that accesses the database and puts some of the information into variables. I've scripted using javascript something that will change the webpage content at the click of a button.
Now, the webpage crashes whenever the button is pushed as it says the variables are undefined or null references. Fair enough, but my question is how does one access variables on a .php file through the webpage? Can a browser use information in the .php file if I script it into the page?
I was told that the php file would be parsed automatically. I'm guessing that server side this page is being accessed but I can use it through web browser.
Edit:
//check connection
if (mysqli_connect_errno()){
echo "failed to connect to MySQL: " . mysqli_connect_error();
}
$grab = mysqli_query($con, "SELECT * FROM table");
$row = mysqli_fetch_array($grab);
$name = $row["name"];
$color = $row["color"];
$price = $row["price"];
$n1 = $name[0];
$c1 = $color[0];
$p1 = $price[0];
?>
Ok so I changed the php file to this, so now all it is doing is defining variables. I installed a couple of MySQL mods and no problems now.
next issue is how do I get use php variables in javascript
function load(){
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "test.php", true);
xmlhttp.send();
xmlhttp.onreadystatecahnge = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
document.getElementById("itemNameLink1").innerHTML = "<?php echo $n1;?>;
}
}
}
So onload this ajax function should run and change itemNameLink1 to the php variable $n1, only it doesn't and I just get an empty string. Everything should be set up right but using the php variable seems impossible. would it be any easier with the jquery get command, I'm guessing that unless I sort this out I'm gonna struggle.
I'm also assuming a few things, I've checked error logs and the php file is active assuming I've connected right it should be accessing the database. I'm very new so I do not know how to test this.
I'm also assuming that when php file is in the server webpage file directory. that it is automatically working. again very new to setting up a server so using ubuntu server and being familiar with all the commands that I need to use or how apache2 operates is difficult for me.
PHP Is executed on the server, your client receives the result as a plain text/html document.
Your browser runs the javascript when it received the plain document, so you can't access PHP vars directly with javascript.
But you could set javascript variables when the page is generated on the server like this
<?php $myPhpVar = 'Hello World'; ?>
<script>
//This line would result in var test = "Hello World"; when send to client
var test = "<?=$myPhpVar?>";
alert(test);
</script>
Furthermore you can execute requests to your server with javascript (so you can read the result from test2.php as example, and use that somewhere on your page). http://en.wikipedia.org/wiki/Ajax_(programming)
Pure javascript: http://en.wikipedia.org/wiki/XMLHttpRequest
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
var DONE = this.DONE || 4;
if (this.readyState === DONE){
alert(this.readyState);
}
};
var action = 'doSomethingOnServer';
request.open('GET', 'test2.php?action=' + action, true);
request.send(null);
Jquery: http://api.jquery.com/jquery.ajax/
<script>
var action = 'doSomethingOnServer';
$.ajax({
url: "test2.php?action=" + action,
}).done(function(result) {
alert(result);
});
<script>
For testing if your php works on your server create a file info.php (or something). and add this to the file
<?php phpinfo(); ?>
If you access that page you should get a page with a lot of information about your php configuration.
I'm not sure how you did install your php, but on a development machine you can change a few things in your php.ini that makes life easier
display_startup_errors = 1
display_errors = 1
error_reporting = E_ALL
See http://php.net/manual/en/errorfunc.configuration.php#ini.error-reporting when you change your php.ini don't forget to restart your apache
JSON Example:
data.php
<?php
$db_result = array(array('name' => 'record1'), array('name' => 'record2'));
echo json_encode($db_result);
?>
index.php
<script>
$.ajax({url: 'data.php', dataType: 'json'}).done(function(result) {
//result = an object from your database (in this case an array with objects with the property name)
alert(result);
alert(result[0].name);
}
</script>

Categories