Hi guys I'm trying to delete a file with Ajax and I have this code:
functions.js:
function deleter(val){
var value = val.replace(".",",");
var del = new XMLHttpRequest();
del.addEventListener("load", completedelete, false);
del.open("POST","index.php?action=delete",true);
del.send("file="+value);
}
index.php:
if(isset($_REQUEST['action'])&& $_REQUEST['action']=="delete"){
if(!isset($_POST['file'])){
echo("not set");
}
if(unlink($_POST['file'])){
echo"1";
}else{
echo"0";
}
}
and I always get "not set" in the response with the 0 .
any one can help me?
Try to add
del.setRequestHeader("Content-type","application/x-www-form-urlencoded");
before del.send().
Related
I am able to run this successfully. I would love to accomplish the same thing with out the use of php. Main goal is to change the value of sel from the json file. Below is my php code and json code. the user.php changes the vaule of sel from the json file when a button is hit.
<?php
$jsonString = file_get_contents('sel.json'); //read contents from json file
$jsondata = json_decode($jsonString, true); //convert string into json array using this function
if(isset($_POST['button1'])) //if button is pressed?
{
$jsondata[0]['sel'] = 1; //initialise data to 1
}
if(isset($_POST['button2'])) //if button is pressed?
{
$jsondata[0]['sel'] = 2; //initialise data to 2
}
if(isset($_POST['button4'])) //if button is pressed?
{
$jsondata[0]['sel'] = 4; //initialise data to 4
}
if(isset($_POST['button6'])) //if button is pressed?
{
$jsondata[0]['sel'] = 6; //initialise data to 6
}
$newJsonString = json_encode($jsondata); //encode data back
file_put_contents('sel.json', $newJsonString); //write into file
?>
<!DOCTYPE html>
<html>
<body>
<p>json testing</p>
<form action="<?php $_SERVER['PHP_SELF'] ?>" method="POST">
<button name="button1" onclick="placeorder()"> sel1:place order</button>
<button name="button2" onclick="cancleorder()">sel2:cancle order</button>
<button name="button4" onclick="unlockenotdone()">sel4:unlock UV box(notdone)</button>
<button name="button6" onclick="unlockedone()">sel6:unlock UV box(done)</button>
</form>
<p id="ui"></p>
<script>
var x = document.getElementById("ui");
function placeorder() {
console.log(1);
x.innerHTML = "Your Order has been Placed";
clear();
}
function cancleorder(){
var usrResponse=confirm('are you sure you want to cancle the order?');
if(usrResponse==true){
cancleconfirm();//call function ChangState2()
}
}
function cancleconfirm() {
console.log(2);
x.innerHTML = "Your Order has been canceled";
clear();//call function clear()
}
function unlockenotdone(){
var usrResponse=confirm('The sterilization is not done. Do you still want to unlock the book?');
if(usrResponse==true){
console.log(4);
openconfirm();
}
}
function unlockedone()
{
console.log(6);
openconfirm();
}
function openconfirm() {
x.innerHTML = "The UV book is now unlocked";
clear();//call function clear()
}
function clear()
{
setTimeout( function(){x.innerHTML="";}, 5000);
return false;
}
</script>
</body>
</html>
this is the sel.json [{"sel":1}]
Simply javascript can never do this, you must have to use of javaScript as well as php for this scenario..
You need to use XHR
step 1 -> handle file saving process as backend using php code.
step 2 -> make a method for button to hit a xhr code to excecute set1 file code
here we go
step 1
creating file with name savingJson.php
/* This is savingJson.php file */
/* here file saving code to handle */
$data = file_get_contents('php://input');
// define path for file
$file = $_SERVER['DOCUMENT_ROOT'] . '/sel.json';
// Write the contents back to the file
file_put_contents($file, $data);
step 2
calling XHR method on button click to run savingJson.php using javaScript
var jsonData = '[{"sel":1}]'
// calling method on button click
var button = document.getElementbyId("btn_id")
button.onclick = function(){
saveJsonToFile(jsonData)
}
function saveJsonToFile(jsonData) {
var xhr = new XMLHttpRequest();
var url = 'savingJson.php' /*path to savingJson.php file*/
xhr.open("POST", url, true); /* must be use POST for large data*/
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.send(jsonData);
}
Hope so this will help you,
Happy Coding!
I am trying to send a javascript variable (placeid) to PHP using AJAX. I use this variable to retrieve a JSON Object. The JSON returned to Javascript is NULL. How do I fix this?
function sendToPhp(placeid){
var url = "finals.php?placeid="+placeid;
var getJSONObj=function(url,callback){
var httpc = new XMLHttpRequest();
httpc.open("GET", url, true);
httpc.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
httpc.responseType='json';
httpc.onload= function(){
var status=httpc.status;
if(status==200){
//alert(httpc.response);
callback(null,httpc.response);
}
else{
callback(status,httpc.response);
}
};
httpc.send();
};
getJSONObj(url,function(err,jsonObjectReturned){
if(err!==null){
alert("something went wrong"+ err);
}
else
{
alert("success");
alert(jsonObjectReturned); // **returns NULL**
}
});
} // end of function
The PHP script uses the placeid to return a JSON file as shown:
if(isset($_GET['placeid']))
{
$placeid= $_GET['placeid'];
$apikey="someKeyValue";
$url="https://maps.googleapis.com/maps/api/place/details/json?placeid=".$placeid."&key=".$apikey;
$jsonPlacesObject=json_decode(htmlspecialchars(#file_get_contents($url),true),true);
echo json_encode($jsonPlacesObject); //sending json to javascript**
die();
}
Your AJAX form looks wrong. Try reading https://www.w3schools.com/js/js_json_php.asp .
Original.
Working example below, hopefully this will help others learn!
I'm using AJAX in javascript to send a JSON string to PHP.
I'm not familiar with AJAX, javascript or php, so this is taking me a while to get started.
I have a html file with a username field, password field, and login button.
Then I have a javascript file that takes the username pass and sends it to a php file.
I know the php file is being accessed because I am seeing the test echo in console.
I just cant figure out how to access the data I'm sending to the php.
script.
function attemptLogin(){
var inputUserName = JSON.stringify(document.getElementById("userName").value);
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', 'ajax.php', true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send(inputUserName);
}
ajax.php
<?php
echo"TestInPHP";
?>
For now all I want to do is echo the username back to console, I'm sure the syntax is something simple, I just cant figure out what it is.
Here is an edit for the working code thanks to SuperKevin in the
comments below. This code will take the string in the username and
password fields in HTML by the JS, send it to PHP and then sent back
to the JS to output to the browser console window.
index.html
<input type="text" name="userID" id="userName" placeholder="UserID">
<input type="password" name="password" id = passW placeholder="Password">
<button type="button" id = "button" onclick="attemptLogin()">Click to Login</button>
script.js
function attemptLogin(){
var inputUserName =
JSON.stringify(document.getElementById("userName").value);
// console.log(inputUserName);
var inputPassword = JSON.stringify(document.getElementById("passW").value);
var cURL = 'ajax.php?fname='+inputUserName+'&pass='+inputPassword;
var ajaxData = new XMLHttpRequest();
ajaxData.open('GET', cURL, true);
ajaxData.onreadystatechange = function(){
var DONE = 4;
var OK = 200;
if (ajaxData.readyState === DONE) {
if (ajaxData.status === OK) {
console.log(ajaxData.responseText);
}else{
console.log("ERROR : " + ajaxData.status);
}
}
};
ajaxData.send();
}
ajax.php
<?php
echo $_GET['fname'];
echo $_GET['pass'];
?>
Here's a simple example of how you would make a vanilla call.
This is our main file, call it index.php.
<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "delete.php", true);
xhttp.send();
</script>
Here's our server script. delete.php
<?php
echo "HELLO THERE";
Now, if you wanted to pass data to your script you can do the following:
xhttp.open("GET", "delete.php?fname=Henry&lname=Ford", true);
xhttp.send();
To access this data you can use the global $_GET array in php. Which would look like this:
$fname = $_GET['fname'];
$lname = $_GET['lname'];
Obviously, you have to sanitize the data, but that's the gist of it.
For a much more in depth tutorial visit W3Schools Tutorial PHP - AJAX.
You can see all the data sent to your php with :
<?php
print_r($_GET); //if it's send via the method GET
print_r($_POST); //if it's send via the method POST
?>
So, in your case it will be something like :
<?php
echo $_GET['username'];
?>
If you're not using jQuery then don't pay attention to my answer and stick to the pure javascript answers.
With jQuery you can do something like this:
First Page:
$.ajax({
url: 'sportsComparison.php',
type: 'post',
dataType: 'html',
data: {
BaseballNumber = 42,
SoccerNumber = 10
},
success: function(data) {
console.log(data);
});
which will send the value 42 and 10 to sportsComparison.php with variable names BaseballNumber and SoccerNumber. On the PHP page they can then be retrieved using POST (or GET if that's how they were sent originally), some calculations performed, and then sent back.
sportsComparison.php:
<?php
$BaseballValue = $_POST["BaseballNumber"];
$SoccerValue = $_POST["SoccerNumber"];
$TotalValue = $BaseballValue * $SoccerValue;
print "<span class='TotalValue'>".$TotalValue."</span>";
?>
This will return a span tag with the class of TotalValue and the value of 420 and print it in the console.
Just a simple way to do ajax using jQuery. Don't forget commas in the parameter list.
So i have written a function that is called onclick in my html file that uses AJAX, but i would like for this post to go to a specific table in mysql.
$('#submitIFC').click(function(e) {
var request;
if (window.XMLHttpRequest) {
request = new XMLHttpRequest();
} else {
request = new ActiveXObject("Microsoft.XMLHTTP");
}
var opinionIFC = $('ul.sort').sortable('toArray').join(',');
request.onreadystatechange = function() {
if ((request.readyState===4) &&(request.status===200)) {
var return_data = request.responseText;
document.getElementById('rank_ul').innerHTML= 'return_data';
// Preventing the default action triggered by clicking on the link
e.preventDefault();
e.preventDefault();
}//end of if
}//end of onreadystatechange function
//send requested movie to php file which will send to the external server
request.open("POST", "results.php", true);
request.send(opinionIFC);
document.getElementById('rank_ul').innerHTML='<img src="ajax-loader.gif">';
});
however there seems to be an issue with connecting this to my php if conditional, i tried copying the contents on my request.send(), like so
if($_POST['opinionIFC'])
{echo
// The data arrives as a comma-separated string,
// so we extract each post ids:
$data=explode(',',str_replace('li','',$_POST['sortdata']));
// Getting the number of objects
list($tot_objects) = mysql_fetch_array(mysql_query("SELECT COUNT(*) FROM sort_objects"));
if(count($data)!=$tot_objects) die("Wrong data!");
foreach($data as $k=>$v)
{
// Building the sql query:
$str[]='('.(int)$v.','.($tot_objects-$k).')';
}
$str = 'VALUES'.join(',',$str);
// This will limit voting to once a day per IP:
mysql_query(" INSERT INTO `sort_votes` (ip,date_submit,dt_submit)
VALUES ('".$_SERVER['REMOTE_ADDR']."',NOW(),NOW())");
// If the user has not voted before today:
if(mysql_affected_rows($link)==1)
{
mysql_query(' INSERT INTO `sort_objects` (id,votes) '.$str.'
ON DUPLICATE KEY UPDATE votes = votes+VALUES(votes)');
}
}
why isnt the ajax post request filtering through to my php file?
thank you so much, any help is much appreciated.
You're not sending opinionIFC parameter, try:
request.send('opinionIFC=' + opinionIFC);
You also need to set Content-type
request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
I am trying to make a ajax call and validate a input html field. But, instead of getting simple echo message. I am getting complete source code in responseText.
JavaScript
function checkUsername() {
document.getElementById("username").className = "thinking";
usernameRequest = createRequest();
if (usernameRequest == null)
alert("Unable to create request");
else {
var theName = document.getElementById("username").value;
var username = escape(theName);
var url= "checkName.php?username=" + username;
usernameRequest.onreadystatechange = showUsernameStatus;
usernameRequest.open("GET", url, true);
usernameRequest.send(null);
}
}
function showUsernameStatus() {
alert(usernameRequest.responseText);
if (usernameRequest.readyState == 4)
{
if (usernameRequest.status == 200) {
if (usernameRequest.responseText == "okay") {
document.getElementById("username").className = "approved";
document.getElementById("register").disabled = false;
}
else {
document.getElementById("username").className = "denied";
document.getElementById("username").focus();
document.getElementById("username").select();
document.getElementById("register").disabled = true;
}
}
}
}
checkName.php
<?php
$takenUsernames = array('bill', 'ted');
sleep(2);
if (!in_array($_REQUEST['username'],$takenUsernames )) {
echo 'okay';
} else {
echo 'denied';
?>
Previously, I tried to integrate PHP into tomcat, but I was advice it was not a good practice. TRIAL TO INTEGRATE PHP
What I can make out of this situation is that Tomcat is not parsing PHP file and instead it is returning the source code. I believe there should be a means for me to let tomcat parse php files and send the right response.
I have also tried with simple php code, with one statment <?php echo 'HELLO'; ?> and I still get the source code.
Thanks in advance.
NOTE : I do not know php, I am working an example from HEAD FIRST AJAX
you need to install PHP for Tomcat & set its path to compile it.see the below link for php configuration settings.
http://php-java-bridge.sourceforge.net/doc/tomcat6.php
http://www.studytrails.com/blog/php-on-a-java-app-server-apache-tomcat-using-quercus/