Issue
I have an onclick Jquery function that will return the value in the first cell of the clicked table row. I then try to pass this value using ajax type: 'POST' to a php script that will then execute a database query using this value for comparison. For some reason, $_POST is always empty. The ajax is not returning any errors but i'm unable to receive the value of the array on server-side. Any help is appreciated.
jQuery
$('tr.profileTableClick').click(function() {
var tableData = $(this).find('td:nth-child(1)').map(function() {
return $(this).text();
}).get();
$.ajax({
url: 'selectAnswers.php',
type: 'POST',
data: {
'id': tableData
},
dataType: 'text',
error: function() {
console.log('Error in ajax request');
},
success: function(data) {
console.log('Success of ajax request');
console.log(data);
}
});
PHP
Here is the selectAnswers.php file:
<?php
$id = $_POST['id'][0];
try {
$conn = new PDO(
"mysql:host=$servername;dbname=$dbname",
$username,
$password
);
$conn->setAttribute(
PDO::ATTR_ERRMODE,
PDO::ERRMODE_EXCEPTION
);
$stmt = $conn->prepare(
"SELECT
quality_of_service,
self_improvement,
personal_behavior,
organization_rules_commitment,
team_work,
appearance, work_with_high_responsibility,
loyalty_to_organization,
punctuality_on_work,
office_maintaining, areas_of_improvement,
points_of_weakness,
points_of_strength
FROM appraisals_table
WHERE Apr_Id = :id"
);
$stmt->bindValue(
':id',
$id,
PDO::PARAM_INT
);
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$ans1 = $row['quality_of_service'];
$ans2 = $row['self_improvement'];
$ans3 = $row['personal_behavior'];
$ans4 = $row['organization_rules_commitment'];
$ans5 = $row['team_work'];
$ans6 = $row['appearance'];
$ans7 = $row['work_with_high_responsibility'];
$ans8 = $row['loyalty_to_organization'];
$ans9 = $row['punctuality_on_work'];
$ans10 = $row['office_maintaining'];
$ans11 = $row['areas_of_improvement'];
$ans12 = $row['points_of_weakness'];
$ans13 = $row['points_of_strength'];
}
} catch(PDOException $e) {
echo 'Error: '. $e->getMessage();
}
$conn = null;
Change either js:
var tableData = $(this).find("td:nth-child(1)").text();
or the php:
$id = (int)$_POST['id'][0]
Use the new javascript's FormData API like so. . .
var formdata = new FormData();
formdata.append('id', tableData);
$.ajax({
url: 'selectAnswers.php',
type: 'POST',
data: formdata,
dataType: 'text',
error: function(){
console.log("Error in ajax request");
},
success: function(data) {
console.log("Success of ajax request");
console.log(data);
}
});
Related
Im trying to insert data into my database with AJAX but dont working.
I can verify that im connected to the database but when i click it doesnt insert the data. thanks
with a click function i take the 2 parameter that i wanna insert in my database.
$( "#q_answer1" ).click(function () {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "server.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no
},
success: function(){
$("#q_no").val('');
$("#total_no").val('');
}
});
});
And here is the php file, first connect to the ddbb and insert the 2 values with the mysql_query.
<?php
include("dbh.php");
if (isset($_POST['done'])) {
$q_no = mysql_escape_string($_POST['username']);
$total_no = mysql_escape_string($_POST['comment']);
mysql_query("INSERT INTO variables(id, names) VALUES('{$q_no}', '{$total_no}')");
exit();
}
?>
html is like this:
<div id="total_no">1</div>
<div id="q_answer1" class="btn left_b">yes</div>
I think you should use PDO, to connect to the database instead of the old driver, which PHP no longer supports. with PDO you can use prepared statements to prevent sql injections
PDO tutorial
filter_var() Constants
dbh.php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = 'db';
try {
$db = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
// set the PDO error mode to exception
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}
catch(PDOException $e)
{
exit($e->getMessage());
}
?>
serve.php
<?php
include("dbh.php");
if (isset($_POST['done'])) {
$q_no = filter_var($_POST['username'], FILTER_SANITIZE_STRING);
$total_no = filter_var($_POST['comment'], FILTER_SANITIZE_STRING);
try {
$stmt = $db->prepare("INSERT INTO variables(id, names) VALUES(?, ?)");
$stmt->execute(array($q_no, $total_no));
echo json_encode(["message" => "success"]); // sends success response to front-end
} catch (\Exception $e) {
echo json_encode(["message" => $e->getMessage() ]); // sends error response to front-end
}
}
?>
in your ajax check if the data was inserted or not.
$("#q_answer1").click(function() {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "file.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no
},
success: function(data) {
const respose = JSON.parse(data);
if (respose.message === 'success') { // data was inserted
$("#q_no").val('');
$("#total_no").val('');
}else {
alert(respose.message); // some error has occured
}
}
});
});
You have to take value of div as mentioned below,
var q_no = $("#q_no").text();
var main_no = $("#total_no").text();
Pass data in key-value Pair, After pass first key-value data concate other data with & sign key.
$( "#q_answer1" ).click(function () {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "server.php",
type: "post",
async: false,
data: 'done=' + 1 + '&username=' + q_no + '&comment=' + main_no,
success: function(){
$("#q_no").val('');
$("#total_no").val('');
}
});
});
You can't use val() on div. Try using text() and then check if your server.php is getting these value.
Thanks
You have typo error in jquery
$qAnswer1.click(function () {
Should be
$('#q_answer1').click(function () {
You can try following to test
$( "#q_answer1" ).click(function() {
alert( "Handler for .click() called." );
});
Include the jquery at the top of your page
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Full working code
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="total_no">1</div>
<div id="q_answer1" class="btn left_b">yes</div>
<script type="text/javascript">
$( "#q_answer1" ).click(function () {
var q_no = $("#q_no").val();
var main_no = $("#total_no").val();
$.ajax({
url: "ajax.php",
type: "post",
async: false,
data: {
"done": 1,
"username": q_no,
"comment": main_no
},
success: function(){
$("#q_no").val('');
$("#total_no").val('');
}
});
});
</script>
in your PHP file try to print $_POST to see its working.
I am trying to login with ajax. The script is working well and I am getting logged in but I am not getting redirected to the dashboard.php file. Codes are given below. Please try to help me out.
Ajax call
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
};
$.ajax({
type: "POST",
url: "login-process.php",
data: dataString,
cache: true,
beforeSend: function(){
$('#loading-image').show();
},
complete: function(){
$('#loading-image').hide();
},
success: function(html){
$('.message').html(html).fadeIn(500);
}
});
return false;
});
});
</script>
login-process.php
<?php
include'config/db.php';
$msg = null;
$date = date('Y-m-d H:i:s');
$uname = (!empty($_POST['username']))?$_POST['username']:null;
$pass = (!empty($_POST['password']))?$_POST['password']:null;
if($_POST){
$stmt = "SELECT * FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':uname', $uname);
$stmt->execute();
$checklgn = $stmt->rowCount();
$fetch = $stmt->fetch();
if($checklgn > 0){
if(password_verify($pass, $fetch['mem_pass'])){
session_start();
$_SESSION['sanlogin'] = $fetch['mem_id'];
$msg = "<div class='message-success'>Access Granted! Please wait...</div>";
$go_login = header("refresh:2; url=dashboard.php");
}else{
$msg = "<div class='message-error'>Password mismatch. Please try again!</div>";
}
}else{
$msg = "<div class='message-error'>User not found. Please try again!</div>";
}
}
echo $msg;
echo $go_login;
?>
If you use AJAX to log in, you must use javascript to redirect. Redirecting PHP will only result in the AJAX call being redirected which doesn't produce the desired result.
In your success clause of the ajax request you can add window.location.replace("dashboard.php");
In you ajax success:
use window.location.href="/uri/to/redirect";
setTimeout(function(){
window.location.href="/uri/to/redirect";
},2000);
You cannot use header PHP function in this situation.
You should redirect in your $.ajax function like this:
1) You should return JSON in your login-process.php:
...
$result = array();
if($_POST){
$stmt = "SELECT * FROM members WHERE mem_uname = :uname";
$stmt = $pdo->prepare($stmt);
$stmt->bindValue(':uname', $uname);
$stmt->execute();
$checklgn = $stmt->rowCount();
$fetch = $stmt->fetch();
if($checklgn > 0){
if(password_verify($pass, $fetch['mem_pass'])){
session_start();
$_SESSION['sanlogin'] = $fetch['mem_id'];
$result = array(
'msg' => "<div class='message-success'>Access Granted! Please wait...</div>",
'redirect' => 'dashboard.php',
);
}else{
$result = array(
'msg' => "<div class='message-error'>Password mismatch. Please try again!</div>",
);
}
}else{
$result = array(
'msg' => "<div class='message-error'>User not found. Please try again!</div>",
);
}
}
echo json_encode($result);
exit;
2) You should add parameter dataType into your $.ajax call and process attribute redirect of the server answer (if this attribute exists):
$(document).ready(function () {
$("#submit").click(function () {
var dataString = {
username: $("#username").val(),
password: $("#password").val(),
};
$.ajax({
dataType: 'json', // <-- set expected dataType here
type: "POST",
url: "login-process.php",
data: dataString,
cache: true,
beforeSend: function () {
$('#loading-image').show();
},
complete: function () {
$('#loading-image').hide();
},
success: function (data) {
$('.message').html(data.message).fadeIn(500);
// if we have attribute "redirect" in answer
if(typeof data.redirect !== 'undefined'){
// redirect here after 2 seconds
setTimeout(function(){
document.location.href = data.redirect;
},2000);
}
}
});
return false;
});
});
My question is how to get an db information (in my case points just a number) from the php file to the jquery ajax script so here is my jquery:
function rate_down(id) {
var id = id;
//submit data to php script
var data = {
"id": id,
};
$.ajax({
type: "POST",
url: "rating.php",
data: data,
success: function(response) {
var currentValue = /* here i want to put the db number */
var newValue = +currentValue - 1;
$("#points_"+id).text(newValue);
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
};
And I want my raiting.php. I'm not sure if I should post it because its useless but here is my mysql query in raiting.php:
$pic_id = (int) $_REQUEST['id'];
mysql_query = mysql_query"SELECT points FROM `photos` WHERE `id` = '$pic_id'";
Problem is in your php script. Please dont use mysql_query. Use PDO.
$pic_id = (int) $_REQUEST['id'];
$db = new PDO("...");
$q = $db->prepare("SELECT points FROM `photos` WHERE `id` = :pic_id");
$q->bindValue(':pic_id', $pic_id);
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$points = $check['points'];
}else{
$points = 0;
}
echo $points;
And then in your ajax function:
$.ajax({
type: "POST",
url: "rating.php",
data: data,
success: function(response) {
if(response != 0) {
var currentValue = response;
var newValue = +currentValue - 1;
$("#points_"+id).text(newValue);
}
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
I'm making an AJAX call to a fairly simple PHP function. The response should be a JSON object to be manipulated, but my response is always an empty object.
Relevant Code:
index.html's AJAX Call:
$( function() {
$('#dates').on('submit', function (e) {
var start_time = new Date().getTime();
e.preventDefault();
var submitData = $('#dates').serialize();
console.log(submitData);
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
dataType: 'json',
beforeSend: function(){
$('#loading').show();
},
success: function(data) {
console.log(data);
$('#loading').hide();
},
error:function(xhr, desc, err){
alert('You tried to send an AJAX request, but something went wrong.\n Please Contact the NASR WebDev Team');
console.log(xhr);
console.log("Details: " + desc +"\nError: "+ err);
}
});
});
});
inflow.php's array creation and echo:
<?php
$msqlStart = $_POST['start_date'];
$msqlEnd = $_POST['end_date'];
$inflowQuery=
"SELECT
COUNT,
QUEUE_ID,
QUEUE_GROUP,
INFLOW_DATE,
LINE_OF_BUSINESS
FROM
ticket_inflow.inflow
WHERE
ROUTE_STATUS = 'Inflow'
AND inflow_date between ? and ?";
$connect = new mysqli($host, $user, $password, $database);
if ($connect->connect_error){
die("Failed to Connect:.".$connect->connect_errno.": ".$connect->connect_error);
}
if(!($statment = $connect->prepare($inflowQuery))){
die('Error in Preparation Error Number:%d Error: %s');
}
if(!$statment->bind_param('ss', $msqlStart, $msqlEnd)){
die ('Error in Binding');
}
if(!$statment->execute()){
die('Error In Execution');
}
$statment->bind_result($inflowCount, $inflowQueue, $inflowQG, $inflowDate, $inflowLOB);
$a_json = array();
$jsonRow = array();
While($statment->fetch()){
$UID = 0;
$jsonRow['UID'] = $UID++;
$jsonRow['count'] = utf8_encode($inflowCount);
$jsonRow['inflow_date'] = utf8_encode($inflowDate);
$jsonRow['queue'] = utf8_encode($inflowQueue);
$jsonRow['queue_group'] = utf8_encode($inflowQG);
$jsonRow['lob'] = utf8_encode($inflowLOB);
array_push($a_json, $jsonRow);
}
$jsonReturn = json_encode($a_json);
echo $jsonReturn;
?>
If I go directly to inflow.php and pass it parameter's identical to what the page passes it, I get what appears to be a nice JSON object, however when I look at the response Chrome Developer's Tools I get:
[]
And nothing more.
You are sending form data, not json;
$.ajax({
type:'POST',
url:'inflow.php',
data:$('#dates').serialize(),
//contentType: "application/json",<-- remove this
dataType: 'json',
Background
I have a web application which displays "simple" information about an account, i.e. Name and account Number.... I have a button on the side to display "detailed" information... i.e Name, Acct# and Phone#.
The system needs to pull the information dynamically upon clicking this button, and will populate into specified div's... What am I doing wrong in this case, because I am constantly receiving the alert with "Error Loading Information". Edit: -Changed error alert to alert(textStatus) - Now all I have is "error" in the alert box....
JS/Ajax
$('.view_information').click(function(e) {
//On Clicking the function, dynamically load the data for the viewing
var dataObj = {};
dataObj["id"] = $(this).data('id');
dataObj["action"] = "get"; // "get" or "set"
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
data: dataObj,
dataType: 'json',
success: function(data){
/* Doesn't Work....*/
$('.view_id').html(data.id);
$('.view_name').html(data.name);
$('.view_account').html(data.account);
$('.view_phone').html(data.phone);
/*Also Doesn't work...
$('.view_id').html(data.message['id']);
$('.view_name').html(data.message['name']);
$('.view_account').html(data.message['account']);
$('.view_phone').html(data.message['phone']);*/
},
error: function(jqXHR, textStatus, errorThrown){
// alert('Error Loading Information');
alert(textStatus);
}
});
JSON
<?php
include_once('customer.class.php');
$customer = new Customer();
$query = "SELECT * FROM table WHERE id=$id LIMIT 1"; //expecting one row
try {
$result = $customer->runQuery($query); //class function with fetchAll
} catch (Exception $e) {
echo "Error: " . $e->getMessage();
}
$message = array(
'id' => $id,
'name' => $result[0]['agency_name'],
'account' => $result[0]['account_number'],
'phone' => $result[0]['phone']
);
}
print json_encode($message);
?>
It appears I was able to fix the syntax to get it operable.... Had to do with passing the array into json to execute.
I changed the JS/AJAX to:
/* Old Variable Definitions
//var dataObj = {};
//dataObj["id"] = $(this).data('id');
//dataObject["column"] = $(this).data('column');
//dataObj["action"] = "get"; // "get" or "set"*/
/* New Syntax: */
var data_id = $(this).data('id');
var data_action = "get";
var column_toact_on = $(this).data('column');
$.ajax({
url: 'view_agency_info.php',
type: 'POST',
//data: dataObj, // OLD array
data: {id : data_id, action: data_action, column: column_toact_on},
dataType: 'json',
success: function(data){
alert("Wooptee Doo Basil!");}