The data i get back to FETCH from my PHP file, had an added empty paragraph at the beginning - fetch-api

I use the FETCH API to pull data from the backend, but since some time I am getting an empty paragraph at the beginning of each response. Unfortunately for me, I am not able to track down what change was made that has caused this, so I am looking for possible reasons why this would happen in order to eliminate it.
Below is once such fetch:
await fetch('__transport.php', {
method: "POST",
body: new URLSearchParams("pk="+pk+"&drvr="+drvr+"&col="+col)
})
.then(response => response.text())
.then((response) => {
if(response.substr(0,6) == "Failed") {
alert(response)
} else {
document.getElementById(id).innerHTML = response;
}
})
.catch(err => console.log('s/g went wrong', err));
and here the backend, the mysql query was removed from the end, but it returns a name
$pk = $_POST['pk'];
$drvr = ($_POST['drvr'] != 0 ? $_POST['drvr']:'NULL');
$col = $_POST['col'];
$sql = "UPDATE mytable
SET
$col = $drvr
WHERE pkcolumn = $pk";
if ($conn->Execute($sql)==false) {
exit("Failed to update database\n\n".$conn->ErrorMsg()."\n\n".$sql);
} else if($drvr != 'NULL'){
//mysql query removed for simplification as I get the same result with this
$name = "Jack Sparrow";
exit($name); //returns the name to the above FETCH
} else {
exit(' '); //returns no name as the field should be blank in this case
}
I am expecting the return "Jack Sparrow" to be received by the JavaScript in the variable "response", as:
"Jack Sparrow"
What I get is and empty paragraph followed by the name:
"
Jack Sparrow"

Related

UnityWebRequest: Null response

So I have a website(it is unsecured/it doesn't have an SSL certificate) where I have a php script that echo's some info of my database. Here is it:
$query = "SELECT id, password FROM users WHERE username = ".$_GET['uname'];
$result = mysqli_query($connect, $query);
while( $record = mysqli_fetch_assoc($result) )
{
echo json_encode($record);
}
Now, in Unity(version 2022.1.0b10.2818), I have a script that does a get request to my website and gets the info the php script displayed. Here is the script:
IEnumerator GetText()
{
string url = "http://example.com/getUser.php?uname=" + "'" +
usernameInputField.text + "'";
using(UnityWebRequest www = UnityWebRequest.Get(url))
{
yield return www.SendWebRequest();
if(www.result != UnityWebRequest.Result.Success)
{
Debug.Log(www.error);
}
else
{
response = www.downloadHandler.text;
}
}
}
Why does it always give me this error:
Curl error 52: Empty reply from server
and I also get this log in the console from the Debug.log(ww.error):
Received no data in response
How can I fix this?

What i did wrong specifying bootbox message, i'm getting an error?

I'm using this function to send in other page where I'm updating user permission level.
var setPermLevel = function(userId, value)
{
$.ajax({
type: "POST",
url: "/user/setPermLevel",
data: {id: userId, value: value},
success: function(data)
{
if(data[0]['error']) bootbox.alert(data[0]['error']);
else bootbox.alert(data[0]['message'], function() { location.reload(); });
}
});
};
I'm trying with that code to send back a message to bootbox to show up to user, but I'm getting anyway an error from bootbox "Please specify a message".
if(isset($_POST['id']))
{
$userId = $_POST['id'];
$value = $_POST['value'];
$rslt = "[";
if(User::isAdmin($_SESSION['user']) < 6 && $value > 4) {
$rslt .= '{"error":" You can\'t acces that."}';
}
else {
$q = DB::prepare('UPDATE `users` SET `Admin` = ? WHERE `ID` = ?');
$q->execute(array($value, $userId));
$data .= '{"message":" Succesfully"}';
}
$rslt .= "]";
echo $rslt;
}
This is the error:
Uncaught Error: Please specify a message
at sanitize (bootbox.js:109)
at Object.window.bootbox.window.bootbox.exports.dialog (bootbox.js:450)
at Object.window.bootbox.window.bootbox.exports.alert (bootbox.js:246)
at Object.success (toolBox.js:3470)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at A (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
What I did wrong, can anyone help me?

sequelize.query returns empty array

Using Sequelize 4.38.1 against PostgreSQL 10.5, I have the following code:
const criteria = {
attended: '2018-09-21',
location: 'Squirrel Hill',
teacher: 'Doe, John',
classTitle: 'Yoga 1'
};
const sql = `
SELECT
"Attendances"._id,
"Attendances"."UserId",
"Users"."lastName" || ', ' || "Users"."firstName" AS name
FROM
"Attendances" INNER JOIN "Users" ON "Attendances"."UserId" = "Users"._id
WHERE
"Attendances".attended = :attended AND
"Attendances".location = :location AND
"Attendances".teacher = :teacher AND
"Attendances"."classTitle" = :classTitle
ORDER BY "Users"."lastName", "Users"."firstName";`;
sequelize.query(
sql,
{
replacements: criteria,
type: sequelize.QueryTypes.SELECT
})
.then(attendeeList => {
console.log(attendeeList);
return res.status(200).json(attendeeList);
})
With sequelize logging turned on, my query is correctly parameterized with the replacements and executed:
SELECT
"Attendances"._id,
"Attendances"."UserId",
"Users"."lastName" || ', ' || "Users"."firstName" AS name
FROM
"Attendances" INNER JOIN "Users" ON "Attendances"."UserId" = "Users"._id
WHERE
"Attendances".attended = '2018-09-21' AND
"Attendances".location = 'Squirrel Hill' AND
"Attendances".teacher = 'Doe, John' AND
"Attendances"."classTitle" = 'Yoga 1'
ORDER BY "Users"."lastName", "Users"."firstName";
The problem: my results (attendeeList) are getting returned as []. When I run the same query using pgAdmin, I get one row:
_id UserId name
40 24601 "Doe, John"
Anyone have any thoughts as to what I'm doing wrong?
I submitted the example above as an Issue on Sequelize's Github repo as I was able to make it work with a query that did not include an INNER JOIN.
For my situation, pg-native is a better fit (considering ripping out sequelize elsewhere as it's slower)...
const client = new PGNativeClient();
client.connect(config.sequelize.uri, err => {
if(err) {
res.status(401).json({ message: 'Not able to connect to database to get list of attendees.' });
return;
}
const sql = `
SELECT
"Attendances"._id,
"Attendances"."UserId",
"Users"."lastName" || ', ' || "Users"."firstName" AS name
FROM
"Attendances" INNER JOIN "Users" ON "Attendances"."UserId" = "Users"._id
WHERE
"Attendances".attended = $1::DATE AND
"Attendances".location = $2 AND
"Attendances".teacher = $3 AND
"Attendances"."classTitle" = $4
ORDER BY "Users"."lastName", "Users"."firstName";`;
const { attended, location, teacher, classTitle } = req.query;
client.query(sql, [attended, location, teacher, classTitle], (err, rows) => {
if(err) {
res.status(424).json({ message: 'Not able to retrieve attendees from database (but connected successfully).' });
return;
}
res.status(200).json(rows);
});

Facebook Graph Api error "An unexpected error has occurred. Please retry your request later"

I'm trying to retrieve all members in a Facebook group getting this error:
array(5) {
["message"]=>
string(66) "An unexpected error has occurred. Please retry your request later."
["type"]=>
string(14) "OAuthException"
["is_transient"]=>
bool(true)
["code"]=>
int(2)
["fbtrace_id"]=>
string(11) "AnfsXcdgM"
}
Here is my code:
$this->_facebook = new Facebook\Facebook(array('app_id' => "$app_id",'app_secret' => "$secret",'default_graph_version' => 'v2.10'));
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name";
try{
$response = $this->_facebook->get($query);
while($pagesEdge)
{
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
$id = $member->id;
}
}
}catch (Facebook\Exceptions\FacebookResponseException $e) { echo 'Graph returned an error: ' . $e->getMessage(); }
It works for groups with few hundreads of people (even once for a group with 10.000 members) but randomly I'm occurring to this.
This might be caused by a server side timeout. I get this error every now and then when I request a huge amount of data. Maybe you should try to limit your request by using the limit parameter (default should be 25).
I solved this by doing a cron that takes 100 data at the time and putting into a file text the value of the token for the next call.
I add this string on the query and when the fields inside $url are empty I quit my execution
<?php
public function updateGroupMembers($groupID)
{
$tempNext = file_get_contents($this->dirM); //check if the next string token is in the file
if (!empty($tempNext))
{
$queryUntil = $tempNext;
}
// Sets the default fallback access token so we don't have to pass it to each request
$this->_facebook->setDefaultAccessToken($_SESSION['facebook_access_token']);
// Create table name
$tableName = $groupID . "_Members";
// Query the Graph API to get all current member's ID and name
try
{
$query = "/".$groupID."/members?fields=id,name,link,picture,first_name,last_name".$queryUntil; //add the next string to my query
$response = $this->_facebook->get($query);
$pagesEdge = $response->getGraphEdge();
// Index for the elements fetched from the API below
$i = 0;
// Get current time
$pageDecoded = json_decode($pagesEdge);
foreach($pageDecoded as $key => $member)
{
/* ...get data and process them... */
}
$temp = $pagesEdge->getMetaData();
$next = parse_url($temp['paging']['next']);
parse_str($next['query'], $url);
$access_token = '&access_token='.$url['access_token'];
$fields = '&fields='.$url['fields'];
$limit = '&limit=100';
$after = '&after='.$url['after'];
$res['until'] = $access_token.$fields.$limit.$after;
file_put_contents($this->dirM, $res['until'], LOCK_EX);
if ( empty($url['access_token']) || empty($url['fields']) || empty($url['limit']) || empty($url['after']) )
{
file_put_contents($this->dirM, '', LOCK_EX); //clean my txt file that contains my next string
die('FINE');
}
} catch (Facebook\Exceptions\FacebookResponseException $e) {
echo 'm2Graph returned an error: ' . $e->getMessage();
exit;
} catch (Facebook\Exceptions\FacebookSDKException $e) {
echo 'm2Facebook SDK returned an error: ' . $e->getMessage();
exit;
}
}

Image capture/upload with Phonegap (cordova) for iPhone not working

I have been trying to set up an app through PhoneGap (Cordova) to take images and upload them to our server. I have gone through so many of the responses on here and tried the code in them. I can get the camera up and taking a photo, I can access the phone gallery even. But I can not get it to send the image to the server. I've tried sending the image, and even sending the base64 image stream. I can't get it to the server.
Here is the javascript on the client side:
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
}
function ImageUpload() {
this.useExistingPhoto = function(e) {
this.capture(Camera.PictureSourceType.SAVEDPHOTOALBUM);
}
this.takePhoto = function(e) {
this.capture(Camera.PictureSourceType.CAMERA);
}
this.capture = function(sourceType) {
navigator.camera.getPicture(this.onCaptureSuccess, this.onCaptureFaile, {
destinationType: Camera.DestinationType.FILE_URI,
soureType: sourceType,
correctOrientation: true
});
}
this.onCaptureSuccess = function(imageURI) {
var fail, ft, options, params, win;
success = function(response) {
alert("Your photo has been uploaded!");
};
fail = function(error) {
alert("An error has occurred: Code = " + error.code + "\nMessage = "+error.message);
};
options = new FailUploadOptions();
options.fileKey = "file";
options.fileName = imageURI.substr(imageURI.lastIndexOf('/') + 1);
options.mimeType = "text/plain";
params = {
val1: "some value",
val2: "some other value"
};
options.params = params;
ft= new FileTransfer();
ft.upload(imageURI, 'http://style.appdev01.com/app/client-profile.php', success, faile, options);
}
this.OnCaptureFail = function(message) {
alert("Failed because: "+message);
}
};
var imageuploader = new ImageUpload();
Two buttons call imageuploader.takePhoto and .useExistingPhoto on click.
On the server side I have this php:
if(isset($_FILES['file'])) {
$target_path = "/home/style/public_html/images/client_images/app_image.jpg";
move_uploaded_file($_FILES['file']['tmp_name'], $target_path);
$insert = "INSERT INTO
`fut`
SET
`request` = '".serialize($_POST)."',
`file` = '".serialize($_FILES)."'";
$mysql->query($insert);
}
This is just to store the POST and FILE arrays to the db to make sure they came through and create the image.
But again, nothing is getting to the server. Any help would be GREATLY appreciated. I've tried so many versions of this code from so many questions here and all over the web.
define ('SITE_ROOT', realpath(dirname(__FILE__))); /* echo SITE_ROOT; to dir
move_uploaded_file($_FILES["file"]["tmp_name"],SITE_ROOT."/uploads/".$_FILES["file"]["name"]); // will move file, make sure uplaods has write permission!
That works for me on Android Simulator, not on Tablet, but let me know if you have it working, busy on the same thing.
$myarray = array( $_REQUEST);
foreach ($myarray as $key => $value) {
echo "<p>".$key."</p>";
echo "<p>".$value."</p>";
echo "<hr />";
}
That you can use to check POST / GET!
Try this is my code. It has worked for me.
Encode your URL by encodeURI method
fileKey with "file" as in your server side script $_FILES['file']
uploadFile: function(refNo){
var uri = fileUpload.fileUri;
var file = uri.substr(uri.lastIndexOf('/') + 1);
var options = new FileUploadOptions();
options.fileKey = "file";
options.fileName = file;
options.mimeType="image/jpeg";
alert("name === "+uri);
options.chunkedMode = false;
var ft = new FileTransfer();
Common.ajaxLoading('show');
ft.upload(uri,encodeURI("http://172.16.1.147:80/upload/home.php") , fileUpload.uploadSuccess, fileUpload.uploadFail, options, true);
},