AJAX xmlhttp.send() not working - javascript

I'm a complete and utter AJAX noob and have been sitting with the same problem for the last 5 hours.
My script code
<script language='javascript'>
function upvote(id ,username)
{
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
}
};
xmlhttp.open("GET", "vote.php?id=" +id+"&username=" +username, true);
xmlhttp.send();
}
</script>
My onclick link,
<a href='javascript:void(0)' onclick='upvote($id,$username)'></a>
$_GET is used to retrieve parameters sent via the URL of the page. For example
../vote.php?id=3&username=anor
My php file works perfect when i tried that.
I don't think there's anything wrong with the PHP anyway. For some reason however, xmlhttp.send(params) is still not sending the required variables to the vote.php file. I tried post AJAX request but it didn't work either.

edit them
If php file
$id = '1';
$username = 'suman';
echo '';
?>

If this is part of your PHP code
onclick='upvote($id, $username)'
it won't work. It should be
onclick='upvote($id, "$username")'
instead. Let's see the example that you posted: $id=3 and $username=anor. This would result in
onclick='upvote(3, anor)'
As long as there is no Javascript variable with the name anor, this would be equivalent to
onclick='upvote(3, undefined)'
Do you get that?
PS: The upvote function itself seems to be fine

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

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

Writing in another file with javascript

I have a php script (just for calculation) and a html file. Let's say the php file has finished its calculation and the solution is 10. The following line is in the body of the just mentioned html file:
<div id="here"></div>
Now I want the php file to write the 10 into the html. I thought of adding a few lines of javascript at the end of the php to make the job. The question is if this is even possible with something like (index.html).getElementById(here).innerHTML or something. Both files are in the same folder and setting the proper permission shouldn't be a problem.
I know I could put everything in one file but this is part of a bigger project. I just adapted my problem on this simple example to avoid that you need to read plenty of lines.
Your Script should look like this to get response from PHP
<script>
function loadDoc() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("here").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "yourphp.php?q=" + str, true);
xmlhttp.send();
}
</script>
Hope this solves your problem
ref: http://www.w3schools.com/ajax/ajax_php.asp
PHP is server-side and Javascript is client-side. I don't recommend you to use embedded PHP but you should take a look at Ajax Requests.
Here's some documentation

How to call a JavaScript function declared in a PHP file? [duplicate]

I want to know is it possible to call a php function within javascript, only and only when a condition is true. For example
<script type="text/javascript">
if (foo==bar)
{
phpFunction(); call the php function
}
</script>
Is there any means of doing this.. If so let me know. Thanks
PHP is server side and Javascript is client so not really (yes I know there is some server side JS). What you could do is use Ajax and make a call to a PHP page to get some results.
The PHP function cannot be called in the way that you have illustrated above. However you can call a PHP script using AJAX, code is as shown below. Also you can find a simple example here. Let me know if you need further clarification
Using Jquery
<script type="text/javascript" src="./jquery-1.4.2.js"></script>
<script type="text/javascript">
function compute() {
var params="session=123";
$.post('myphpscript.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
}
</script>
Barebones Javascript Alternative
<script type="text/javascript">
function compute() {
var params="session=123"
var xmlHttp;
var addend_1=document.getElementById("par_1").value;
var addend_2=document.getElementById("par_2").value;
try
{
xmlHttp = new XMLHttpRequest();
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("No Ajax for YOU!");
return false;
}
}
}
xmlHttp.onreadystatechange = function()
{
if (xmlHttp.readyState == 4) {
ret_value=xmlHttp.responseText;
var myObject = eval('(' + ret_value + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
}
}
xmlHttp.open("POST", "http://yoururl/getjs.php", true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
</script>
No that's not possible. PHP code runs before (server-side) javascript (client-side)
The other answers have it right.
However, there is a library, XAJAX, that helps simulate the act of calling a PHP function from JavaScript, using AJAX and a particularly designed PHP library.
It's a little complicated, and it would be much easier to learn to use $.get and $.post in jQuery, since they are better designed and simpler, and once you get your head around how they work, you won't feel the need to call PHP from JavaScript directly.
PHP always runs before the page loads. JavaScript always runs after the page loads. They never run in tandem.
The closest solution is to use AJAX or a browser redirect to call another .php file from the server.

Categories