I have a form in that I am trying to do inline editing and adding using AJAX call.
Firstly I am displaying data in HTML table. And then if enter data into text boxes and click on add button record adding displaying data in HTML table. After I click edit button data showing in the textboxes fine.
But I am getting the ajax response as null.
I couldn't figure it out.
This is my AJAX code PHP file:
$(function() {
$(".scrollingTable tbody a").click(function() {
//debugger;
var link = $(this).attr('href');
var arr = link.split('=');
var id = arr[1];
//alert(id);
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
cntid: id
},
success: function(datas) {
var data = $.parseJSON(datas);
$("#num").val(data.id);
$("#namegr").val(data.vndr_cntname);
$("#designation").val(data.designation);
$("#mobilegr").val(data.vndr_cntmobile);
$("#maildgr").val(data.vndr_cntmail);
}
});
});
});
$(function() {
$('.txtcbt a').click(function() {
debugger;
var cntname, designation, mobile, email, vndrid, id, cid;
cid = $("#num").val();
cntname = $("#namegr").val();
designation = $("#designation").val();
mobile = $("#mobilegr").val();
email = $("#maildgr").val();
vndrid = "<?php echo $selectid; ?>";
//alert(cid);
if (cntname == "" || designation == "" || mobile == "" || email == "") {
alert("fields should not be empty");
} else {
$.ajax({
url: "insertgr.php",
type: "POST",
data: {
id: cid,
name: cntname,
dgnation: designation,
mobileno: mobile,
emailid: email,
vid: vndrid
},
success: function(html) {
var dat = $.parseJSON(html);
alert(html);
alert("it came to success");
$("#num").val("");
$('#namegr').val("");
$('#designation').val("");
$('#mobilegr').val("");
$('#maildgr').val("");
}
});
}
});
});
This is file AJAX is calling:
<?php
require('Assests/connection/connection.php');
error_reporting(0);
$vcntlist = "";
if (!empty($_POST['cntid'])) {
$id = $_POST['cntid'];
$result = mysqli_query($conn, "SELECT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,`vndr_id` FROM `vndr_cntdtls`where id=$id");
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
$row = mysqli_fetch_array($result);
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
if (!empty($_POST['name']) && !empty($_POST['dgnation']) &&
!empty($_POST['mobileno']) && !empty($_POST['emailid']) &&
!empty($_POST['vid'])) {
$id = $_POST['id'];
$name = $_POST['name'];
$degination = $_POST['dgnation'];
$mobile = $_POST['mobileno'];
$email = $_POST['emailid'];
$vndrid = $_POST['vid'];
if (empty($_POST['id'])) {
$query = mysqli_query($conn, "INSERT INTO `vndr_cntdtls`(`vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`, `vndr_id`) VALUES ('$name','$degination','$mobile','$email',$vndrid)");
} else {
$update1 = mysqli_query($conn, "UPDATE `vndr_cntdtls` SET `vndr_cntname`='$name',`designation`='$degination',`vndr_cntmobile`='$mobile',`vndr_cntmail`='$email' WHERE id=$id") or die(mysqli_error($conn));
}
$result = mysqli_query($conn, "SELECT DISTINCT `id`, `vndr_cntname`, `designation`, `vndr_cntmobile`, `vndr_cntmail`,vc.vndr_id FROM `vndr_cntdtls` vc INNER JOIN vendors v ON vc.vndr_id=$vndrid") or die(mysqli_error($conn));
$rowcount = mysqli_num_rows($result);
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$vcntid = $row['id'];
$cntname = $row['vndr_cntname'];
$cntdesignation = $row['designation'];
$cntmobile = $row['vndr_cntmobile'];
$cntmail = $row['vndr_cntmail'];
}
}
}
echo json_encode($row);
?>
There could be a lot of ways it is not working.
First:
You need to put a application/json in your php so it can be compatible with the browser you are using.
header('Content-Type: application/json');
echo json_encode($row);
Second:
Why are you doing a while loop and assigning it into an unused variable?
You can simplify it by doing:
$row = mysqli_fetch_array($result);
header('Content-Type: application/json');
echo json_encode($row);
Unless it is multiple rows then:
$rowcount = mysqli_num_rows($result);
$rows = array();
if ($rowcount > 0) {
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
}
header('Content-Type: application/json');
echo json_encode($row);
Third
null values usually appears when a variable you are trying to use is not initialized. By having the error_reporting turned off it does not display the error.
error_reporting(true);
Fourth
Check also the logs for database error, I assume it has something to do with MySQL query not having to reach the $row initialization.
Fifth
I believe you need to have it fetched as associative array for it to be useful
$row = mysqli_fetch_assoc($result);
Related
Scenario :
I have a datatable which has checkbox on each row. When i try to select all checkbox and remove all selected data from datatable, it was not refreshing but the code works perfectly fine on the backend. But when i try to select all except 1 row (any of the row) it works fine...
phpaction :
$query = "
SELECT id ID, code Code, name Name, description Description FROM tablename WHERE active = 1 ORDER BY id ASC";
$res = mysqli_query($dbcon, $query);
if (mysqli_num_rows($res) > 0) {
$data = array();
$tbl = '';
while ($row = mysqli_fetch_assoc($res)) {
$data[] = $row;
}
echo json_encode($data);
} else {
echo json_encode('');
}
ajax:
$datatable.find('input[type="checkbox"]:checked').each(function() {
ID = $(this).attr("value").substr((($(this).attr("value")).length - 8) * -1);
remove(ID);
});
function remove(ID) {
requestAction = 'remove';
$.ajax({
url: 'phpaction.php',
method: 'post',
data: {
requestAction: requestAction,
ID: ID
},
success: function(data) {
list();
},
error: function(err) {
console.log(err);
}
});
}
When I send an ajax post request to my getMessages.php file it doesn't return anything.
I've tried manually setting the array values and printing them in the console and that seems to work.
getMessages.php
<?php
require_once "mysqli.php";
$data = array();
if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
$username = $_SESSION["username"];
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_array($result)) {
$data['startuser'] = $row['msg_startuser'];
$data['msg'] = $row['msg'];
}
}
echo json_encode($data);
exit;
?>
js ajax
function getChat() {
$.ajax({
url: 'getMessages.php',
type: 'POST',
data: {getChat: 'yes'},
dataType: 'JSON',
success: function(data) {
// testing
console.log(data.startuser, data.msg);
}
})
}
I want it to print out in the console for testing.
Hi you can try this way:
The php script :
<?php
require_once "mysqli.php";
session_start();// start the session
$data = array();
if (isset($_SESSION["username"])) {
if (isset($_POST["endUser"]) && isset($_POST["action"])) {
$case = $_POST["action"];
$endUser = $_POST["endUser"];
$username = $_SESSION["username"];
switch (case) {
case 'getChat':
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = '{$endUser}'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = '{$endUser}' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_assoc($resultado)) {
if (isset($row['msg_startuser']) && isset($row['msg'])) {
$temp = array(
"user"=>$row['msg_startuser'],
"msg"=>$row['msg']
);
}
$data[] = $temp;
}
echo json_encode($data);
break;
}
}
}else {
echo "error-403";
}
?>
The javascript :
function getChat() {
return $.ajax({
url: 'getMessages.php',
type: 'POST',
data: {action: 'getChat',endUser:'mariokiller470'},
dataType: 'JSON'
})
}
getChat()
.done(function(response){
console.log(response);
})
Hope it Helps
data is overwritten in the loop again and again, I guess you would like to do something like this:
$x = 0;
while ($row = mysqli_fetch_array ($result)) {
$data[$x]['startuser'] = $row['msg_startuser'];
$data[$x]['msg'] = $ row['msg'];
$x++;
}
Ooops!
I forgot to start the session!
Thanks PatrickQ!
This will solve the problem since you are returning response as objects
An Updates:
You will need to initialize session
and data parameters for an array should be inside the the if statements
Try code below
<?php
require_once "mysqli.php";
session_start();
if (isset($_POST['getChat']) && !empty($_POST['getChat'])) {
$username = $_SESSION["username"];
$data = array();
$result = mysqli_query($conn, "SELECT msg_startuser, msg, time
FROM messages
WHERE msg_startuser = '{$username}' and msg_enduser = 'mariokiller470'
UNION
SELECT msg_startuser, msg, time
From messages
WHERE msg_startuser = 'mariokiller470' and msg_enduser = '{$username}'
order by time;
");
while ($row = mysqli_fetch_array($result)) {
$startuser = $row['msg_startuser'];
$msg = $row['msg'];
$data = array("startuser" =>$startuser, "msg" =>$msg);
}
echo json_encode($data);
exit;
}
?>
so in ajax console. this line of code will work fine
console.log(data.startuser, data.msg);
I know that this question is already answered a lot, but even the previous responses from php are working, this response cannot work and i cannot find the reason for this issue.
Although php was send the response succesfully, ajax cannot display without refreshing the page first.
Here is my jquery.ajax code in the file helpers.js:
function likeButton(commentId, userId) {
$.ajax({
url: "requests.php",
type: "POST",
data: {
like: "likeUp",
commentId: commentId,
userId: userId
},
success: function(response) {
$("#comment_body").append(response);
}
});
}
Here is my php code in requests.php:
if(isset($_POST['like'])) {
if($_POST['like'] == "likeUp") {
$commentId = $_POST['commentId'];
$userId = $_POST['userId'];
$sql = "SELECT gaming_comment_like FROM gaming_comments WHERE gaming_comment_id='$commentId'";
$result = mysqli_query($conn, $sql);
if($row = mysqli_fetch_assoc($result)) {
$gaming_comment_like = $row['gaming_comment_like'];
}
$gaming_comment_like = $gaming_comment_like + 1;
$sql_update = "UPDATE gaming_comments SET gaming_comment_like='$gaming_comment_like' WHERE gaming_comment_id='$commentId'";
$result_update = mysqli_query($conn, $sql_update);
exit();
}
}
here is the eventhandler that calling the likeButton function, which is in a php file:
<p><img src='like.png' class='like_button' onclick='likeButton(".$gaming_comment_id.", ".$user_id.");'>$gaming_comment_like</p>";
I am using the following ajax script to run my MySQL query and then only want the jquery to fade out my div and fade in another if the query returned true otherwise if the query returned false don't do anything.
Ajax:
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "include/fade_to_do_list.php",
data: "theOption=" + $(this).attr("id"),
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("success") >-1 ){
setTimeout(
function() {
$("#to_do_list").fadeOut();
}, 3500
);
setTimeout(
function() {
$("#compliance_list").fadeIn();
}, 500
);
}
}
});
});
</script>
PHP/MYSQL:
<?php
session_start();
include 'config.php';
$query = "SELECT * FROM supplier_stats WHERE complete_count = > 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
if(mysql_num_rows($result)>0) {
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
if($result2) {
$return['res'] = 'success';
} else {
}
}
echo json_encode($return);
?>
Please can someone show me where I am going wrong? I currently get no error and my jquery just doesnt execute. Thanks
mysql_query() always return you something. You need to count number of affected row.
Also problem is with equal to greater then operator it is used as >=
$query = "SELECT * FROM supplier_stats WHERE complete_count >= 3 AND user_id = '{$_SESSION['id']}'";
$result = mysql_query($query);
$query2 = "UPDATE supplier_stats SET profile_complete = 'complete' WHERE user_id = '{$_SESSION['id']}'";
$result2 = mysql_query($query2);
$total=mysql_affected_rows();
if($total >0) {
$return['res'] = 'success';
} else {
}
I have a jquery save script like :
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Your file is save as : '+ naam);
window.location.replace("index.php?id=latest");
}
else
{
alert('Not saved');
}
I save a div in save.php which creates an new id in the database
What I want to achive is were
window.location.replace("index.php?id=latest");
id=latest must become (id=id from last saved file).
I tried
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
window.location.replace("index.php?id="+MBId);
and
var MBID =
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo $MBId ?>
window.location.replace("index.php?id="+MBId);
They both failed.
How can I run the query in the if(naam !=null) statement?
At first place you must fix your jQuery POST... You don't use POST respond which is wrong.. You should wait for it and then continue with other actions
naam = prompt('Give a name for your file.');
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam }, function(responde){
if(responde.id)
window.location.replace("http://yoururl.com/index.php?id="+responde.id);
else
alert("No responde...");
}, "json");
}
else
{
alert('Not saved');
}
For better results I suggest you to use JSON data in that post/respond..
At your PHP code you have to set:
<?php
$q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = $data[0];
echo json_encode(array('id'=>$MBId));
exit();
?>
P.S. For window.location.replace please set your FULL url: "http://localhost/index.php?id=" OR atleast put slash at start of it "/index.php?id="
Solution
if(naam != null)
{
var div_contents = $("#print").html();
$.post("save.php", { 'contents': div_contents,'naam':naam });
alert('Uw moodboard is opgeslagen als '+ naam);
window.location.replace("index.php?id=<?php $q = "select MAX(id) from Moodboards";
$result = mysql_query($q);
$data = mysql_fetch_array($result);
$MBId = ($data[0] + 1); echo "$MBId";?>");
}
This Works for me , i didnt need to make a jquery var i could echo the variable in php.
And i had to add 1 cause the sql query is loaded when the page is loaded.
So the file isn't saved yet when i get the highest id.