Ajax / PHP Notice: Undefined index: - javascript

Pulling my hair out with this. Suddenly receiving the following error which wasn't there before:
>>PHP Notice: Undefined index: rmvFileList in C:\wamp\www\somesubdirectory\members\delete.php on line 7
This is coming from an Ajax submission to delete.php. Although the "notice" is appearing, the script is executing properly as it should (database deletion completed correctly, file deleted correctly, and the success call being logged correctly in the console.log). Probably just some sort of sick obsession, but I want to get rid of the warning popping up in my error log every time the delete script is called.
Here is the ajax:
var rmvFile = "Some file name";
$.ajax({
type: "POST",
url: "delete.php",
dataType:"text",
data: {'rmvFileList' : rmvFile },
success: function(returnData) {
console.log(returnData);
}
});
And here is delete.php:
<?php
session_start();
include('../../phpincl/db.php');
$table = 'phoeteo_img_' . $_SESSION['memberID'] . '_' . $_SESSION['showID'];
$name = $_POST['rmvFileList']; <<--This is line 7
$sql = "SELECT * FROM $table WHERE imgNameTime = '$name'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while($row = mysqli_fetch_assoc($result))
{
$toBeDeletedIndex = $row['imgIndex'];
$toBeDeletedFilename = $row['imgNameTime'];
$sql = "DELETE FROM $table WHERE imgNameTime = '$name'";
mysqli_query($conn, $sql) or die('Failed: ' . mysqli_error($conn));
$path = 'repository/' . $_SESSION['memberID'] . '_' . $_SESSION['showID'] . '/' . $toBeDeletedFilename;
unlink($path);
}
echo $name;
?>
Any and all help would be greatly appreciated. Thanks!

set isset in php:check code below :
if(isset($_POST['rmvFileList'])){
$name = $_POST['rmvFileList'];
$sql = "SELECT * FROM $table WHERE imgNameTime = '$name'";
$result = mysqli_query($conn, $sql) or die(mysqli_error($conn));
while($row = mysqli_fetch_assoc($result))
{
$toBeDeletedIndex = $row['imgIndex'];
$toBeDeletedFilename = $row['imgNameTime'];
$sql = "DELETE FROM $table WHERE imgNameTime = '$name'";
mysqli_query($conn, $sql) or die('Failed: ' . mysqli_error($conn));
$path = 'repository/' . $_SESSION['memberID'] . '_' . $_SESSION['showID'] . '/' . $toBeDeletedFilename;
unlink($path);
}
echo $name;
}

Related

How to handle PHP session variables on AJAX call?

When I try to get a Session variable into a php script called with AJAX to make a MySQL query it gives me ""
I've tried passing the id using a hidden_input filled with php at the loading of my web page and the function worked! but when I try to catch the session variable directly from the script called by the AJAX it stops working again :(
This is the code where I set my php variables, I call this script directly from a html form.
<?php
if(isset($_POST['empresa']))
{
if(isset($_POST['usuario']))
{
if(isset($_POST['password']))
{
$empresa = $_POST["empresa"];
$usuario = $_POST["usuario"];
$password = $_POST["password"];
$host = "localhost";
$bd = "nominet_Directorio_Web_Beta";
$us = "nominet_Marvin2";
$pas = "NominetBD2019!";
error_reporting(0);
$con = new mysqli($host, $us, $pas, $bd);
if($con->connect_errno)
{
echo "Error de conexión al servidor de base de datos...";
exit();
}
mysqli_set_charset('utf8');
$query = "SELECT `Tbl_Usuarios`.`Id`, `Tbl_Usuarios`.`Fk_Empresa`, `Tbl_Usuarios`.`Tipo_Usuario` FROM `Tbl_Usuarios` INNER JOIN `Tbl_Empresas` ON `Tbl_Usuarios`.`Fk_Empresa` = `Tbl_Empresas`.`Id` WHERE `Tbl_Usuarios`.`Usuario` = '" . $usuario . "' AND `Tbl_Usuarios`.`Password` = '" . $password . "' AND `Tbl_Empresas`.`Razon_Social` = '" . $empresa . "'";
//$query = "SELECT `Tbl_Administradores`.`Id` FROM `Tbl_Administradores` WHERE `Tbl_Administradores`.`Usuario` = '" . $usuario . "' AND `Tbl_Administradores`.`Password` = '" . $password . "'";
$resultado = mysqli_query($con, $query);
$res= mysqli_fetch_array($resultado);
if($res["Id"] > 0)
{
session_start();
$_SESSION["Id"] = $res["Id"];
$_SESSION["Empresa"] = $res["Fk_Empresa"];
$_SESSION["Usuario"] = $usuario;
$_SESSION["Tipo_Usuario"] = $res["Tipo_Usuario"];
header("Location: ../SISTEMA/");
}
else
{
header("Location: ../?error=0");
}
}
else
{
header("Location: ../?resp=error1");
}
}
else
{
header("Location: ../?error=2");
}
}
else
{
header("Location: ../?error=3");
}
?>
The code below it's my JavaSCript (JQuery) function where I call my php script.
function contactosGeneral(){
//var empresa = $('#hidden1').val();
var funcion = "contactosGeneral";
$.ajax({
url: "/PHP/PRUEBA.PHP",
type: "POST",
data: {funcion: funcion},
error: function(xhr){
window.location.href = "../REPORTES/?resp=0";
},
success: function(respuesta) {
var arreglo = JSON.parse(respuesta);
$('#p_contactos').html(arreglo[0]["resp"]);
}
});
}
this is my php script, here I call the DataBase.
<?php
$funcion = $_POST['funcion'];
switch($funcion){
case 'contactosGeneral':
break;
}
function contactosGeneral(){
require("../../ABRIR_CON.php");
//$empresa = $_POST['empresa'];
session_start();
$empresa = $_SESSION["Empresa"];
$sql = 'SELECT COUNT(`Tbl_Contactos`.`Id`) AS "resp" FROM `Tbl_Contactos` WHERE `Tbl_Contactos`.`Fk_Empresa` = ' . $empresa;
$query = mysqli_query($con, $sql);
$json = array();
while($row = mysqli_fetch_array($query))
{
$json[]=array('resp'=>$row['resp']);
}
$resources_JSON_array = json_encode($json);
echo $resources_JSON_array;
require("../../CERRAR_CON.php");
}
?>
I know there's a lot I can improve in my code, but i'm not here for that reason, just help my with my question. thanks :)
As #Barman said, I never called my php function contactosGeneral() into my switch(){} code :B

How do get php array in javascript variable

I am using following code .
<?php
$dbhost = 'localhost';
$dbuser = '****';
$dbpass = '******';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT * FROM mytable';
mysql_select_db('sujeet_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo "EMP ID :{$row['firstname']} <br> ".
"EMP NAME : {$row['lastname']} <br> ".
"EMP SALARY : {$row['doj']} <br> ".
"--------------------------------<br>";
}
echo "Fetched data successfully\n";
mysql_close($conn);
?>
to get data from db . But I want to store these data in JavaScript variable for future use. Like var users=$row; but it is not working.
You can do this by putting your mysql result in json format and print it with script tag to use it in javascript like:
<script>
var result = '<?php echo json_encode($row);?>';
</script>
you could do this by assigning inside script tag here is how.
<script>
var spge = '<?php echo json_encode($row); ?>';
alert(spge);
console.log(spge);
</script>

Alert box not showing when action from php js php

I have a problem in showing the alert box. This code for the rating star.
rating.js
$(document).ready(function(){
$('.post li').mouseout(function(){
$(this).siblings().andSelf().removeClass('selected highlight')
}).mouseover(function(){
$(this).siblings().andSelf().removeClass('selected');
$(this).prevAll().andSelf().addClass('highlight');
})
$('.post li').click(function(){
$(this).prevAll().andSelf().addClass('selected');
var parent = $(this).parent();
var oldrate = $('li.selected:last', parent).index();
parent.data('rating',(oldrate+1))
data = new Object();
data.id = parent.data('id');
data.rating = parent.data('rating')
$.ajax({
url: "add_rating.php",// path of the file
data: data,
type: "POST",
success: function(data) {
}
});
})
/* reset rating */
jQuery('.post ul').mouseout(function(){
var rating = $(this).data('rating');
if( rating > 0) {
$('li:lt('+rating+')',this).addClass('selected');
}
})
})
add_rating.php
<?php
include("dbconnection.php");
session_start();
$myid = $_SESSION['id'];
// echo "".$myid;
$sql_notification ="SELECT * FROM table_user_skills where user_id='$myid' and rating=5";
$result = $conn->query($sql_notification);
$count = 0;
while ($row=$result->fetch_assoc()) {
if ($row['rating']==5) {
$count = $count +1;
}
}
// echo "Count: ".$count;
if(!empty($_POST["rating"]) && !empty($_POST["id"])) {
$myrate=$_POST["rating"];
if($count<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Less than 5");';
print '</script>';
} else if($myrate<5){
$query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' where rating_id='".$_POST['id']."'";
$result = $conn->query($query);
print '<script type="text/javascript">';
print 'alert("Rate Less than 5");';
print '</script>';
}else if($count>5){
print '<script type="text/javascript">';
print 'alert("Lpas 5 stars");';
print '</script>';
}
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE skills_id='" . $_POST["skills_id"] . "'";
// $query ="UPDATE table_user_skills SET rating='" . $_POST["rating"] . "' WHERE user_id='" . $_POST["userid"] . "' and skills_id='" . $_POST["id"] . "' and category_id='" . $_POST["category"] . "'";
}
?>
My problem is that the alert box is not showing. I have to limit the number of 5 stars being updated. If anyone could help me figure out what's wrong with my code, I would appreciate it.
Look at the success callback function for your AJAX call - it's empty. You're having PHP print out the alert box code in the ajax call and then never doing anything with that output.
To make the alert show up, you would have to append the code your AJAX call returns to the DOM. However, it would probably be better to just return just the message and let the JavaScript code take care of raising the alert box. Just a simple alert(data) should do the trick.

increment a field manually in database using jquery and php [duplicate]

This question already has answers here:
When to use single quotes, double quotes, and backticks in MySQL
(13 answers)
Closed 7 years ago.
I am trying to build a click button that increments value of the item in the database. I am using UPDATE method for this.
The problem is that whenever the update query is run, the value it takes from the databse to increment (or decrement) is zero. (0+1 = 1, 0-1 = -1)
require_once("C:/xampp/htdocs/Selfie/database/dbcontroller.php");
$db_handle = new DBController();
$image_id = $_POST["image_id"];
$active_user_id = $_POST["active_user_id"];
$query = "SELECT user_image_id from users where user_id='" . $active_user_id . "'";
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
if ($row['user_image_id'] == $image_id) {
echo "own image";
}
else
{
$query = "SELECT image_id from hearts where user_id='" . $active_user_id . "'";
$result = mysql_query($query);
if ($row = mysql_fetch_assoc($result)) {
if ($row['image_id'] == $image_id) {
$query = "UPDATE images SET image_hearts='image_hearts'-1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "DELETE FROM hearts WHERE user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE users SET user_like ='' where user_id=" . $active_user_id;
$result = mysql_query($query);
echo "just unlike";
}
else
{
$query = "DELETE FROM hearts WHERE user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'-1 where image_id=" . $row['user_image_id'];
$result = mysql_query($query);
$query = "Select image_path from images where image_id=" . $image_id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query = "UPDATE users SET user_like ='" . $row["image_path"] . " where user_id=" . $active_user_id;
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'+1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "INSERT INTO hearts (image_id , user_id) VALUES ('$image_id','$active_user_id')";
$result = mysql_query($query);
echo "unlike then like";
}
}
else
{
$query = "INSERT INTO hearts (image_id , user_id) VALUES ('$image_id','$active_user_id')";
$result = mysql_query($query);
$query = "UPDATE images SET image_hearts='image_hearts'+1 where image_id=" . $image_id;
$result = mysql_query($query);
$query = "Select image_path from images where image_id=" . $image_id;
$result = mysql_query($query);
$row = mysql_fetch_assoc($result);
$query = "UPDATE users SET user_like ='" . $row["image_path"] . "' where user_id=" . $active_user_id;
$result = mysql_query($query);
echo "image liked successfully.";
}
}
This is my jQuery code:
function test_click(i_image_id, i_heart_id, i_active_user_id) {
var active_user_id = i_active_user_id;
var image_id = i_image_id;
var heart_id = i_heart_id;
jQuery.ajax({
url: "../Selfie/validations/add_like.php",
data: {
active_user_id: active_user_id,
image_id: image_id
},
type: "POST",
success: function(data) {
if (data == "own image")
{
alert('You are trying to like your own image You NARCISSIST');
}
else if (data == "just unlike")
{
$("*").removeClass("btn-heart-red animated bounce fa-heart-red");
alert('just unlike');
}
else
{
$("*").removeClass("btn-heart-red animated bounce fa-heart-red");
$("#" + heart_id).removeClass("animated rubberBand");
$("#" + heart_id).toggleClass("btn-heart-red animated bounce fa-heart-red");
}
alert(data);
}
});
}
This image_hearts='image_hearts'+1 remove the quotes; that's a column you're wanting to update and not the string literal. The same thing goes for 'image_hearts'-1
Check for errors on your queries, which would have helped you here.
http://php.net/manual/en/function.mysql-error.php
Plus, your present code is open to SQL injection. Use mysqli with prepared statements, or PDO with prepared statements.
mysql_* functions deprecation notice:
http://www.php.net/manual/en/intro.mysql.php
This extension is deprecated as of PHP 5.5.0 and removed as of PHP 7.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used. See also the MySQL API Overview for further help while choosing a MySQL API.
These functions allow you to access MySQL database servers. More information about MySQL can be found at » http://www.mysql.com/.
Documentation for MySQL can be found at » http://dev.mysql.com/doc/.
Footnotes:
If I may quote Marc's comment:
"in other words. 'image_hearts' + 1 is string literal plus integer, and unless that string literal contains digits at the start of it, will simply become 0 + 1 – Marc B"

TinyMCE's style="" breaks JSON

I currently have PHP code that fetches some html from the database, it then passes this as JSON to jquery which parses the JSON. Until that moment all is good. However, if you then change some styles in TinyMCE it attaches this as style to the element. (E.g. <h1 style="font-weight:bold">)
Next time the script tries to retrieve this, the JSON doesn't parse, because of the double apostrophes. Is there any way to make TinyMCE not use double apostrophes?
EDIT WITH SOME ACTUAL CODE
PHP Storer:
$conn = mysql_connect($row['ipdb'],$row['usernamedb'], $row['wwdb']) or die("err");
$db = mysql_select_db($row['usernamedb']) or die("err");
$id = $_POST['id'];
$column = $_POST['column'];
$page = $_POST['page'];
$value = $_POST['value'];
$qry = "UPDATE ".$page." SET ".$column."='$value' WHERE id='$id'";
$result = mysql_query($qry) or die("An error occurred ".mysql_error());
PHP Fetcher:
$conn = mysql_connect($row['ipdb'],$row['usernamedb'], $row['wwdb']) or die("err");
$db = mysql_select_db($row['usernamedb']) or die("err");
$identifier = $_POST['identifier'];
$page = $_POST['page'];
$qry = "SELECT id, textnl, texten FROM ".$page." WHERE identifier='$identifier'";
$result = mysql_query($qry) or die("An error occurred ".mysql_error());
$obj = mysql_fetch_object($result);
$textnl = $obj->textnl;
$texten = $obj->texten;
$id = $obj->id;
echo '{ "textnl" : "' . $textnl . '", "texten" : "' . $texten . '", "id" : "' . $id . '" }';
Try to use stripslashes http://www.php.net/manual/es/function.stripslashes.php. Maybe can help you.

Categories