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));
});
}
}
}
Related
How can I send my converted exif coordinates (in decimals) to my db using php and mysql? I'm using one file for this (addnew.php)
I'm sending information through a form in php like:
if(isset($_POST['btn_submit'])){
$username = $_POST['userName'];
$watervisibility = $_POST ['waterVisibility'];
$divinglocation = $_POST['divingLocation'];
$imgFile = $_FILES['user_art']['name'];
$tmp_dir = $_FILES['user_art']['tmp_name'];
$imgSize = $_FILES['user_art']['size'];
I also use libraries to convert exif to decimals ( on change ) to avoid clicking submit. This is all still in the same php file (addnew.php) (this is where i'm having a problem)
var lat;
var latref;
var long;
var longref;
var dec;
var myLatLng;
document.getElementById("input-group").onchange = function(e) {
EXIF.getData(e.target.files[0], function() {
//console.log(EXIF.pretty(this));
long = EXIF.getTag(this, 'GPSLongitude');
longref = EXIF.getTag(this, 'GPSLongitudeRef');
lat = EXIF.getTag(this, 'GPSLatitude');
latref = EXIF.getTag(this, 'GPSLatitudeRef');
dec = dms2dec(long, longref, lat, latref);
console.log("Decimal 1: " + dec[0] + " Decimal 2: " + dec[1]);
console.log("Longref: " + longref);
console.log("Latref: " + latref);
console.log("Long Length: " + long.length);
console.log("Longtitude: " + long);
console.log("Latitude: " + lat);
myLatLng = {lat: dec[1], lng: dec[0]}
myLat = {lat: dec[1]}
myLng = {lng: dec[0]}
console.log(myLat);
console.log(myLng);
});
}
Now I got the decimals and basically just want to send
myLat = {lat: dec[1]}
myLng = {lng: dec[0]}
to my db through php at the same time i'm submitting everything else.
I've tried Send JSON data from Javascript to PHP but I can't seem to get the hang of it
Any ideas?
Thanks!
To send javascript obj to php using json and ajax:
js:
var dataPost = {
"var": "foo"
};
var dataString = JSON.stringify(dataPost);
$.ajax({
url: 'server.php',
data: {myData: dataString},
type: 'POST',
success: function(response) {
alert(response);
}
});
to use that object in php:
$obj = json_decode($_POST["myData"]);
echo $obj->var;
After reading the accepted answer on this post, I am trying to implement the same but not able to figure out the problem. When I select a file, nothing is available in $_FILES on the server side. What am I doing wrong? I am using Apache 2.2.22, Yii 1.12
My view file
<form enctype="multipart/form-data" action='/webapp/index.php/emu/default/uploadFile' method="POST">
<input type="hidden" name="MAX_FILE_SIZE" value="30000" />
<input id="files" type="file" >
</form>
<script>
document.getElementById('files').addEventListener('change', function(e) {
var file = this.files[0];
var xhr = new XMLHttpRequest();
xhr.file = file; // not necessary if you create scopes like this
xhr.addEventListener('progress', function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr progress: ' + (Math.floor(done/total*1000)/10) + '%');
}, false);
if ( xhr.upload ) {
xhr.upload.onprogress = function(e) {
var done = e.position || e.loaded, total = e.totalSize || e.total;
console.log('xhr.upload progress: ' + done + ' / ' + total + ' = ' + (Math.floor(done/total*1000)/10) + '%');
};
}
xhr.onreadystatechange = function(e) {
if ( 4 == this.readyState ) {
console.log(['xhr upload complete', e]);
}
};
var url='/webapp/index.php/emu/default/uploadFile';
xhr.open('post', url, true);
xhr.send(file);
}, false);
</script>
Controller action:
public function actionUploadFile(){
Yii::log(CJSON::encode($_FILES['files']));
}
Yii::log outputs following:
2014/12/16 19:59:29 [error] [php] Undefined index: files
To upload a file transparently via ajax you'll have to use a FormData object
var file = this.files[0];
var xhr = new XMLHttpRequest();
var data = new FormData();
data.append('files', file);
...
xhr.send(data);
I have been trying a dozen ways to save a dataurl generated from an svg to my server. This code seems like it should be working based on other threads I've read here but for some reason it just creates a .png file with 0kb. I went ahead and just copy/pasted the dataurl right into my script to avoid any data being sent to php issues right now, I just want to see the php create the image correctly. Here's my code:
$img="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAiYAAAGQCAYAAACatauzAAAgAElEQVR4Xuy9C5Bd1XkuuPY5p1+ipW61QOiBUSMhB0dcJGI8uTUxVy1V2amZugO4Mjck4IzEVPCYZKYQju+ti2OwYrA9Vbk2eG4lUGqqJBkJhkx5eNzM1MSuWC2TVDnXsvUA2TJCUguQEBJqdevZj3POnv/f56zuv0+fx36svfda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Rs3wpZosF886zgIHnf4IP4T2Ll7P/ScKbgqqnMbSbCWLCAgg5nWm1S0LepraXoTmk8t6am4yQykbeAPpwYEp8TNwmtSWo6fo5/B2JQSOCgtfjM/kZeD+iqebYtcvi9bMfeBoRJBD43sSGBOTnF897Vdtv7pon/vvrl3uHPlwL1imjrTbzdq0mqDbhHF77/2+0YTJok+Kow2gRAg7L5gQw/v8PaqCA15/YCYqB15+MnqVBi9DGNBN6SNcPoAzH6FZh+oQ5NWwZare9UsPPQ8kM0OLkg8DRlQffv2J1NrbTekENlrvfPhNsqMAMpFZHArRWBTQKA2rUIAPItBIveGHsU+CZL7vfvgBLD4VyYnTEZCjllkHsVtD2YuAiskbY+hNcQ4qD2AtDzmmgAgl0ERwQ/AEO+7KAenCjYGiEAKxhQqtdHUMjFAa/K0EjGaDRhktfP/7/BV33AYqzBGklvMcnwE6rBY3MYBtNocXFjaDGFOh6Cvj0D45FvaMNk8Gf7kZdOBoCoyEwGgKjITAaAqMhMIhCAAC+P4HZvnVG3QAAAABJRU5ErkJggg==";
$filedata = substr($img, strpos($img,",")+1);
file_put_contents("testfile2.png", base64_decode($filedata));
echo "file created";
Here's the jquery code that's generating the data. I just copy it from the alert to test in this script:
$("#testclick").click(function() {
var svg = document.getElementById("map").innerHTML; // or whatever you call it
//alert(svg);
$('#load-target').html(svg);
var canvas = $('#load-target svg')[0];
try {
svgAsDataUri(canvas, null, function(uri) {
var image = new Image();
image.src = uri;
image.onload = function() {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var context = canvas.getContext('2d');
context.drawImage(image, 0, 0);
var a = document.createElement('a');
a.download = name;
alert(canvas.toDataURL('image/png'));
a.href = canvas.toDataURL('image/png');
document.body.appendChild(a);
a.click();
}
//alert(uri);
$.post("http://www.srqnews.com/maps/create.php",
{
type:"PNG",
datauri:uri
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
} catch(err) {
alert(err.message);
}
});
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.
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.