I have this code.
JAVASCRIPT
function removeAndReplace(id, sezione){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
alert(xhttp.responseText);
}
}
xhttp.open("POST", "removeAndReplace.php", true);
xhttp.send("id=" + id + "&sezione=" + sezione);
}
PHP
print_r($_POST);
$id = $_POST['id'];
$sezione = $_POST['sezione'];
.
.
.
HTML
<input type="button" value="Elimina" class="btn_elimina" onClick="removeAndReplace(1, 'Shopping')">
I want to call a PHP function after the button click so I read that the better way is to use AJAX.
Firefox and Chrome return this error message:
Array
(
)
Notice: Undefined index: id in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 6
Notice: Undefined index: sezione in C:\pweb\tools\xampp\htdocs\Bazaar\php\removeAndReplace.php on line 7
Line 6 is: $id = $_POST['id'];
Line 7 is: $sezione = $_POST['sezione'];
Where am I going wrong?
You are dumping your data into the request body without telling the server how it is formatted.
Since PHP doesn't know you have sent it data in an encoding it understands, it ignores the request body.
You need to add:
xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
… before you send the request.
Aside
While your hard coded data is free of special characters, it is best practice to encode your data. This will save you headaches in the future:
xhttp.send("id=" + encodeURIComponent(id) + "&sezione=" + encodeURIComponent(sezione));
You can save yourself the trouble of manually encoding the data and having to set your own content-type by using the FormData API:
var data = new FormData();
data.append("id", id);
data.append("sezione", sezione);
xhttp.open("POST", "removeAndReplace.php", true);
xhttp.send(data);
Related
I'm trying to pass a long formatted text string to a php process to save to a file. I am use the POST method as the string can be quite long. It seems to run thro the process and gives back the message 'File saved' but with the error message 'Undefined Array Key "data"' on line 2 of the php code. The file does not get saved and no data is being sent across from the XMLHttpRequest in the previous function.
My code is:- This gets 'str' from the previous function and is formatted correctly.
function getGame(str){
//Sends data to the php process "saveGame.php".
var data = 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);
}
it then goes the the 'saveGame.php' where the problem occurs on line 2.
<?php
$outputString = $_POST["data"];
$DOCUMENT_ROOT = $_SERVER['DOCUMENT_ROOT'];
$fp = fopen("C:\\xampp\\htdocs\\BowlsClub\\GamesSaved\\test26.txt","w");
fwrite($fp, $outputString);
if (!$fp){
$message = "Error writing to file. Try again later!" ;
}else{
$message = "File saved!";
}
fclose($fp);
echo $message;
?>
I think my code of the process is okay but there is a problem with passing the "data" variable and I not sure what it is.
I tested the file saving process. I put a dummy string as a value of 'outputString' and it saved it. When I went back and used the current code the file was overwritten and was blank, indicating it had saved a blank string. So it seems no data is been passed to saveTeams.php although the saving of the file works.
I have got a reproducible example below. If you use it with the saveTeams.php file and a file to attempt to save the data to it should display the error I get in an alert drop down.
<!DOCTYPE html>
<head>
<title>Test program</title>
<script language="javascript">
function formatOutput() {
// lots of formatting goes on here
var formattedText = "This is a test"; //test data
getGame(formattedText);
}
function getGame(str){
//Sends data to the php process "save Game".
var data = 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);
}
</script>
</head>
<body>
<table width="1000" align="center" border="0">
<br />
<tr>
<td width="500"align="center" colspan="3" <button onclick="formatOutput()"/>Click on me</td>
</tr>
</table>
</body>
</html>
Hope this okay. I'm a bit new to this.
You are missing a post key
try changing this line to
var data = 'data='+str;
I'm recently working on a website project. Therefor I have a website.php with all html code, a function.php and saveArray.js . In website.php I'm printing a html table with a button at the bottom. Through the button click I'm getting to the saveArray.js, where I save all the table data in an array.
With this code
var arrString = JSON.stringify(tableData);
var request = new XMLHttpRequest();
request.open('post', 'function.php', true);
request.setRequestHeader('Content-Type', 'application/x-www-form-
urlencoded');
request.send('daten=' + arrString);
I post the JS array to function.php. In function.php I do something with the array and in an if statement I want to show a modal.
The modal itself works, but I want to show it on website.php page. Which doesn't happends, because I'm currently on function.php .
How can I solve this ?
EDIT: In my array is an ID and I want to check if this ID is already in my database or not. Depending on this result I want to show the modal and upload the data if necessary. All the checking is happening in function.php
I suppose you want to inject the string returned (the modal PHP code) by your function in function.php in your current page ('website.php').
To do this, you'll have to inject the response given by the XMLHttpRequest when the request is finished.
Let's suppose we want to add all the contents within
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
See, You are not handling the response of the request.So handle the response.and restuern the status of the request from function.php and if data is saved the open the model. You need not go to the function.php page. See the code
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// this is response of the request //now check it
//Suppose you returned " data saved" as response from function.php
if(this.responseText='data saved'){
//Open model here
}
}
};
xhttp.open("POST", "function.php", true);
xhttp.send();
I have been trying to insert data into a table in a mysql database. This data was sent with ajax using the POST method. However, when I try to insert it into the database nothing happens.
So here is the javascript function the sends the data to the php file.
addToCart: function(itemId,userId){
let request = new XMLHttpRequest();
request.open("POST", "../E-CommerceCore/addToCart.php?
itemId="+ itemId + "?userId=" + userId, true);
request.send();
},
Here is where it is being used. This is nested in a bigger function so thats where the book[i].Id comes from.
document.getElementById('add-to-cart').onclick = function(){
cartFunctions.addToCart(book[i].Id, '1');
};
So this takes an item id and a user id and stores them in a php variables here.
class Cart
{
public function addToCart($item,$user){
include 'connect.php';
$query = $bookStore->prepare("INSERT INTO cart SET item_Id=?, user_Id=?");
$query->execute([$item,$user]);
}
}
$cartManager = Cart();
$itemId = $_REQUEST["itemId"];
$userId = $_REQUEST["userId"];
$cartManager->addToCart("$itemId","$userId");
This php file then runs the addToCart function which should insert it into the table. This is where I run into the problem because not data is inserted to the database when the user clicks the button. I use the connect.php file for another controller that selects from a different table in the same database, if that is an issue, and yes I have checked to make sure that the connection to the database is good. Any insight would be immensely appreciated. Please no jQuery solutions. Thank you for you time and effort.
request.open("POST", "../E-CommerceCore/addToCart.php? itemId="+ itemId + "?userId=" + userId, true); You are sending the parameters as GET with the url and you have another mistake since you used another ? to separate the 2 parameters . Please follow this link to send your data: Send POST data using XMLHttpRequest
var http = new XMLHttpRequest();
var url = "path_to_file.php";
var params = "itemId="+ itemId + "&userId=" + userId; //Please note that the 2 params are separated by an **&** not a **?** as in your question
http.open("POST", url, true);
//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.onreadystatechange = function() {//Call a function when the state changes.
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
http.send(params);
Also the quotes here are unnecessary when passing parameters:
$cartManager->addToCart("$itemId","$userId");
If it is possible try to var_dump($_REQUEST) before calling the addToCart method to make sure that parameters have been successfully sent through the javascript request.
Now regarding the sql query you have to update the class and use bindParam and afterwards call the execute. I have updated your php code as follows:
class Cart{
public function addToCart($item,$user){
include 'connect.php';
$query = $bookStore->prepare("INSERT INTO cart SET item_Id=:item_id, user_Id=:user_id");
$query->bindParam(':item_id', $item);
$query->bindParam(':user_id', $user);
$query->execute();
}
}
$cartManager = new Cart();
$itemId = $_REQUEST["itemId"];
$userId = $_REQUEST["userId"];
$cartManager->addToCart($itemId, $userId);
For more reference regarding prepared statements you can have a look at this: http://php.net/manual/en/pdo.prepared-statements.php
I'm trying to include the Wordpress blog header in a php file to use it as an AJAX call function.
define('WP_USE_THEMES',false);
echo 'Something';
require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-blog-header.php');
Original snippet found in: Wordpress include("../../../wp-blog-header"); failing, current by Ole Sauffaus.
The code only works when there is something echoed or printed between the define and the require function. Without it the server responds with a 404-error.
This behavior occurs only when I target the php via an AJAX request as follows.
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('directory_results').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "http://localhost:8888/appsconnected/wp-content/themes/appsconnected/ajax-loop.php");
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.send("platform=" + platforms + "&category=" + category + "&orderby=" + order);
What causes this behavior?
Try this:
<?php
define('WP_USE_THEMES',false);
require(explode("wp-content",realpath(dirname(__FILE__)))[0].'wp-blog-header.php');
?>
Problem: Trouble receiving what is being sent to my PHP document.
Javascript:
$('#form_id').submit(function(event){
event.preventDefault();
event.stopPropagation();
var message;
var myRegExp = validation stuff
var urlToValidate = document.getElementById("url").value;
if (!myRegExp.test(urlToValidate)){
}else{
var code = (urlToValidate).slice(-22)
var request = new XMLHttpRequest();
request.addEventListener('readystatechange', function(event){
if (this.readyState == 4){
if (this.status ==200){
console.log (this.status);
}else{
console.log('Server replied with HTTP status ' + this.status);
}
}
});
request.open('POST', 'php/submit.php', true);
request.setRequestHeader('Content-Type', 'text/plain');
request.send("code=" + code);
}
});
Then I'm using this code on my php/submit.php:
if (!empty($_POST['code'])) {
$code = $_POST['code'];
echo $code;
};
I feel like I'm not using the right tag names for PHP because I'm new to all of this. I'll note that I'm using form id but getting the value from an input.
Ramblings
I'm trying to send a user input that has been validated and sliced to mySQL database.
I achieved the string I wanted with javascript and passed it to a variable.
I'm trying to send it to a separate php file in another folder with a request.send(the_javaS_variable).
Now in the console I can see the variable holds the correct text value and I see it sending with state 4 and 200.
But it never shows up on the submit.php page.
try this and remove the console.log()
$('#form_id').submit(function(event){
var myRegExp = validation stuff
var urlToValidate = document.getElementById("url").value;
if (!myRegExp.test(urlToValidate)){
// failed
}else{
var code = 'code='+(urlToValidate).slice(-22);
$.post('php/submit.php', code, function() {
// success stuff
});
}
return false;
});