Error when JSON array is echoed back to AJAX script - php

I have a text box where I search database for a specific information.
The PHP code when I just type and click on search is the following:
try
{
$date_emp = $_POST['date_emp'];
$val = $_POST['data1'];
$gender = $_POST['gen'];
if($date_emp == "choose" && $gender == "specify")
{
$search = "SELECT * FROM employee
WHERE emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
And here the AJAX script for it:
$("#search").click(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
//console.log(txt);
if(txt == '' && drop == "choose" && gender == "specify")
{
$("#txtSearch").css('border-color', 'red');
}
else
{
if(drop == "choose" && gender == "specify")
{
$.ajax
({
url: 'search.php',
type: 'POST',
data: {data1: txt, date_emp: drop, gen: gender},
dataType: 'JSON',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Something Wrong");
}
});
}
$("#date_employed, #sex").change(function()
{
var txt = $("#txtSearch").val();
var drop = $("#date_employed").val();
var gender = $("#sex").val();
$.ajax({
url: 'search.php',
type: 'post',
data: {data1: txt, date_emp: drop, gen: gender},
datatype: 'json',
success:function(res)
{
$("#myTable tr").remove();
$("#myTable").append("<tr><th>Name</th><th>Position</th><th>Salary</th><th>Date</th><th>Gender</th></tr>");
$.each( res, function(key, row){
$("#myTable").append("<tr><td>"+row['emp_name']+"</td><td>"+row['position']+"</td><td>"+row['salary']+"</td><td>"+row['date_employed']+"</td><td>"+row['gender']+"</td></tr>");
});
},
error:function(res)
{
alert("Couldn't find any data!");
}
});
});
}
});
WHERE gender and drop are 2 drop lists that forming a search filters
When I change one of the drop lists, per example, when I choose the date equal to: this week I should see in table 2 rows.
But I can only see them in the network (in devTool), and at console tab I see the following error:
Uncaught TypeError: Cannot use 'in' operator to search for 'length' in
[{"id":"48","0":"48","emp_name":"Alexa","1":"Alexa","position":"Secretary","2":"Secretary","salary":"8000","3":"8000","date_employed":"2016-02-23","4":"2016-02-23","gender":"female","5":"female"}]
The PHP code when I change drop lists is:
if($date_emp == "week" && $gender == "specify")
{
$search = "SELECT * FROM employee WHERE (emp_name = :val OR position = :val
OR salary = :val OR date_employed = :val
OR gender = :val) AND date_employed > DATE_SUB(NOW(), INTERVAL 1 WEEK)";
$searchStmt = $conn->prepare($search);
$searchStmt->bindValue(":val", $val);
$searchStmt->execute();
$res = $searchStmt->fetchAll();
echo json_encode($res);
}

When you make an ajax call and expect the response to be a json you need to send a json header from the PHP
header('Content-Type: application/json');
echo json_encode($data);
Sending the json header from the PHP will turn the "res" param in your ajax to a json object and not a json string.
If you don't send the the header you need to parse the json string into a json object
var json = JSON.parse(res);

Related

Data missing when sent via AJAX

I want to send two values to my PHP script that is being called from an AJAX request. Somehow my data is not being passed to the PHP script.
Maybe I am doing something wrong somewhere. Can I have some insight?
$(function() {
$(".delbutton").click(function() {
var viewed_comments = $("#viewed_comments").val();
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
var comments = 'comm=' + viewed_comments;
var tr = $(this).closest('tr');
if (confirm("Are you sure to mark this as viewed?")) {
$.ajax({
type : "POST",
url : "update_entry.php",
dataType: "json",
data: {info:info, comments:comments },
success : function(response) {
if(response=="updation success"){
console.log('inside');
}
}
});
}
return false;
});
});
And my PHP where the AJAX request is going,
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
$level_code = $_SESSION['level_code'];
$action = 'view';
$viewed_date = date("Y-m-d");
$viewed_by = $_SESSION['session_admin_id'] ;
if($action == 'view')
{
$viewed_date = date('Y-m-d h:i:s');
$nots = $db->idToField("tbl_table","notes",$id);
if ($nots == "")
{
$date_string = "last viewed on|".$viewed_date."|" ;
}
else {
$date_string = $nots."last viewed on|".$viewed_date."|" ;
}
$fnc->update_is_viewed_for("tbl_table",$id, "$viewed_date", $viewed_by);
$notes_data = array("notes"=>$date_string,"viewed_comments"=>$viewed_comments);
$db->query_update("tbl_table", $notes_data, "id=$id");
}
if($db->query_update("tbl_table", $notes_data, "id=$id")){
http_response_code();
echo json_encode('updation success');
}else{
http_response_code(204);
}
Isn't it a name thing? You send two POST variables:
data: {
info: info,
comments: comments
},
but you retrieve them with different names:
$id = $_POST['id'];
$viewed_comments = $_POST['comm'];
What do you get if you var_dump($_POST);?
Use seriliaze form values it will solve your data missing problem, change #frm to your form id
$(document).ready(function(){
$('#frm').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"update_entry.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if (data == 'updation success') {
console.log('success');
}
}
});
});
});

PHP 'Insert Into' Query Returning error result on Ajax

I php code that will insert into database but it always returns false even if it is inserting values into the database.
Here is my code: PHP
<?php
require_once 'connection.php';
if (isset($_POST['borrowBook']))
{
newBorrowRequest();
}
function newBorrowRequest()
{
$b_id = $GLOBALS['db']->real_escape_string($_POST['b_id']);
$userID = $GLOBALS['db']->real_escape_string($_POST['userID']);
$dateBorrowed = $GLOBALS['db']->real_escape_string($_POST['dateBorrowed']);
$remarks = $GLOBALS['db']->real_escape_string($_POST['remarks']);
$sql = "INSERT INTO `tbl_requestbook`(`b_id`, `userID`, `dateBorrowed`, `remarks`) VALUES ('$b_id','$userID','$dateBorrowed','$remarks')";
if($GLOBALS['db']->query($sql))
{
$GLOBALS['db']->close();
header("location:../../admin/Book-Items.php?r=success", true);
}
else
{
header("location:../../admin/Book-Items.php?r=failed", true);
}
}
>?
And here is my Ajax Code:
<script>
$("#borrowBook").click(function(event) {
var bookID = $("#bookBorrow").val();
var userID = $("#borrowBook").val();
var d = new Date();
var month = d.getMonth()+1;
var day = d.getDate();
var output = d.getFullYear() + '/' +
(month<10 ? '0' : '') + month + '/' +
(day<10 ? '0' : '') + day;
$.ajax({
url: '../assets/php/functions-book.php',
type: 'POST',
data: {borrowBook: 'true', b_id: bookID, userID: userID, dateBorrowed: output, remarks: $("#remarks").val() },
success: function(result) {
window.location.reload();
},
error: function(result) {
//window.location.reload();
console.log(result);
}
});
});
</script
There is something wrong with the php query, it will not iterate with the condition thus, it will call the ajax error function.
[EDITED]
I solved this by changing 'header("location:../../admin/Book-Item.php?r=success");' to 'header("location:../../admin/Book-Items.php?r=success");'. It was a wrong call.
My problem now is, after success the header remains. It can't be replace by the new header that I want to change. I already changed the php code to the latest.

Select multiple rows into array and send them via AJAX

I am trying to run a SELECT query in PHP and then multiple rows are selected, but I need to fetch them into an array and then use: echo json_encode($array). After That I need to get this array into AJAX.
Here is the PHP code:
$val = $_POST['data1'];
$search = "SELECT * FROM employee WHERE emp_name = :val OR salary = :val OR date_employed = :val";
$insertStmt = $conn->prepare($search);
$insertStmt->bindValue(":val", $val);
$insertStmt->execute();
$insertStmt->fetchAll();
//echo "success";
//$lastid = $conn->lastInsertId();
$i = 0;
foreach($insertStmt as $row)
{
$arr[$i] = $row;
$i++;
}
echo json_encode($arr);
The problem is that I can't get all the lines of this array into AJAX so I can append them into some table. Here is the script:
var txt = $("#txtSearch").val();
$.ajax({
url: 'search.php', // Sending variable emp, pos, and sal, into this url
type: 'POST', // I will get variable and use them inside my PHP code using $_POST['emp']
data: {
data1: txt
}, //Now we can use $_POST[data1];
dataType: "json", // text or html or json or script
success: function(arr) {
for() {
// Here I don't know how to get the rows and display them in a table
}
},
error:function(arr) {
alert("data not added");
}
});
You need to loop over your "arr" data in the success callback. Something along the lines of:
var txt = $("#txtSearch").val();
$.ajax
({
url: 'search.php', //Sending variable emp, pos, and sal, into this url
type: 'POST', //I will get variable and use them inside my PHP code using $_POST['emp']
data: {data1: txt},//Now we can use $_POST[data1];
dataType: "json", //text or html or json or script
success:function(arr)
{
var my_table = "";
$.each( arr, function( key, row ) {
my_table += "<tr>";
my_table += "<td>"+row['employee_first_name']+"</td>";
my_table += "<td>"+row['employee_last_name']+"</td>";
my_table += "</tr>";
});
my_table = "<table>" + my_table + "</table>";
$(document).append(my_table);
},
error:function(arr)
{
alert("data not added");
}
});
You could just return
json_encode($insertStmt->fetchAll());
Also, be sure to retrieve only characters in UTF-8 or JSON_encode will "crash".
Your success function should be like this :
success:function(arr)
{
$.each(arr,function (i,item) {
alert(item.YOUR_KEY);
});
}

How get AJAX to Post JSON data into div

I'm new Jquery and AJAX and I've really been struggling with the syntax I've been trying to use other tutorials as reference but nothing seems to work. I feel I have the right idea but syntax is wrong somewhere please help.
Here is the Ajax side
var var_numdatacheck = <?php echo $datacheck; ?>;
var var_numcheck = parseInt(var_numdatacheck);
function activitycheck(){
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var json = eval('(' + data + ')');
$('#datacheck').html(json['0']);
var var_numcheck = parseInt(msg);
//setTimeout('activitycheck()',1000)},
error:function(msg) {
console.log(msg);
}
});
}
$(document).ready(function() {
activitycheck();
});
Here is the php the AJAX calls
<?php
require "dbc.php";
$function = $_POST['function'];
$datacheck = $_POST['datacheck'];
$search="SELECT * FROM Feedtest ORDER BY id DESC";
$request = mysql_query($search);
$update= mysql_fetch_array($request);
$updateid = $update['id'];
$updatecheck = mysql_num_rows($request);
$data = array();
if ($function == $datacheck){
echo $updatecheck;
echo $datacheck;
}
if ($function == "3test" && $updatecheck > $datacheck ) {
$updatesearch="SELECT * FROM Feedtest WHERE id = '$updateid' ORDER BY id DESC";
$updatequery = mysql_query($updatesearch);
$data['id'] = $updateid;
while ($row = mysql_fetch_array($updatequery))
{
?>
<?php $data[]= $row['First Name']; ?>
<?php
}
echo json_encode($data);
}
?>
</div>
</ul>
first of all ,always use JSON.parse(data) instead of eval.It is considereda a good practice.
second thing is always try to debug your code by checking it in console or alerting.In your context,this is what is happening-:
$.ajax({
type: 'POST',
url: 'feedupdate.php',
data: {function: '3test', datacheck: var_numcheck},
dataType: "json",
success: function(data) {
var data = eval('(' + data + ')');
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i=0;i< data.length;i++)
{
alldata += "<li>"+data[i][0]+"<li><hr>";
}
$('#datacheck').html(alldata);
});
}
For JSON.parse:
success: function(data) {
var data = JSON.parse(data);
console.log("myData"+data)//debugging.check the pattern so that you can acces it the way you want!!!
for(var i in data)
{
alldata += "<li>"+data[i].First Name+"<li><hr>";
}
$('#datacheck').html(alldata);
});

how to update PHP variable with Jquery Ajax?

I'm making a simple voter that takes either a "like" vote or "dislike" vote. Then, I count the total number of likes and dislikes and output the total numbers. I figured out how to put in the votes using Jquery Ajax, but the number of votes do not update after I put in a vote. I would like to update the $numlike and $numdislike variables using Jquery Ajax.
Here is the PHP script pertaining to the output:
$like = mysql_query("SELECT * FROM voter WHERE likes = 1 ");
$numlike = 0;
while($row = mysql_fetch_assoc($like)){
$numlike++;
}
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo "$numlike like";
echo "<br>";
echo "$numdislike dislike";
UPDATE:
Jquery Ajax for uploading vote
<script>
$(document).ready(function(){
$("#voter").submit(function() {
var like = $('#like').attr('value');
var dislike = $('#dislike').attr('value');
$.ajax({
type: "POST",
url: "vote.php",
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished
});
function submitFinished( response ) {
response = $.trim( response );
if ( response == "success" ) {
jAlert("Thanks for voting!", "Thank you!");
}
return false;
});
});
</script>
<form id="voter" method="post">
<input type='image' name='like' id='like' value='like' src='like.png'/>
<input type='image' name='dislike' id='dislike' value='dislike' src='dislike.png'/>
</form>
vote.php:
if ($_POST['like'])
{
$likeqry = "INSERT INTO test VALUES('','1')";
mysql_query($likeqry) or die(mysql_error());
echo "success";
}
if ($_POST['dislike'])
{
$dislikeqry = "INSERT INTO test VALUES('','0')";
mysql_query($dislikeqry) or die(mysql_error());
echo "success";
}
If you want to change current like or dislike number after clicking it you must return result instead of printing it ! return json result and echo this and change div innerHTML to see new result !
............
............
............
$dislike = mysql_query("SELECT * FROM voter WHERE likes = 0 ");
$numdislike = 0;
while($row = mysql_fetch_assoc($dislike)){
$numdislike++;
}
echo json_encode( array( $numlike, $numdislike ) ) ;
exit();
Now in your html code :
$.ajax({
type: "POST",
url: "vote.php",
context:$(this)
data: "like=" + like +"& dislike="+ dislike,
success: submitFinished(data)
});
function submitFinished( response ) {
response = $.parseJSON( response );
//Now change number of like and dilike but i don't know where are shown in your html
$('#like').attr('value',response[0]);
$('#dislike').attr('value',response[1]);
return false;
});
You can send a $_GET or $_POST variable to the file that you are calling with AJAX.
.load("google.com", "foo=bar", function(){
});

Categories