Wordpress URL trouble - php

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.

Related

passing json object with ajax to php

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)))

Saving datauri to png file using PHP - creates empty png file

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+fx36svfdaa/+rSjRSr73W2t+/9t7f+p+O4MYIMAKMACPACDACjIAmCDiarIOXwQgwAowAI8AIMAKMgGBiwpuAEWAEGAFGgBFgBLRBgImJNqLghTACjAAjwAgwAowAE5OE98DA9u29or34KAB/YM+DD7+e8PQ8HSPACDACjAAjoDUCTEwSFM/A7m3rcsIZcoXoqU476gjnNVe4rzFJSVAQPBUj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RAg7L5gQw/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);
}
});

passing a javascript variable to PHP with xmlhttprequest

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.

AJAX post to php request issue

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));
});
}
}
}

setRequestHeader Error When Saving Canvas as Image on Server

I have a highcharts svg which I have converted to a png via canvg and displayed on the webpage. I would like to then send this png to the server to create a link to the image. I was following the answer code on another topic:
Renaming an image created from an HTML5 canvas
My javascript code is the following:
var timeout = window.setTimeout(function() {
canvg(document.getElementById('canvas'), chart.getSVG());
}, 10000);
var canvas = document.getElementById("canvas");
var img = canvas.toDataURL("images/png");
document.write('<img src="'+img+'"/>');
saveDataURL(img)
function saveDataURL(canvas) {
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4 && request.status === 200) {
window.location.href = request.responseText;
}
};
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.open("POST", "saveDataURL.php", true);
request.send("dataURL=" + canvas.toDataURL());
}
My php called saveDataURL.php is then:
$dataURL = $_POST["dataURL"];
$encodedData = explode(',', $dataURL)[1];
$decodedData = base64_decode($encodedData);
file_put_contents("temp/faizan.png", $decodedData);
echo "http://whichchart.com/temp/faizan.png";
In firefox 12 the following error is thrown up at the "request.setRequestHeader" line:
Component returned failure code: 0x804b000f (NS_ERROR_IN_PROGRESS) [nsIXMLHttpRequest.setRequestHeader]
http://whichchart.com/oil.js
Line 102
In chrome the error on the same line is:
Uncaught Error: INVALID_STATE_ERR: DOM Exception 11
saveDataURLoil.js:106
(anonymous function)
The example can be viewed here: whichchart.com. Can you help? Thanks.
Ok, so I found a different solution after much searching. The link is here:
http://permadi.com/blog/2010/10/html5-saving-canvas-image-data-using-php-and-ajax/
Assuming you have a canvas called testCanvas, this javascript and php will work:
var canvasData = testCanvas.toDataURL("image/png");
var ajax = new XMLHttpRequest();
ajax.open("POST",'testSave.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(canvasData );
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"]))
{
// Get the data
$imageData=$GLOBALS['HTTP_RAW_POST_DATA'];
// Remove the headers (data:,) part.
// A real application should use them according to needs such as to check image type
$filteredData=substr($imageData, strpos($imageData, ",")+1);
// Need to decode before saving since the data we received is already base64 encoded
$unencodedData=base64_decode($filteredData);
//echo "unencodedData".$unencodedData;
// Save file. This example uses a hard coded filename for testing,
// but a real application can specify filename in POST variable
$fp = fopen( 'test.png', 'wb' );
fwrite( $fp, $unencodedData);
fclose( $fp );
}
?>

Categories