Im having problem Posting a javascript variable to a php file. Please would someone tell me what's going on?
// Get Cookies
var getCookies = document.cookie;
cookiearray = getCookies.split(';');
SelectedIds = cookiearray[0];
//take key value pair
name = cookiearray[0].split('=')[0];
value = cookiearray[0].split('=')[1]; // The variable(values) i want to pass
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
hr.open("POST", url, true);
var url = "page.php";
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("Comp").innerHTML = return_data;
}
}
hr.send(value); // Request - Send this variable to PHP
document.getElementById("Comp").innerHTML = "loading...";
PHP
$test = $_POST['value'];
print_r($test); // NULL
Thanks
Instead of
print_r($test);
use the echo
echo $test;
As $test is not an array is a string value. print_r is used to print the array. that's why is given the null value.
And your send function in ajax should be like this:
hr.send("value="+value);
In the send function, the parameter that passed must be a string like this:
"name=value&anothername="+encodeURIComponent(myVar)+"&so=on"
More tutorial is here.
I've been trying work out, for sometime, how to pass quite a long string I have formatted in javascript into php to save in a file and I think I now have the answer. At least it works for me.
The variable 'str' is passed into 'getGame' from another function after it has been formatted. I am using the 'POST' method as the string can get quite long.
The code is:-
function getGame(str){
//Sends data to the php process "save Game".
var test = str;
var xhr = new XMLHttpRequest();
xhr.open("POST", "saveGame.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (this.readyState === 4 ){
alert(xhr.responseText);
}
};
xhr.send("data="+ test);
}
This sends the "data" to "saveGame.php where it is saved to a file as in the following code and returns a messsage in the alert dropdown.
<?php
$outputString = $_POST["data"];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
fwrite($fp, $outputString);
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
This works for me and I hope it is useful to other newbies.
Related
I have set up a basic api and I know its working because requests that come with postman pass normally ,what I am having trouble with is passing the JSON object through AJAX to the php file.
The AJAX part
function add_book(){
if(validate()){
var jsonData = {};
jsonData.Price = document.getElementsByName("Price")[0].value;
jsonData.Title = document.getElementsByName("Title")[0].value;
jsonData.Author = document.getElementsByName("Author")[0].value;
jsonData.Genre = document.getElementsByName("select_dropdown")[0].value;
alert(JSON.stringify(jsonData));
var request = new XMLHttpRequest();
var url = "/books.php";
request.open("POST", url, true);
request.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
}
}
request.send(jsonData);
}
}
For example this is the alert I get from stringifying the object
{"Price":"23","Title":"asdas","Author":"dasda","Genre":"Science fiction"}I can basically copy/paste this string to postman and it works as intended.
Now to the php part
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if(!empty($json_obj->Price) && !empty($json_obj->Genre) && !empty($json_obj->Author) && !empty($json_obj->Title)){
The if always returns false ,while it should not ,again postman requests pass for true.
========================================================================
EDIT :
I managed to find the source of the problem . I made a function to check if the json is valid , turns out its not , there is no problem in the php part as it turns out . Here is the function in case someone needs it / wonders :
function isValidJSON($str) {
json_decode($str);
return json_last_error() == JSON_ERROR_NONE;
}
=========================================================================Edit 2:
The problem was on the request.send(jsonData); part . Fixed it with request.send(JSON.stringify(jsonData));
Thanks for your time !
This is the problem
$json str = file_get_contents('php://input');
The post parameters should be accessed by $_POST.
Instead try this
$json_str = $_REQUEST['jsonData']`;
and also do a var_dump for $json_str
Does this help?
$json_str = file_get_contents('php://input');
$json_obj = json_decode($json_str);
if(!empty($json_obj['Price']) && !empty($json_obj['Genre']) && !empty($json_obj['Author']) && !empty($json_obj['Title'])){
I think the problem is the file_get_contents(). Maybe you try to echo it.
And for the if you could write:
if (!(empty($json_obj->Price) && empty($json_obj->Genre) && empty($json_obj->Author) && empty($json_obj->Title)))
I am using ajax to send data with JSON and it keeps returning null. Here is the string I'm sending:
{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}
It is sent via post. Here is the code I send it with:
function slash(strr){
var re = /([^a-zA-Z0-9])/g;
var str = strr;
var subst = '\$1';
var st = encodeURIComponent(str.replace(re,subst));
console.log("st");
return st;
}
function create() {
var info = {};
var code=editor.getValue();
info.username=username;
info.code=slash(code);
var name=document.getElementById('projectName').value;
name2=name;
info.name=slash(name2);
info=JSON.stringify(info);
console.log(info);
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("POST", "create_project.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("info="+info);
}
When it gets received in the php file it is processed like this:
$info = $_POST['info'];
echo "<pre>".$info."</pre>";
//$info = urldecode($info);
$info = json_decode($info);
echo "<pre>".$info."</pre>";
However for some reason the json_decode() doest work. Again here is the JSON I'm sending:
{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}
the first echo works correctly but the second one doesn't. How do I fix this?
json_decode() must be emitting an error which you are not checking. Functions like json_decode() and json_encode() do not display errors, you must use json_last_error and since PHP 5.5 there is also json_last_error_msg().
<?php
$str = '{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B\'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}';
var_dump($str);
var_dump(json_decode($str));
var_dump(json_last_error());
var_dump(json_last_error_msg());
The above outputs:
string(189) "{"username":"HittmanA","code":"%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B\'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F","name":"Untitled-1"}"
class stdClass#1 (3) {
public $username =>
string(8) "HittmanA"
public $code =>
string(136) "%601234567890-%3D~!%40%23%24%25%5E%26*()_%2Bqwertyuiop%5B%5D%5CQWERTYUIOP%7B%7D%7Casdfghjkl%3B\'ASDFGHJKL%22zxcvbnm%2C%2FZXCVBNM%3C%3E%3F"
public $name =>
string(10) "Untitled-1"
}
int(0)
string(8) "No error"
If we try to decode invalid JSON:
<?php
$str = 'foobar{';
var_dump($str);
var_dump(json_decode($str));
var_dump(json_last_error());
var_dump(json_last_error_msg());
The above prints:
string(7) "foobar{"
NULL
int(4)
string(16) "boolean expected"
There must be an error in the JSON when you try to decode it. Check for errors usings the json_* error message functions. The error message will tell you what's wrong and it will be straight to fix once you know what the error is.
hello mister if you echo in php is equal to return or print in some functional programming.
if your using ajax, ajax is one way communication.
$info = $_POST['info'];
//this code will be return
echo "<pre>".$info."</pre>";
//this also will not be triggered cause you already return the above code
//$info = urldecode($info);
$info = json_decode($info);
echo "<pre>".$info."</pre>";
Perhaps setting the xhttp content-type as json like
<?PHP
$data = /** whatever you're serializing **/;
header('Content-Type: application/json');
echo json_encode($data); ?>
As stated in this answer.
Looking at the object it looks like you have a ' inside your code parameter. I think that's invalid for encoding.
Using json_decode like this:
$info = json_decode($info);
Will return a PHP variable.
If you add the associative parameter as true (false by default) like this:
$info = json_decode($info, true);
Then it will return an associative array
http://php.net/manual/en/function.json-decode.php
I was struggling with this on my Windows 10 machine, PHP version 5.5.9 only to find that the php_json.dll file was not in the ext folder of my installation and obviously no extension to uncomment in php.ini file. I found the dll at http://originaldll.com/file/php_json.dll/31989.html. After copying it to my ext folder I added extension=php_json.dll to my php.ini file and restarted my apache server and it started working fine.
i am working on wordpress site , i would like to send a variable to a php file , and get it back , the php file(new.php) its an external file , i have put it on the directory , when im on my localhost , it works well , but does not when uploded to my domain and i can not access the file , this my code :
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url ="http://belcodes.com/new.php";
alert(url);
var fn = tit;
var ln = "";
var vars = "firstname="+fn+"&lastname="+ln;
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...";
//here the code of new.php:
<?php
echo'without any post';
if(isset ( $_POST['firstname'] ) ){
echo'with post ';
}
?>
Thanks in advance.
Hi I'm wanting to post a variable from ajax js file to a php file. here is my attempt so far.
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
here is my php file
<?php
print_r($_POST);
$node = $_POST['deletenode'];
print "node to be deleted: $node";
?>
nothing comes up in my php file, what can be the issue. my ajax request is intact and working right too. thank you and here is my handle request.
function handleRequest(request) {
// we only care for now about when we get to readyState 4
// which means the request completed and we have the response back
if(request.readyState == 4){
//alert("response: " + request.responseText); // check to see what
// we got back just for testing
// now get response's TEXT and put into document (specify where)
// below we have an html element with the id as timeLoc
json= eval ("(" + request.responseText + ")");;
//alert ("json="+json); //tests what was recieved
//clicking the close button
closeButton.onclick = function() {
node.setData('alpha', 0, 'end');
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0, 'end');
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
});
}// end readystate=4
}//end handle request
Remember you have to send the data as key/value pairs - request.send("deletenode=" + encodeURIComponent(deletenode));
I'm not sure if this is a copy/paste error, but if that's your actual code you appear to be missing a few curly braces closes. And have a double;; at the end of your eval line. This is the code tidied up with the extra curly braces, does that work?
function handleRequest(request) {
if(request.readyState == 4){
json= eval ("(" + request.responseText + ")");
closeButton.onclick = function() {
node.setData('alpha', 0, 'end');
node.eachAdjacency(function(adj) {
adj.setData('alpha', 0, 'end');
var request = createRequest();
var deletenode = node.id;
window.alert("nodeid=" + deletenode);
var vars = "deletenode="+deletenode;
request.open("POST", "deletenode.php", true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.onreadystatechange = function() {
handleRequest(request);
};
request.send("deletenode=" + encodeURIComponent(deletenode));
});
}
}
}
This is my url
http://localhost:8888/App.php#?ID=1S
I needed the 1S as a variable for using it with a query.
If you want to parse URL as string:
$str = 'http://localhost:8888/App.php#?ID=1S';
$temp = explode( "?", $str );
$result = explode( "=", $temp['1'] );
echo $result['1'];
Demo
If you want to get it on server side:
Hash value is not sent to server side. So it impossible to get it on server side but you can use javascript to do some trick.
Can I read the hash portion of the URL on my server-side application (PHP, Ruby, Python, etc.)?
Using JavaScript/jQuery: (tags are not added though)
<script>
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('#') + 1).split('&');
hash = hashes[0].split('=');
alert( hash['1'] );
// you can use jQuery.ajax() here to send this value to server side.
</script>
Get hash value & pass from javascript to php
echo parse_url('http://localhost:8888/App.php#?ID=1S', PHP_URL_FRAGMENT);
OR
echo parse_url($_SERVER['QUERY_STRING'], PHP_URL_FRAGMENT);
If you need to parse it further:
$x = parse_url($_SERVER['QUERY_STRING'], PHP_URL_FRAGMENT);
parse_str($x, $arr);
echo $arr['ID']
$url = "http://localhost:8888/App.php#?ID=1S&another=3";
$a = parse_url($url);
parse_str($a["fragment"],$arr);
print_r($arr);
outputs:
Array (
[?ID] => 1S
[another] => 3
);
if you can live accessing the first parameter with "?ID"
I guess that the only way to do this is by an AJAX request, here is a simplified example:
the index page
<!doctype html>
<html>
<head>
<title>Website</title>
<script type="text/javascript">
var url = document.location;
url = url.toString();
var getVal = url.split("#");
var xmlhttp = new XMLHttpRequest();
xmlhttp.open('GET', 'App.php'+getVal[1], true);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.send();
</script>
</head>
<body>
</body>
</html>
the App.php page
<?php
if (isset($_GET['url'])) echo 'url : ' . $_GET['url'];
?>