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
Related
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.
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
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
Yes, there are lots of questions to similar stuff but I can't figure it out, sorry.
I have a file with some javascript variables, depending on user input (but no form) and a normal HTML link to my php file.
<script>
function doStuff() {
var a = 'foo';
var b = 'bar';
window.location = 'newfile.php?a=' + a + '&b=' + b;
}
</script>
go to new php file
That works fine, I can access the data in newfile.php with $_GET.
newfile.php:
<?php
$a= $_GET['a'];
$b= $_GET['b'];
echo($a,$b); // works
?>
But I'd like to use POST. I guess I have to use ajax for that but how exactly?
jQuery is included btw so I could use $.ajax()
Any help is highly appreciated :)
EDIT:
Thanks for the quick response guys!
The JSON parsing doesn't work, I can't really figure out why - after clicking on the button the browser window disappears for a split second and I'm on the same page again which is unresponsive now :(
I went with the following code:
jQuery.post('newfile.php',{'a': a, 'b': b}); //curious: with or without ''?
setTimeout(function () {
window.location = 'newfile.php';
}, 5000); //this will redirct to somefile.php after 5 seconds
newfile.php:
$a= $_POST['a'];
$b= $_POST['b'];
echo('Testing: '.$a);
Right after clicking I can see the correct output in Firebug (Testing: foo) but of course after redirecting to the site the values are lost and I'm left with "Testing: "
What can I do?
You can use ajax to achieve this. Following is the code which works on a button click or anchor click.
HTML
<button type="button" id="button1">Click me </button>
Ajax
$('#button1').click(function() {
var a = $('#IDofYourFormelement').val();
var b = $('#IDofYourFormSecondElement').val();
$.post('/somefile.php', {'somevariable': a, 'variableB': b}, function(data) {
var parsed = JSON.parse(data);
if (parsed == 'success') {
setTimeout(function () {
window.location = '/somefile.php';
}, 3000);//this will redirct to somefile.php after 3 seconds
}
else
{
alert ('Invalid details');
}
});
});
and then in your somefile.php you can access it as
$a = $_POST['somevariable'];
$b = $_POST['variableB'];
//do some stuff and return json_encoded success/failure message
You can use the new with HTML5 FormData();
Code snippet from https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects see also https://developer.mozilla.org/en/docs/Web/API/FormData and http://caniuse.com/#feat=xhr2 for browser support
var formData = new FormData();
formData.append("username", "Groucho");
formData.append("accountnum", 123456); // number 123456 is immediately converted to string "123456"
var request = new XMLHttpRequest();
request.open("POST", "http://foo.com/submitform.php");
request.send(formData);
I guess you are trying to post the variables using javascript and display the page post executing your post variables. Found a similar question and an answer in here - JavaScript post request like a form submit.
EDIT
The window.location will call another instance of you page and then will assign or replace the current doc, hence your previous post parameters are lost. If you want the page with your post parameters passed you need to do a form submit to your php page with method=POST also with the post parameters. That's what is written in the above stackoverflow link I shared.
I am writing some code in JavaScript. In this code i want to read a json file. This file will be loaded from an URL.
How can I get the contains of this JSON file in an object in JavaScript?
This is for example my JSON file located at ../json/main.json:
{"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]}
and i want to use it in my table.js file like this:
for (var i in mainStore)
{
document.write('<tr class="columnHeaders">');
document.write('<td >'+ mainStore[i]['vehicle'] + '</td>');
document.write('<td >'+ mainStore[i]['description'] + '</td>');
document.write('</tr>');
}
Here's an example that doesn't require jQuery:
function loadJSON(path, success, error)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
if (success)
success(JSON.parse(xhr.responseText));
} else {
if (error)
error(xhr);
}
}
};
xhr.open("GET", path, true);
xhr.send();
}
Call it as:
loadJSON('my-file.json',
function(data) { console.log(data); },
function(xhr) { console.error(xhr); }
);
XHR can be used to open files, but then you're basically making it hard on yourself because jQuery makes this a lot easier for you. $.getJSON() makes this so easy to do. I'd rather want to call a single line than trying to get a whole code block working, but that's up to you...
Why i dont want to use jQuery is because the person i am working for doesn't want it because he is afraid of the speed of the script.
If he can't properly profile native VS jQuery, he shouldn't even be programming native code.
Being afraid means he doesn't know what he is doing. If you plan to go for performance, you actually need to know how to see how to make certain pieces of code faster. If you are only just thinking that jQuery is slow, then you are walking into the wrong roads...
JSON has nothing to do with jQuery.
There is nothing wrong with the code you have now.
To store the variable mainStore, it is a variable in that json.
You should store that json to a variable:
var myJSON = {"mainStore":[{vehicle:'1',description:'nothing to say'},{vehicle:'2',description:'nothing to say'},{vehicle:'3',description:'nothing to say'}]};
var mainStore = myJSON.mainStore;
//.. rest of your code.
I understand that by "reading a json file" you mean making the request to the url that returns json content. If so, then can you explain why you don't want to use jQuery for this purpose? It has $.ajax function that is perfectly suitable for this and covers the browsers' differences.
If you want to read the file then you have to do it server-side, e.g. php and provide it somehow to the dom (there are different methods) so js can use it. Reading file from disk with js is not possible.
function loadDoc() {
const xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(xhttp.responseText)
}
};
xhttp.open("GET", "./user.json");
xhttp.send();
}
Naming using the linux filename structure
You can store the responseText to a variable or whatever you want to do with it