Why AJAX is returning duplicated data? - javascript

So, what im doing is searching for records stored in a database using AJAX, but when it prints the callback data, the first record is duplicated:
My code:
$gUser = $_GET['q'];
$connect = mysql_connect("localhost", "root", "") or die("Could not connect to the server");
mysql_select_db("socialj") or die("Could not connect to the database");
$result = mysql_query("SELECT fullname, email FROM users WHERE fullname LIKE '%$gUser%' ");
while($array[] = mysql_fetch_array ($result))
{
foreach($array as $r)
{
echo $r['fullname'].' | '.$r['email'].'<br>';
}
}
?>
JavaScript Code:
$(document).ready(function (){
$('#searchh').on('submit', function (e){
e.preventDefault();
var sVal = $('#search').val();
$.ajax({
type: 'get',
url: 'profile.php',
data: {q : sVal},
success: function (data) {
alert(data);
}
});
});
});
Could you guys help me? I don't know whats happening... Thanks.

Replace this
while($array[] = mysql_fetch_array($result)) {
foreach($array as $r) {
echo $r['fullname'] . ' | ' . $r['email'] . '<br>';
}
}
with this
while($row = mysql_fetch_array($result)) {
echo $row['fullname'] . ' | ' . $row['email'] . '<br>';
}

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

Issue with ODBC PDO and Ajax

I'm working on a project for work, and I've run into some issues.
I'm creating dynamic elements based on PDO queries and ajax, and I've searched and searched to resolve my specific issue. Basically, I have two select boxes that are dynamically added from a database response, and regardless of which option is selected, all of the dynamically created buttons are made exactly the same. Selected Rack_G
I've also created timers for each Rack/Tray, and the same issue arises for the timers. There is only a record for Rack H Tray 8.Rack H Tray 8
My db_connect.php
$first = "odbc:TIMERODBC";
$user = "exampleuser";
$pass = "examplepass";
$pdo = new PDO($first,$user,$pass);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Below is my class.db.php file that queries my database
public function selectOven()
{
try{
$stmt = $this->conn->query("SELECT sub.equipName FROM STR_EquipSubCategory sub LEFT JOIN STR_EquipCategory category ON category.categoryID = sub.categoryID GROUP BY sub.equipName");
$data = $stmt->fetchAll();
foreach($data as $row)
{
echo "<option value=" . $row['equipName'] . "><strong>" . $row["equipName"] . "</strong></option>";
}
}
catch(PDOException $e) {
return $e->getMessage();
}
}
public function selectRack($oven) {
try{
$sth = $this->conn->prepare('SELECT storageBayName FROM STR_EquipSubCategory WHERE equipName =:oven');
$sth->bindParam(':oven',$oven,PDO::PARAM_STR);
$sth->execute();
$data = $sth->fetchAll();
echo "<select id='rack' class='custom-select mb-2'>Rack";
echo "<option value ='Select Rack'></option>";
foreach($data as $row)
{
echo "<option id=".$row['storageBayName']." value=". $row["storageBayName"] . ">". $row["storageBayName"] . "</option>";
}
echo "<select>";
}
catch(PDOException $e) {
return $e->getMessage();
}
}
public function selectRackTray($oven,$rack) {
try{
$sth = $this->conn->prepare("EXECUTE STR_GetTimerOpenTraysSp ?, ?");
$sth->bindParam(1,$oven,PDO::PARAM_STR);
$sth->bindParam(2,$rack,PDO::PARAM_STR);
$sth->execute();
$data = $sth->fetchAll();
foreach($data as $row)
{
if(($row['material'] != 0) ) {
echo "<div class='row'>";
echo "<button type='button' id='tray".$row['storageBayName']." ". $row['sublevelID'] ."' class='btn btn-danger' data-toggle='popover'>Tray " .$row['sublevelID'] . "</button>";
echo "</div>";
}
else {
echo "<div class='row'>";
echo "<button type='button' id='emptyTray".$row['storageBayName']. " ".$row['sublevelID'] ."' class='btn btn-success'>Tray " .$row['sublevelID'] . "</button>";
echo "</div>";
}
}
}
catch(PDOException $e) {
return $e->getMessage();
}
}
And now my ajax jQuery & Ajax
$(document).ready(function(){
$("select#oven").change(function(){
var selectedOven = $("#oven option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { oven : selectedOven }
}).done(function(data){
$("#rackResponse").html(data);
});
});
});
$(document).on('change', "select#rack", function() {
var selectedRack = ($(this).val());
var selectedOven = ($("#oven option:selected").text());
$.ajax({
type: "POST",
url: "process-a-request.php",
data:
{
rack: selectedRack,
oven: selectedOven
},
}).done(function(data){
$("#tResponse").html(data);
});
});
If anyone can help me out, I would greatly appreciate it. Note, I'm not super experienced with PHP, but everything else seems to be working correctly.
My problem wasn't with ajax, php, or the PDO statements. I ran some tests on my stored procedure that I was calling, and found the problem there. Thanks for attempting to help me out.

parse return data from html to ajax

I have some problem with the returned value of ajax.
this is the ajax code:
$(document).ready(function() {
var request;
$("#flog").submit(function(event) {
if(request)
request.abort();
event.preventDefault();
var form = $(this);
var serializedData = form.serialize();
var btnname = $('#log').attr('name');
var btnval = $('#log').val();
var btn = '&'+btnname+'='+btnval;
serializedData += btn;
request = $.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: serializedData,
});
request.done(function(data, status, jdXHR) {
alert(data);
});
request.fail(function(jdXHR, status, error) {
});
});
});
it takes data from a form and send it to another page.
this is the second page:
<?php include 'head.php'; ?>
<?php
if($_POST['login']) {
session_regenerate_id(true);
$con = mysqli_connect("localhost", "Alessandro", "ciao", "freetime")
or die('Could not connect: ' . mysqli_error($con));
$query = 'SELECT * FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
if(mysqli_num_rows($result) == 0) {
mysqli_close($con);
session_unset();
session_destroy();
$res = false;
return $res;
}
$query = 'SELECT password FROM users WHERE username="' . $_POST['user'] . '"';
$result = mysqli_query($con, $query) or die('Query failed: ' . mysqli_error($con));
$line = mysqli_fetch_array($result, MYSQL_ASSOC);
if(md5($_POST['password']) != $line['password']) {
mysqli_close($con);
session_unset();
session_destroy();
return false;
}
?>
<?php include 'foot.php'; ?>
and in .done the returned data is all the html page.
How can I retrieve only a data, like $res? I tried with json_encode() but with no results.
If in the second page I delete the lines include 'head.php' and include 'foot.php' it works. But I need that the secon page is html, too.
Somenone can help me?
Dont use the Data attribute from AJAX.
Replace
request.done(function(data, status, jdXHR) {
alert(data);
});
with
request.done(function(data, status, jdXHR) {
alert(jdXHR.responseText);
});
You could do it in a much simpler way.
In PHP store the result of the attempted login into a variable, for instance $result =0; to start with
If the login is valid change it to 1 and return it to ajax by doing an echo at the end of your PHP file. If you need other value returned such as the name you could add it to the variable with a separator such as || for instance.
in javascript collect your return and go data = data.split('||');
if (data[0] == 0){alert("Welcome back " + data[1]);}else{alert("wrong login...")}
Previous use is correct, you need to escape the user collected in your PHP script.
Hope this helps.

Creating jQuery array variable and Transferring array to another page PHP

I currently have this function exactly how I want it except for the jQuery at the bottom in which I am only alerting and not creating a real variable. It all works but I am stuck on how I can take all of the data from the jQuery script and then make it into a variable so that I can bring it to another page? Any ideas, NEED HELP!
function getGrade($id, $grades_array) {
$counter = 0;
$sql = "Select grade FROM grades";
$result = mysql_query($sql) or die (mysql_error());
echo '<select name="grades_selected" multiple="multiple" id="grades_selected">';
while ($row = mysql_fetch_array($result)) {
if ($row['grade'] != $grades_array[$counter]) {
echo "<option>" . $row['grade'] . "</option>";
} else {
echo "<option selected=" . $row['grade'] . ">" . $row['grade'] . "</option>";
$counter = $counter + 1;
}
}
mysql_free_result($result);
echo '</select>';
$_SESSION['test'] = $grades_array;
?>
<script>
$(document).ready(function() {
$('#grades_selected').change(function() {
alert($(this).val());
});
});
</script>
<?
}
You need to use ajax within on change function:
$(document).ready(function() {
$('#grades_selected').change(function() {
var variable = $(this).val();
$.ajax({
type: 'post',
url: 'target_page.php',
data: {variable : variable},
success: function (res) {
alert(res);
}
});
});
});
On target_page.php:
echo $_POST['variable'];

Textbox and AJAX data from mySQL

Hello I have a textbox and when I type something in it should update the page with the mySQL data via AJAX.
So Im trying to get live updated database results whenever you type something in the textbox. The goal is to get a textbox that is getting data from the mySQL database.
I have written the code so far, hopefully someone can advise me in this mather, thank you.
$select = 'SELECT *';
$from = ' FROM overboekingen';
$where2 = ' WHERE naam_klant LIKE % . $val . % ';
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
$val = (isset($_POST['txt']) ? $_POST['txt'] : FALSE);
if (is_array($opts) || $val) {
$where = ' WHERE FALSE';
if (in_array("naam_klant", $val)){
$where2.val;
}
}
else {
$where = false;
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
AJAX
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
You must define the PHP $val variable before.
The correct sytax:
$where2 = " WHERE naam_klant LIKE %$val% ";

Categories