How to post text variable in angular to mysql trough php - javascript

so I have a little bit tricky or rather say odd situation.
I have php and mysql database, for frontend I am using angular.js
So I am creating service, that sends data, via post request to php.
So everything is working properly when I am sending input values via name html attribute.
But problem appears when I am trying to send hardcoded text variable from for loop.
I know it's very hardcoded way for doing it but i don't know how to do it differently.
So here is my php
<?php
$conn = mysqli_connect('localhost','nemkeang','nemkic23','interventure');
if(!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$text = $_POST['first_name'];
$text2 = $_POST['last_name'];
$text3 = $_POST['date'];
$text4 = $_POST['author'];
$text5 = $_POST['note'];
$text6 = $_POST['skill'];
$target = "/assets";
$target = $target . basename( $_FILES['cv_file_name']['name']);
//This gets all the other information from the form
$file_name= $_FILES['cv_file_name']['name'];
$file_name2= $_FILES['cv_file_name']['name'];
//Writes the file to the server
if(move_uploaded_file($_FILES['cv_file_name']['tmp_name'], "./".$file_name)) {
//Tells you if its all ok
echo "The file ". basename( $_FILES['cv_file_name']['name']). " has been uploaded, and your information has been added to the directory";
// Connects to your Database
}
$sql = "INSERT INTO user (first_name, last_name, skill, date, cv_file_name, cv_url, author, note)
VALUES ('$text','$text2','$text6','$text3','$file_name','$file_name2','$text4','$text5')";
if (!mysqli_query($conn,$sql)) {
die('Error: ' . mysqli_error($conn));
}
else {
echo "success";
}
mysqli_close($con);
?>
The php is working correctly it's sending data, but on the $text6 = $_POST['skill']; problem arrives.
So here is my angular service first
app.service('testpost',['$http',function($http){
this.saveRecipe = function(postdata){
let payload = new FormData();
payload.append("first_name", postdata.first_name);
payload.append('last_name', postdata.last_name);
payload.append('date', postdata.date);
payload.append('cv_file_name', postdata.cv_file_name);
payload.append('author', postdata.author);
payload.append('note', postdata.note);
payload.append('skill', postdata.skill);
return $http.post('login/post.php', payload, {
transformRequest: angular.identity,
headers: {'Content-Type': undefined},
})
}
}]);
And it's also working correctly, when i log it to console, it shows correct values. Just don't send payload.append('skill', postdata.skill); value to php.
Here is my controller
app.controller('newUser',['$scope','$filter','testpost', function($scope,$filter,testpost) {
$scope.postdata = {}
$scope.arr = [];
let bar = document.getElementsByClassName('md-chip-content');
this.saveRecipe = function(postdata) {
for(var i = 0; i < bar.length; i++) {
$scope.arr.push(bar[i].innerText);
}
let skills = $scope.arr;
postdata.date = $filter('date')(postdata.date, "MM/dd/yyyy").split('/').join('-');
postdata.skill = skills[0];
postdata.skill2 = skills[1];
postdata.skill3 = skills[2];
postdata.skill4 = skills[3];
testpost.saveRecipe(postdata).then((data)=>{
console.log(data);
})
error:(err) =>{ return false};
}
}]);
Just to be clear i just want the value from postadata.skill to be sent to mysql via php. And I think the problem is in php because the value don't come from input type.
I hope that I've explained everything well. Thanks in advance.

Related

How to get variable value from PHP to Java Script via AJAX?

I have created a chat website. I send the message with AJAX to PHP and the MySql Database. The messages are fetched using AJAX which runs per second. But this lead to fetch of all the messages (from starting to end). I came with an solution that I will pass the last message ID to the AJAX/JAVA SCRIPT and then fetch only the messages which are more than that.
Here is the Java Script / AJAX
function fetchdata(){
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
data : {cuser:cuser, ouser:ouser},
success: function(read){
$("#readarea").html(read);
}
});
}
Here is the PHP code to get messages:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
$result = mysqli_query($conn, $sql) or ("Query Failed");
while($row=mysqli_fetch_assoc($result)){
if($row["fromid"]==$_POST['cuser']){
echo "<div class='cuser'>".$row["message"]."</div>";
}else{
echo "<div class='ouser'>".$row["message"]."</div>";
}
}
Here I want to get the ID (message) in the Java Script function back from the PHP and use it as a variable for fetching the messages which will be more than it.
You should return JSON from the PHP, instead of HTML. That way you can return an object with properties such as ID, message, etc. Then you can use Javascript to store the latest ID, and also to put the message into your page with the relevant HTML.
Something like this:
PHP:
$sql = "SELECT id, fromid,message,toid FROM messages WHERE (fromid={$_POST['cuser']} AND toid={$_POST['ouser']}) OR (fromid={$_POST['ouser']} AND toid={$_POST['cuser']})";
if (!empty($_POST["lastid"]) $sql .= " AND id > {$_POST['lastid']}";
$result = mysqli_query($conn, $sql) or ("Query Failed");
$messages = array();
while($row=mysqli_fetch_assoc($result)){
$messages[] = $row;
}
echo json_encode($messages);
JS:
//make this global so it persists beyond each call to fetchdata
var lastMessageID = null;
function fetchdata()
{
var cuser = //id of the current user
var ouser = //id of the other user
$.ajax({
url: "messagesprocess.php",
type: "POST",
dataType: "json",
data : { cuser: cuser, ouser: ouser, lastid: lastMessageID },
success: function(read) {
for (var i = 0; i < read.length; i++)
{
var className = "ouser";
if (read[i].fromid == cuser) classname = "cuser";
$("#readarea").append("<div class='" + className + "'>" + read[i].message + "</div>");
lastMessageID = read[i].id;
}
}
});
}
P.S. Please also take note of the comment about about SQL injection and fix your query code, urgently. I haven't done it here for the sake of brevity, but it must not be ignored.

Access Json Array from HTTP Get request and Update Page every 1s Using AJAX or JQUERY

So, I'm working on a project which involves getting data from my website into the ESP32. I came across making the Json array and updating the info from time to time, but now I need to get the specific info from my Json array so I can use it with my ESP. For some reason when I try to access the data from my page, I'm getting 0 instead of the number that is in that place, in the case of text, I don't receive anything as a response. I fixed not receiving any response from the file, I had to create a separate PHP file in which get the database info and turns that info in a datajson.json file, so the code that I have works, but I will need to update the PHP file every 1 second, I saw that Ajax was the way to go since I wouldn't need to refresh the page every time, only the content
ESP32 code:
void loop() {
if ((WiFi.status() == WL_CONNECTED)) { //Check the current connection status
HTTPClient http;
http.begin("https://nps-tech.com.br/receive.php"); //Specify the URL and certificate
int httpCode = http.GET();
if (httpCode > 0)//Check for the returning code
{
String payload = http.getString();
Serial.println("\nStatuscode: "+ String(httpCode));
Serial.println(payload);
char json[500];
payload.replace(" ", "");
payload.replace("\n", "");
payload.trim();
payload.remove(0,1);
payload.toCharArray(json, 500);
StaticJsonDocument<200> doc;
deserializeJson(doc, json);
int id = doc["AutoIncrement"];
const char* nome = doc["Nome Aparelho"];
int stat = doc["Status"];
Serial.println(id);
Serial.println(nome);
Serial.println(stat);
}
else
{
Serial.println("Error on HTTP request");
}
http.end(); //Free the resources
}
delay(10000);
}
New response from ESP32:
Statuscode: 200
[{"AutoIncrement":"1","Aparelho":"LED","Status":"0"}]
1
LED
0
PHP Code, How can I set a SetInterval to update get_data function from php every 1 second, without reloading the page:
<!DOCTYPE html>
<html lang="pt-br">
<head>
</head>
<body>
<?php
function get_data()
{
$servername = "stuuf";
$dBUsername = "stuuf";
$dBPassword = "stuuf";
$dBname = "stuuf";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
if ($conn->connect_error){
die ("Connection failed". $conn->connect_error);
}
$sql = "SELECT * FROM dados;";
$result = mysqli_query($conn, $sql);
$json_array = array();
while($row = mysqli_fetch_assoc($result))
{
$json_array[] = array(
'AutoIncrement' => $row["AutoIncrement"],
'Aparelho' => $row["aparelho"],
'Status' => $row["Status"],
);
}
return json_encode($json_array);
}
$file_name = 'dadosjson' . '.json';
if (file_put_contents($file_name, get_data()))
{
echo $file_name. ' file created';
}
else
{
echo 'There is some error';
}
?>
<script>
setInterval(1000);
//ajax to update every 1s
</script>

Having issues interpreting json inside php and passing it to mysql

I am new to php and I am not sure how to debug this.
I am trying to pass json to a php page and then send that data to mySQL.
I think it is having issues interpreting the data inside the php file or getting the information to the php page. When I open the php file it gives signs that it is properly accessing the database.
Here is my javascript code:
var request = new XMLHttpRequest();
request.open('POST', 'http://website/saveF.php', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.send(bInfo);
This is taking information in and passing it to a php file to then be added to a mySQL database.
Here is my php code:
This is decoding the jSon and then itterating over each entry inside the array. It then asks the question if it has a website listed or not and stores it into the appropriate table.
//as long as the connection is good then we keep it live.
include_once "head.php";
if ($conn->connect_error) {
die("connection failed: " . $conn->connect_error);
}
//gettting the information from the front end (index.html)
$inputJSON = file_get_contents('php://input');
//decode all the previously encoded information
$postThings = json_decode($inputJSON, TRUE);
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
//create a variable the is the total length of our array
$totalNum = count($input);
//arrays start at 0
$i = 0;
//you can see where this is going. We have a while loop that will continue as long as i is less than totalnum. Ask me why i didn't use a for loop.... I don't have an answer.
while($i < $totalNum){
$var0 = $input[$i][0];
$var1 = $input[$i][1];
$var2 = $input[$i][2];
$var3 = $input[$i][3];
$var4 = $input[$i][4];
$var5 = $input[$i][5];
$var6 = $input[$i][6];
if($var1 == "Not Listed") {
$sql = "INSERT INTO missing(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}else{
//here we set the information into the database.
$sql = "INSERT INTO companies(cName, website, rating, phone, id, address, placeType) VALUES ('$var0', '$var1', '$var2', '$var3', '$var4', '$var5', '$var6')";
}
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$i++;
}
First, note that this line:
$input = filter_var($postThings, FILTER_SANITIZE_STRING);
Will return FALSE if sanitization fails on any of the array elements. In your code, you should be testing if($input) immediately after the sanitization.
Furthermore, you will want to sanitize your inputs further to avoid SQL injection and XSS attacks. (e.g. remove SQL escape characters and other injectable characters).
http://php.net/manual/en/mysqli.real-escape-string.php
Last, it is recommended that you use bound parameters or fully sanitized inputs to avoid a SQL injection attack.

External PHP file not get variable from PHP link

Building a messaging system for my site and i have been stuck for days. I have this PHP link
<a href='user_msg.php?hash=$hash'>$name</a>
When you click on the link, it takes you to a page where you can send message to a user you've connected to (this connection is binded by the $hash)
in the page for sending the message, i hid the $hash in and hidden input value="$hash" and it sends the message to row in database with the $hash with the following scripts (They have no issue and work fine)
var msg_area = $('.msg_area');
msg_area.scrollTop(msg_area.prop("scrollHeight"));
$('#send_rep').submit(function (e) {
e.preventDefault();
var $form = $(this), url = $form.attr('action');
var posting = $.post(url, {rep_msg: $('#rep_msg').val(), hash: $('#hash').val()});
posting.done(function (data) {
alert('success');
});
});
PHP script to send
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['rep_msg']) && !empty($_POST['rep_msg']) || isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_GET['hash'];
$my_id = $_SESSION['log_id'];
$rep_msg = $_POST['rep_msg'];
$hash = $_POST['hash'];
$rsql = <<<EOF
INSERT INTO messager (message, group_hash, from_id) VALUES('$rep_msg', '$hash', '$my_id');
EOF;
$rret = $db->exec($rsql);
$ursql = <<<EOF
SELECT * FROM User WHERE ID = '$my_id';
EOF;
$urret = $db->query($ursql);
while ($urrow = $urret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urrow['fname'];
$from_img = $urrow['image'];
header('Location: user_msg.php?hash=' . $hash);
}
}
The above Ajax Request and php script work fone to sedn the messages to database.
The issue not is getting the messages from database
This is the script i am currently using (not working)
PHP script to get message
require_once ("db.php");
$db = new MyDB();
session_start();
if (isset($_GET['hash']) && !empty($_GET['hash']))
{
$hash = (int)$_GET['hash'];
$us_id = $_SESSION['log_id'];
$mesql =<<<EOF
SELECT from_id, message FROM messager WHERE group_hash = '$hash';
EOF;
$meret = $db->query($mesql);
while ($merow = $meret->fetchArray(SQLITE3_ASSOC))
{
$from_id = $merow['from_id'];
$messages = $merow['message'];
$usql =<<<EOF
SELECT * FROM User WHERE ID = '$from_id';
EOF;
$uret = $db->query($usql);
while ($urow = $uret->fetchArray(SQLITE3_ASSOC)) {
$from_fname = $urow['fname'];
$from_img = $urow['image'];
if ($from_id != $_SESSION['log_id']) {
echo "
<div class='from_bubble'><div class='from_img'><img src='$from_img'></div><div class='from_txt'><p>$messages</p></div></div>";
} else {
echo "
<div class='rep_bubble'><div class='rep_img'><img src='$from_img'></div><div class='rep_txt'><p>$messages</p></div></div>";
}
}
echo "<input style='display: none' type='text' class='hash' name='hash' value='$hash' id='hash'>";
}
}
Ajax Request
setInterval(function() {
$('.msg_area').load("get_msg.php");
}, 2000);
But the get is not working. I suspect fro some reason, its not getting the $hash. Please is there a solution to this or am i trying something impossible.
Any help would be appreciated. If more info is needed please ask. Thanks in advance
Maybe $hash = (int)$_GET['hash']; would be $hash = (int)$_POST['hash'];
And you have more than just one $_GET...
In your ajax request you are using POST so you will need to get the hash with the POST as well: if (isset($_POST['hash']) && !empty($_POST['hash']))
{
$hash = (int)$_POST['hash'];
Using '' in PHP indicates the actual string you are writing.
If you want to use a PHP variable in a string you should use "", so try changing $name
Check this for more info:
http://php.net/manual/en/language.types.string.php
Then, how do you hide your hash in the input?
You could use <input value="$_GET['hash']" ... />
In the script to send , does it enter the if? Try adding statements to see if SQL returns any error.
Hope this helps.
Answer to the question was to create a PHP SESSION for the $hash($_SESSION['hash'] = $hash) and to use this session all over the site with session_start().

$_GET PHP is misbehaving

I'm a javascript newbie and I'm writing an application using javascript with php on the server side, I'm trying to use AJAX to send data to my php script. This is my code below
Javascript:
$(document).on("click", ".uib_w_18", function(evt)
{
var lecturer = document.getElementById("reg_name").value;
//var lecturer = $("#reg_name").val();
var dept = document.getElementById("reg_dept").value;
var level = document.getElementById("reg_level").value;
var course = document.getElementById("reg_course").value;
var start = document.getElementById("reg_time_1").value;
var ade = 2;
window.alert(lecturer);
var dataString = '?ade=' + ade+'&lecturer='+lecturer+'&dept='+dept +'&level='+level+'&course='+course+'&start='+start;
$.ajax({
type: "GET",
url: 'http://localhost/my_queries.php',
data: dataString,
success: window.alert ("I've been to localhost.")
});
window.alert(dataString);
});
and on the server side:
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbname = "myDatabase";
$dbpass = null;
//Connect to MySQL Server
echo "yo";
$con = mysqli_connect($dbhost, $dbuser,$dbpass,$dbname);
$level = $_GET['level'];
$lecturer = $_GET['lecturer'];
$sql = "INSERT INTO level1(message, department)
VALUES ($level,'Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ($lecturer,'Jane')";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
?>
now the problem is '$sql1' executes successfully but '$sql2' doesn't. I've been on this for a while and found out that $_GET in the script only works for numerical data. I've confirmed that the problem is not from the data type of my table, I can insert literal strings directly from PHP, I'm also confirmed that "dataString" collects data just like I want it to. (window.alert(dataString);) displays correct output.
I feel like I'm missing something very basic but I just can't figure out what it is. and i felt extra pairs of eyes would help, any help would be appreciated, Thank you.
The proper way to pass "dynamic" SQL queries is like so :
$sql = "INSERT INTO level1(message, department)
VALUES ('".$level."','Jane')";
$sql2 = "INSERT INTO level1(message, department)
VALUES ('".$lecturer."','Jane')";

Categories