Pass javascript variable to external php file - javascript

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.

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

call PHP function inside JS [duplicate]

Is there a way I can run a php function through a JS function?
something like this:
<script type="text/javascript">
function test(){
document.getElementById("php_code").innerHTML="<?php
query("hello"); ?>";
}
</script>
<a href="#" style="display:block; color:#000033; font-family:Tahoma; font-size:12px;"
onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
I basically want to run the php function query("hello"), when I click on the href called "Test" which would call the php function.
This is, in essence, what AJAX is for. Your page loads, and you add an event to an element. When the user causes the event to be triggered, say by clicking something, your Javascript uses the XMLHttpRequest object to send a request to a server.
After the server responds (presumably with output), another Javascript function/event gives you a place to work with that output, including simply sticking it into the page like any other piece of HTML.
You can do it "by hand" with plain Javascript , or you can use jQuery. Depending on the size of your project and particular situation, it may be more simple to just use plain Javascript .
Plain Javascript
In this very basic example, we send a request to myAjax.php when the user clicks a link. The server will generate some content, in this case "hello world!". We will put into the HTML element with the id output.
The javascript
// handles the click event for link 1, sends the query
function getOutput() {
getRequest(
'myAjax.php', // URL for the PHP file
drawOutput, // handle successful request
drawError // handle error
);
return false;
}
// handles drawing an error message
function drawError() {
var container = document.getElementById('output');
container.innerHTML = 'Bummer: there was an error!';
}
// handles the response, adds the html
function drawOutput(responseText) {
var container = document.getElementById('output');
container.innerHTML = responseText;
}
// helper function for cross-browser request object
function getRequest(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
The HTML
test
<div id="output">waiting for action</div>
The PHP
// file myAjax.php
<?php
echo 'hello world!';
?>
Try it out: http://jsfiddle.net/GRMule/m8CTk/
With a javascript library (jQuery et al)
Arguably, that is a lot of Javascript code. You can shorten that up by tightening the blocks or using more terse logic operators, of course, but there's still a lot going on there. If you plan on doing a lot of this type of thing on your project, you might be better off with a javascript library.
Using the same HTML and PHP from above, this is your entire script (with jQuery included on the page). I've tightened up the code a little to be more consistent with jQuery's general style, but you get the idea:
// handles the click event, sends the query
function getOutput() {
$.ajax({
url:'myAjax.php',
complete: function (response) {
$('#output').html(response.responseText);
},
error: function () {
$('#output').html('Bummer: there was an error!');
}
});
return false;
}
Try it out: http://jsfiddle.net/GRMule/WQXXT/
Don't rush out for jQuery just yet: adding any library is still adding hundreds or thousands of lines of code to your project just as surely as if you had written them. Inside the jQuery library file, you'll find similar code to that in the first example, plus a whole lot more. That may be a good thing, it may not. Plan, and consider your project's current size and future possibility for expansion and the target environment or platform.
If this is all you need to do, write the plain javascript once and you're done.
Documentation
AJAX on MDN - https://developer.mozilla.org/en/ajax
XMLHttpRequest on MDN - https://developer.mozilla.org/en/XMLHttpRequest
XMLHttpRequest on MSDN - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
jQuery - http://jquery.com/download/
jQuery.ajax - http://api.jquery.com/jQuery.ajax/
PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.
The only way to execute PHP from JS is AJAX.
You can send data to server (for eg, GET /ajax.php?do=someFunction)
then in ajax.php you write:
function someFunction() {
echo 'Answer';
}
if ($_GET['do'] === "someFunction") {
someFunction();
}
and then, catch the answer with JS (i'm using jQuery for making AJAX requests)
Probably you'll need some format of answer. See JSON or XML, but JSON is easy to use with JavaScript. In PHP you can use function json_encode($array); which gets array as argument.
I recently published a jQuery plugin which allows you to make PHP function calls in various ways: https://github.com/Xaxis/jquery.php
Simple example usage:
// Both .end() and .data() return data to variables
var strLenA = P.strlen('some string').end();
var strLenB = P.strlen('another string').end();
var totalStrLen = strLenA + strLenB;
console.log( totalStrLen ); // 25
// .data Returns data in an array
var data1 = P.crypt("Some Crypt String").data();
console.log( data1 ); // ["$1$Tk1b01rk$shTKSqDslatUSRV3WdlnI/"]
I have a way to make a Javascript call to a PHP function written on the page (client-side script). The PHP part 'to be executed' only occurs on the server-side on load or refreshing'. You avoid 'some' server-side resources. So, manipulating the DOM:
<?PHP
echo "You have executed the PHP function 'after loading o refreshing the page<br>";
echo "<i><br>The server programmatically, after accessing the command line resources on the server-side, copied the 'Old Content' from the 'text.txt' file and then changed 'Old Content' to 'New Content'. Finally sent the data to the browser.<br><br>But If you execute the PHP function n times your page always displays 'Old Content' n times, even though the file content is always 'New Content', which is demonstrated (proof 1) by running the 'cat texto.txt' command in your shell. Displaying this text on the client side proves (proof 2) that the browser executed the PHP function 'overflying' the PHP server-side instructions, and this is because the browser engine has restricted, unobtrusively, the execution of scripts on the client-side command line.<br><br>So, the server responds only by loading or refreshing the page, and after an Ajax call function or a PHP call via an HTML form. The rest happens on the client-side, presumably through some form of 'RAM-caching</i>'.<br><br>";
function myPhp(){
echo"The page says: Hello world!<br>";
echo "The page says that the Server '<b>said</b>': <br>1. ";
echo exec('echo $(cat texto.txt);echo "Hello world! (New content)" > texto.txt');echo "<br>";
echo "2. I have changed 'Old content' to '";
echo exec('echo $(cat texto.txt)');echo ".<br><br>";
echo "Proofs 1 and 2 say that if you want to make a new request to the server, you can do: 1. reload the page, 2. refresh the page, 3. make a call through an HTML form and PHP code, or 4. do a call through Ajax.<br><br>";
}
?>
<div id="mainx"></div>
<script>
function callPhp(){
var tagDiv1 = document.createElement("div");
tagDiv1.id = 'contentx';
tagDiv1.innerHTML = "<?php myPhp(); ?>";
document.getElementById("mainx").appendChild(tagDiv1);
}
</script>
<input type="button" value="CallPHP" onclick="callPhp()">
Note: The texto.txt file has the content 'Hello world! (Old content).
The 'fact' is that whenever I click the 'CallPhp' button I get the message 'Hello world!' printed on my page. Therefore, a server-side script is not always required to execute a PHP function via Javascript.
But the execution of the bash commands only happens while the page is loading or refreshing, never because of that kind of Javascript apparent-call raised before. Once the page is loaded, the execution of bash scripts requires a true-call (PHP, Ajax) to a server-side PHP resource.
So, If you don't want the user to know what commands are running on the server:
You 'should' use the execution of the commands indirectly through a PHP script on the server-side (PHP-form, or Ajax on the client-side).
Otherwise:
If the output of commands on the server-side is not delayed:
You 'can' use the execution of the commands directly from the page (less 'cognitive' resources—less PHP and more Bash—and less code, less time, usually easier, and more comfortable if you know the bash language).
Otherwise:
You 'must' use Ajax.

Ajax and dynamic url

I have been following a tutorial on javascript and php and modifying it to my own personal tastes.
I've run into something i dont know how to fix, and i cant find anything online to help me fix it either.
The tutorial in question has shown me how to create and ajax module i can call from any php script to do its bidding. however the tutorial simply had the ordinary file paths of "index.php" or "signup.php", but i went ahead and out of my own personal preference, i used $_GET includes to display my pages via "index.php?page=signup"
the tutorial ajax module is:
function ajaxObj( meth, url ) {
var x = new XMLHttpRequest();
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
now when i use a form to call this function to send data to php, it just sends me back to index.php without the dynamic url in place. im not sure what i need to place into the function call. the tutorial had:
var ajax = ajaxObj("POST", "signup.php");
I just dont know what to use besides "signup.php in the case of having the url being index.php?page=signup but nothing i've tried seems to work, and im starting to question if the error actually has anything to do with the ajax function.
Please assist a nooby noob in this dilemma.

How to prevent window.onload from repeating itself

I am trying to execute a js action that automatically sends informations to the URL for future use with php. To do so, I added a "onload" event on the window object and modified the URL in the listener. This is what it looks like so far:
window.addEventListener("load", function() {
window.location = "?test=test";
}, false);
When I load the page, the URL changes, but this is repeated over and over until the browser crashes. I was just wondering if there was a way to only execute it once.
If you don't want to use AJAX, and don't want to write JS functions to parse query strings, why not a simple:
<?php if(!isset($_GET['test'])): ?>
<script>
window.addEventListener("load", function() {
window.location = "?test=test";
}, false);
</script>
<?php else: ?>
<!--No JS written on the page, so no redirect -->
<?php endif;?>
But you really should look into AJAX, try using some JS framework like jQuery to help you in the process: http://api.jquery.com/jquery.ajax/
Check to see if you're already ON that page, before redirecting.
Add a simple flag on the URL like so: window.location = "?test=test&second=true";
As suggested in How can I get query string values in JavaScript?
Write a function to check get the URL params in JS GetQueryStringParams()
Then as suggested by others pass a send param in while reload
window.location = "?test=test&second=true";
Use the function in JS to check if you have a URL query string second and if its not there then reload the page
if you want to pass variables do this:
<?php
if(!isset($_GET['page'])){ //this line check if the variable field is available
$a = "Blank";
}else{
$a = $_GET['page'];
}
?>
that is it.
You could just erase the onLoad method once it's run, like so:
<script>
function doLoadStuff()
{
doSomeStuff();
//Clear onLoad contents
body.onLoad = function() {};
}
</script>
<body onLoad="doLoadStuff();">MyContent</body>

problem in refreshing the page after making two ajax calls

Problem I am making ajax call to server1 i.e. csce and once I got the response I am sending the response as contents to server2 i.e.yahoo server after getting response from there I want to refresh the page or atleast redirect it to the same page. Both ajax calls are working fine. The contents I am sending are also saved the only problem is that I have to manually refresh the page to see the changes. I want to refresh the page once the contents are saved on yahoo. I tried reload and redirect commands in success function of yahoo. But nothing works. I can see the both ajax calls in the HTTPfox but not the redirect.
The url from which i am making calls is different from the url where contents are saved thats why I need to refresh the page to see the changes. i.e. I am saving in yahoo/save while sending contents and seeing changes at yahoo/edit.
I am not sure where I am going wrong. Here is my code I am using. Can anyone suggest where I am going wrong. If my problem is not clear kindly do ask me to clarify more. Thanks.
This code is the code:
function handleButtonClick()
{
// Declare the variables we'll be using
var xmlHttp, handleRequestStateChange;
// Define the function to be called when our AJAX request's state changes:
handleRequestStateChange = function()
{
// Check to see if this state change was "request complete", and
// there was no server error (404 Not Found, 500 Server Error, etc)
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
var substring=xmlHttp.responseText;
alert(substring);// I am able to see the text which is returned by the server1 i.e csce
var handleSuccess = function(o)
{
if(o.responseText !== undefined)
{
console.log(o.responseText);
**window.location.reload()** // also I tried to redirect it to the same site but that also not works
}
};
var callback ={ success:handleSuccess, failure: function(x) {
console.error(x) }, argument: ['foo','bar']};
var request = YAHOO.util.Connect.asyncRequest('POST','http://yahoo.com******', callback, substring);
}
}
xmlHttp = new XMLHttpRequest();
xmlHttp.open("GET", "http://cse*****id=c6c684d9cc99476a7e7e853d77540ceb", true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
Do you just want to display the content in your page? Why don't you try something along the lines of document.getElementById('divID').innerHTML = xmlHttp.responseText;?
With divID being the id of a div that you want to fill the content with.
try following in the handleRequestStateChange function
window.location.href = window.location.href;

Categories