I don't have much experience with PHP, but what I'm trying to do is to write content to a file. For some reason the content is written to the file, but still returns 'failed to write to file!' with the 400 status code. But the contents are successfully written to the file. How?
php code (update.php):
<?php
//get root and page of request
$content_root = $_SERVER['DOCUMENT_ROOT'] . '/Animagie/content';
$page = $_POST['page'];
//open the correct contentfile
$content_file = fopen($content_root . '/' . $page, 'w');
if (isset($_POST[$page . '-content'])) {
if (fwrite($content_file, $_POST[$page . '-content']) === FALSE ) {
echo 'failed to write to file!';
fclose($content_file);
http_response_code(400);
} else {
fclose($content_file);
http_response_code(200);
}
} else {
echo 'something went wrong!';
fclose($content_file);
http_response_code(400);
}
?>
I call update.php with following code:
editor.addEventListener('saved', function(e) {
var name, payload, regions, xhr;
//check if something changed
regions = e.detail().regions;
if (Object.keys(regions).length === 0) {
return;
}
//set editor busy while saving
this.busy(true);
// Collect the contents of each region into a FormData instance
payload = new FormData();
payload.append('page', getCurrentPage());
for (name in regions) {
if (regions.hasOwnProperty(name)) {
payload.append(name, regions[name]);
}
}
// Send the updated content to the server to be saved
function onStateChange(e) {
//check if request is finished
if (e.target.readyState === 4) {
editor.busy(false);
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
}
}
xhr = new XMLHttpRequest();
xhr.addEventListener('readystatechange', onStateChange);
xhr.open('POST', '../api/update.php');
xhr.send(payload);
});
As you probably can tell it's quiet important to get the correct statuscode since I check for it and return if it's succesfull or not to the user. Anyone able to help me?
Thanks in advance!
Apperently the problem lays in the javascript check:
if (e.target.status === '200') {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
should be
if (e.target.status == 200) {
new ContentTools.FlashUI('ok');
} else {
new ContentTools.FlashUI('no');
}
Also after I switched the if-statement (like told by #Jon Stirling), postman wasn't refreshed yet. So it was partially a wrong if-statement on the server side & wrong if-statement on the client side.
Related
I'm using PHP 7.3 with MySQL v5.6.
Browsing a catalog page, I stored some items ids to localStorage.wishlistStorage.data, and now on the wishlist page I want to retrieve this list of ids for display. I'm using PHP because later I will be sending and retrieving items from a database. Also, it's easy to build HTML on the fly using PHP and a POST array. Unfortunately, I'm struggling with the AJAX XMLHttpRequest.
I am loading a Javascript file at the bottom of the page that retrieves the localStorage data:
var wishlistStorage = {};
window.addEventListener("load", function() {
wishlistStorage.get();
loadWishlist();
});
wishlistStorage = {
data : null, // empty storage
get : function() {
wishlistStorage.data = localStorage.getItem("wishlistStorage");
if(wishlistStorage.data === null) {
wishlistStorage.data = { items: [], item_notes: [], comments: '' };
wishlistStorage.save();
}
else {
wishlistStorage.data = JSON.parse(wishlistStorage.data);
}
}
};
// get wishlist contents
function loadWishlist() {
var items = wishlistStorage.data.items.join("%20");
var wishlistRequest;
if(window.XMLHttpRequest) {
wishlistRequest = new XMLHttpRequest();
} else {
wishlistRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
wishlistRequest.onreadystatechange = function() {
if(wishlistRequest.readyState == 4 && wishlistRequest.status == 200) {
console.log("Got them.");
} else {
console.log("I see nothing.");
}
wishlistRequest.open("POST", "_self", true);
wishlistRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
wishlistRequest.send("wishlist_items=" + encodeURIComponent(items));
}
}
In the body of wishlist.php
<?php
if (array_key_exists('wishlist', $_POST)) {
$temporary_wishlist = $_POST['wishlist'];
echo "Yes, it works! $temporary_wishlist";
} else {
echo 'Invalid parameters!';
}
?>
All I get is the "Invalid Parameters" message. None of the console.log messages appear. Where am I going wrong?
source
below is my code fo ajax which sends a string data via post method, the request is successful but I get an empty response. I had checked the readystate and status both are proper and the php file is in the same directory.
function getData(str)
{
if (str == "")
{
} else
{
if (window.XMLHttpRequest)
{
var dat = new XMLHttpRequest();
} else
{
dat = new ActiveXObject("Microsoft.XMLHTTP");
}
dat.open("POST","userdat.php",true);
dat.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
dat.onreadystatechange = function ()
{
if (dat.readyState == 4 && dat.status == 200)
{
alert(dat.responseText);
$('#dataReT').text(dat.responseText);
}
}
dat.send("userid=" + str);
}
}
content of my php file:
<?php
$id=$_REQUEST['userid'];
echo $id;
?>
there is no userid in $_REQUEST. Try to add this to your php file:
if(array_key_exists('userid',$_REQUEST)) {
echo $_REQUEST['userid'];
} else {
echo 'no userid.';
}
You may send userid value from your javascript file
I writing a registration/login form, I am sending user info via POST to a PHP that is looking in a DB. I would like that the PHP returns an ok or wrong value to the js and I don't now how to do it.
Here my js:
ui.onClick_regsubmit=function()
{
var fname=document.getElementById('fname').value;
var lname=document.getElementById('lname').value;
var password=document.getElementById('password').value;
var mail=document.getElementById('mail').value;
var affiliation=document.getElementById('affiliation').value;
var data = new FormData();
var xhr = (window.XMLHttpRequest) ? new XMLHttpRequest() : new activeXObject("Microsoft.XMLHTTP");
data.append("fname",fname);
data.append("lname",lname);
data.append("password",password);
data.append("mail",mail);
data.append("affiliation",affiliation);
xhr.open( 'post', 'PHP/registration.php', false );
xhr.send(data);
window.alert(affiliation);
}
And the php:
<?php
mysql_connect('localhost','root','') or die('Cannot connect mysql server');
mysql_select_db('ChemAlive_login') or die('cannot connect database');
$lname=$_POST['lname'];
$fname=$_POST['fname'];
$password=$_POST['password'];
$mail=$_POST['mail'];
$affiliation=$_POST['affiliation'];
$q=mysql_query("select * from login where mail='".$mail."' ") or die(mysql_error());
$n=mysql_fetch_row($q);
if($n>0)
{
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password) echo "ok";
else echo "wrong";
}
else
{ $insert=mysql_query("insert into login values('".$fname."','".$lname."','".$mail."','".$password."','".$affiliation."')") or die(mysql_error());}
?>
I would like to return to js this ok or wrong value. How to do it?
xhr.onload=function()
{
if (xhr.status==200)
{
alert(xhr.response);
}else
{
alert("unknown server error");
}
}
it will be better if the server sends a response code, and javascript will transfer this code to the text. For example:
onload=function()
{
switch(xhr.response)
{
case "0":{alert("unknown error")};break;
case "1":{alert("email is already used")};break;
...
}
}
I think thought it is clear
I do not have the rep to comment or I'd ask for details, but if you can consider using ajax, it could look something like this:
php:
$doit = //your query;
if($doit){
$youdid = 'ok';
}
else{
exit('1');
}
js:
$(document).ready(function () {
var foo = $("#formfield")val();
$.ajax({
"foo":foo;
type: 'POST',
url: 'some.php',
success: function(responseText) {
if(responseText == "1") {
alert("Leave instantly");
};
}
else {
alert("One of us");
}
If you want to return either ok or wrong to the JavaScript to handle you could do something like this in your registration.php page:
$q=mysql_query("select password from login where mail='".$mail."' ");
$pp=mysql_fetch_row($q);
if($pp[0]=$password){
header('Content-Type: application/json');
echo json_encode(array('password' => 'ok'));
}else{
header('Content-Type: application/json');
echo json_encode(array('password' => 'wrong'));
}
I have not fully testing this, but the idea is to set the header to return json and then send it a JSON string.
Does that make sense?
Like I said in my comment below I have only used jQuery for AJAX. But here is a little something of what I know about XMLHttpRequest and my undertsanding of how you would test what you get back.
You can set up a listener for when you get a response back onreadystatechange and then put the response in a variable var pass = xhr.response and then just output the text to an alert box like alert(pass.password).
if (xhr.onreadystatechange === 4 && xhr.status === 200){
var pass = xhr.response;
//should output either ok or wrong
alert(pass.password);
}
Read more about XMLHttpRequest here
Let me know if that works.
I have an XMLHttpRequest where i am sending an image across to be saved on my Amazon s3 bucket. It works correctly and the file goes to my bucket but i am getting no response back saying it is in process or has successfully uploaded. My code is below:
Javascript code in html page:
var ajax = new XMLHttpRequest();
ajax.open("POST",'http://www.xxxx.php',false);
ajax.setRequestHeader('Content-Type', 'application/upload');
ajax.send(theImage);
ajax.onreadystatechange=function(){
if (ajax.readyState==4 && ajax.status==200) {
console.log('success');
}
else {
console.log('ongoing...');
}
}
PHP code in xxxx.php:
<?php
if (isset($GLOBALS["HTTP_RAW_POST_DATA"])){
$imageData = $GLOBALS['HTTP_RAW_POST_DATA'];
$filteredData = substr($imageData, strpos($imageData, ",")+1);
$imgFileString = base64_decode($filteredData);
$s3Filename = time().'.png';
if($s3->putObjectString($imgFileString, $bucket , $s3Filename, S3::ACL_PUBLIC_READ) ){
echo "SUCCESS";
}
else{
echo "ERROR";
}
}
else {
echo "EMPTY";
}
?>
How can i get a callback to say when the upload has successfully been uploaded or if an error has occurred?
ajax.open("POST",'http://www.xxxx.php',false);
^^^^^^
You are making a synchronous request, so the request is being made and the response received before you assign your event handler. Don't do that. Remove false (or change it to true).
I've been looking for a simple example of how to send POST data in a cross domain request in IE (with the XDomainRequest object).
I've been able to make a simple POST request, but haven't been able to add POST data to it.
Any help is appreciated, thanks!
Try something like this:
var xdr;
function err() {
alert('Error');
}
function timeo() {
alert('Time off');
}
function loadd() {
alert('Response: ' +xdr.responseText);
}
function stopdata() {
xdr.abort();
}
xdr = new XDomainRequest();
if (xdr) {
xdr.onerror = err;
xdr.ontimeout = timeo;
xdr.onload = loadd;
xdr.timeout = 10000;
xdr.open('POST','http://example.com');
xdr.send('foo=12345');
//xdr.send('foo=<?php echo $foo; ?>'); to send php variable
} else {
alert('XDR undefined');
}
Server side (php):
header('Access-Control-Allow-Origin: *');
if(isset($HTTP_RAW_POST_DATA)) {
parse_str($HTTP_RAW_POST_DATA); // here you will get variable $foo
if($foo == 12345) {
echo "Cool!"; // This is response body
}
}