Hi so my over all aim is to click a table get its ID and then use its ID to load another table. So far I am able to get the ID, but when I try to load the second table I get the error
"Undefined index: Projec_ID in C:\xampp\htdocs\abac\ajaxupdate.php on
line 6 "
Here's my Code
AJAX Script(Console prints the rowID so it is getting, the variable I think something is going wrong when trying to pass it?)
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var log = $("#log");
$(".getRow").click(function() {
console.log("Clicked a row...");
rowID = $(this).find("td.idCell").text();
//Print the row ID in the log cell to make sure we got the right one.
log.text("You 1clicked row "+rowID);
console.log("You cl2icked row "+rowID);
//Send the row ID to ajaxupdate.php
$.post("/abac/ajaxupdate.php", { what: "updateRow", Projec_ID: rowID})
.done( function(data) {
var results = $.parseJSON(data);
console.log(rowID );
})
.fail( function() {
console.log("AJAX POST failed.");
});
});
});
</script>
PHP File (ajaxupdate.php) I think there is something wrong here im guessing
<?php
if( (isset($_POST['submit'])) || (isset($_POST['Projec_ID'])) )
{
$Projec_ID =($_POST['Projec_ID']);
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select($db->quoteName(array('CV_ID', 'Classifier', 'Value', 'TP_ID')))
->from($db->quoteName('sessionta'))
//also is the like part right?
->where($db->quoteName('TP_ID') . ' LIKE '. $db->quote($_POST['Projec_ID']));
$db->setQuery($query);
$results = $db->loadObjectList();
//echo $Classifier;
}
?>
$_POST['submit'] will be false unless you set it:
[...] { "what": "updateRow", "Projec_ID": rowID, "submit" : "true"}
Which is why you get the error message "Undefined Index" -!
Furthermore, you can always:
<?php
echo "<pre>";
print_r($_POST);
echo "</pre>";
die("The data above was sent via POST");
to troubleshoot these sorts of things..
Your problem could be that you are using an || operator and not an && operator.
if( (isset($_POST['submit'])) || (isset($_POST['Projec_ID'])) )
What this means if at some point you pass $_POST['submit'] and not $_POST['Projec_ID'] it will still run this code. giving you the
"Undefined index: Projec_ID in C:\xampp\htdocs\abac\ajaxupdate.php on line 6 "
Try changing your code to:
if( (isset($_POST['submit'])) && (isset($_POST['Projec_ID'])) )
I think Project_ID isn't going as a string..
Try this code.
<script language="javascript" type="text/javascript">
$(document).ready(function() {
var log = $("#log");
$(".getRow").click(function() {
console.log("Clicked a row...");
rowID = $(this).find("td.idCell").text();
//Print the row ID in the log cell to make sure we got the right one.
log.text("You 1clicked row "+rowID);
console.log("You cl2icked row "+rowID);
//Send the row ID to ajaxupdate.php
$.post("/abac/ajaxupdate.php", { what: "updateRow", "Projec_ID": rowID})
.done( function(data) {
var results = $.parseJSON(data);
console.log(rowID );
})
.fail( function() {
console.log("AJAX POST failed.");
});
});
});
</script>
i just enclosed Projec_ID with with " .
Related
Update: The code is working. I had an incorrectly named table in my php file.
I have the following that I've found from some snippets during my searches for help however I cannot get it to work. What I am trying to accomplish is clicking a check box and it automatically populate a row in my database that I can refer to on any other page. Right now when I click the checkbox, nothing happens.
HTML
<td><input type="checkbox" name="<?php echo $brow['WorkOrder']; ?>" value="<?php echo $brow['WorkOrder']; ?>"></td>
Ajax
<!-- Checkbox storage -->
<script>
$(document).ready(function(){
$("input[type='checkbox']").on('click', function(){
var checked = $(this).attr('checked');
if(checked){
var value = $(this).val();
$.post('functions/checkBox.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
});
</script>
functions/checkBox.php
<?php
if ($_POST && isset($_POST['value'])) {
// db connection
include("../../db.php");
// sanitize the value
$value = mysql_real_escape_string($_POST['value']);
// start the query
$sql = "INSERT INTO TemporaryCheckBoxID (WorkOrder) VALUES ('$value')";
// check if the query was executed
if(mysql_query($sql)){
// everything is Ok, the data was inserted
print(1);
} else {
// error happened
print(0);
}
}
?>
To check whether checkbox is checked or not use as below and try
<script>
$(document).ready(function(){
$("input[type='checkbox']").on('click', function(){
var checked = $(this).is(":checked");
if(checked){
var value = $(this).val();
$.post('functions/checkBox.php', { value:value }, function(data){
// data = 0 - means that there was an error
// data = 1 - means that everything is ok
if(data == 1){
// Do something or do nothing :-)
alert('Data was saved in db!');
}
});
}
});
});
I have an image and after clicking this image I take this game id by JQuery code and then a new PHP tap opens this PHP take should display this image id
Here is the JQuery code:
$(".selected").click(function(){
$.post("bookinfo.php", { id: $(this).attr('id') }, function (response) {
alert(response);
});
});
and here is the PHP code
<?php
$id = $_POST['id'];
echo $id;
?>
and here is the error that i get
Notice: Undefined index: id in C:\xampp\htdocs\bookstore\bookinfo.php on line 2
I have tried AJax request and get but the same error happens..
I have been trying for this error for about 2 hours so please help me!
You can do something like this:
Edited:
jQuery
<script>
$(document).ready(function(){
$(document).on('click','.selected',function(){
var id = $(this).attr('id');
window.location.replace("bookinfo.php?id=" + id);
});
});
</script>
PHP
<?php
if(isset($_GET['id']) && !empty($_GET['id'])){
$id = $_GET['id'];
echo $id;
}
?>
in your php you have to return a json to get it from AJAX. just try changing your php code like this.
<?php
header('Content-Type: application/json');
if(isset($_POST['id']))
{
$data = array($_POST['id']);
echo json_encode($data);
}
I have a php page where i have used a jquery function to get the dynamic value according to the values of checkboxes and radio buttons and text boxes. Whats' happening is i have used two alerts
1.) alert(data);
2.)alert(grand_total);
in the ajax part of my Jquery function just to ensure what value i'm getting in "grand_total". And everything worked fine, alerts were good and data was being inserted in the table properly.
Then i removed the alerts from the function, and after sometime i started testing the whole site again and i found value of grand_total in not being inserted in mysql table.
I again put those alerts to check what went wrong, again everything started working fine. Removed again and problem started again. Any idea folks what went wrong?
here is the code snippet of JQUERY func from "xyz.php":
<script type="text/javascript">
$(document).ready(function() {
var grand_total = 0;
$("input").live("change keyup", function() {
$("#Totalcost").val(function() {
var total = 0;
$("input:checked").each(function() {
total += parseInt($(this).val(), 10);
});
var textVal = parseInt($("#min").val(), 10) || 0;
grand_total = total + textVal;
return grand_total;
});
});
$("#next").live('click', function() {
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
},
success: function(data) {
// do something;
}
});
});
});
Corresponding HTML code:
<form method="post" id="logoform3" action="xyz_sql.php">
<input type="text" name="Totalcost" id="Totalcost" disabled/>
<input type="submit" id="Next" name="next"/>
This the code from *"xyz_sql.php"*:
<?php
session_start();
include ("config.php");
$uid = $_SESSION['uid'];
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2 (total,uid)VALUES('$total','$uid');";
if($total > 0){
$res = mysql_query($sql);
}
if($res)
{
echo "<script> window.location.replace('abc.php') </script>";
}
else {
echo "<script> window.location.replace('xyz.php') </script>";
}
?>
And last but not the least: echo " window.location.replace('abc.php') ";
never gets executed no matter data gets inserted in table or not.
First you submit form like form, not like ajax - cause there is no preventDefault action on clicking submit button. That's why it looks like it goes right. But in that form there is no input named "grand_total". So your php script fails.
Second - you bind ajax to element with id "next" - but there is no such element with that id in your html that's why ajax is never called.
Solutions of Роман Савуляк is good but weren't enough.
You should casting your $total variable to integer in php file and also use if and isset() to power your code, so I'll rewrite your php code:
<?php
session_start();
include ("config.php");
if(isset($_SESSION['uid']))
{
$uid = $_SESSION['uid'];
if(isset($_POST['grand_total']))
{
$total= mysql_real_escape_string($_POST['grand_total']);
$sql="INSERT INTO form2(total,uid) VALUES('".$total."','".$uid."')";
if((int)$total > 0)
{
if(mysql_query($sql))
{
echo "your output that will pass to ajax done() function as data";
}
else
{
echo "your output that will pass to ajax done() function as data";
}
}
}
}
and also you can pass outputs after every if statement, and complete js ajax function like:
$.ajax({
url: 'xyz_sql.php',
type: 'POST',
data: {
grand_total: grand_total
}
}).done(function(data) {
console.log(data); //or everything
});
Having trouble deleting a record from mysql databse using ajax/jquery. Issue I am having is that it does not delete from the database but does delete from the list. What am I doing wrong here?
Here is my code:
jQuery(document).ready(function(){
$(".deleteitem").click(function(){
var parent = $(this).closest('li');
var id = parent.attr('id');
$.ajax({
type: "POST",
data: "id=" +id,
URL: "delete.php",
success: function(msg){
$('#'+id).remove();
}
});
});
});
My php file delete.php:
$con=mysqli_connect("localhost","user","pass","db");
// Check connection
if (mysqli_connect_errno())
{ echo "Failed to connect to MySQL: " . mysqli_connect_error(); }
$id = $_POST['id'];
if (isset($id)) {
$query = "DELETE FROM img_slider WHERE id = '$id'";
mysqli_query($query) or die('Error, insert query failed');
}
The HTML markup:
<li id='".$row['id']."'>
<a href='#' class='deleteitem'><img src='../img/delete.png'></a>
</li>
Firstly test to make sure calling the delete file with a valid id works. The javascript below should work fine.
<script type="text/javascript">
<!--
$(function() {
$('.deleteitem').click(function(e) {
e.preventDefault();
var id = $(this).parent('li').attr('id');
$.get('delete.php',{ id: id}).done(function(data) {
if(data=='Error, insert query failed') {
// dont delete from list
alert('Failed to delete '+id);
} else {
//delete from list
$('#'+id).remove();
alert('Deleted '+id);
}
});
});
});
//-->
</script>
EDIT: updated the script to assist parent-id handling.
Are you able to say where the error is coming from? Most modern browsers should offer you some insight into what line, or what section the error is occurring on.
The script above should replace all your javascript.
I'm new to server validation and I've looked all over the web and can't find a thing. I'm trying to validate a form with php by posting it to itself and returning a 1 or a 0 in an array depending on whether the form is valid or not. That works fine but the issue I'm having is I want to make the log in screen fade out if the result is 1. I can't get that to work.
Here's my code:
The PHP
if ($valid == 1) {
$isvalid = array('valid' => $valid);
echo json_encode(array_values($isvalid));
};
The javascript
<script>
$(document).ready(function(){
$('#login_button').click(function(){
$.getJSON("/index.php",function(result){
console.log(result);
});
});
});
</script>
nothing outputs into the console, I've also tried alert and nothing happens. The JSON seems to be working in the top left corner I get a [1] which should be what I need.
Here is my whole code maybe it's a matter of placing the script?
<script type="text/javascript" src="/jquery-1.9.1.min.js">
</script>
\\wait to load the script until the document is ready
<script>
$(document).ready(function(){
//on submission
$('#login_button').click(function(){
//check if login was valid
$.getJSON("localhost/index.php",function(result){
console.log(result) .error(function() {console.log('error');});
});
});
});
</script>
<?PHP
$valid = 0;
//Declare the database connection
$con = mysql_connect("localhost","root");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
//Has the form been submitted?
if(isset($_POST['Username'])){
//Check if Username and PW correct
mysql_select_db ("Users",$con);
$sqlCheckUser = mysql_query ( "select Username from userinfo where UserName = '$_POST[Username]' && Password = MD5('$_POST[Password]')");
//Parse Results
$row = mysql_fetch_assoc($sqlCheckUser);
//is the login valid
if (isset($row) && !empty ($row)) {
$valid = 1;
}
else {
$badpw = "Invalid Username or Password";
}
}
//handle if form has not been submitted
else {
echo "<center>Please Enter Username and Password</center><br />";
};
if ($valid == 1) {
$isvalid = array('valid' => $valid);
echo json_encode(array_values($isvalid));
};
?>
</head>
I validated my JSON, it looks good does anyone know what's going on? I really need this to work.
EDIT
Ok so appending this onto my code does give me the error.
the script now looks like the following
<script>
$(document).ready(function(){
$('#login_button').click(function(){
$.getJSON("index.php",$('#Login').serialize(),function(result){
alert(result);
})
.error(function(error) { alert(error); console.log(error); })
})
});
</script>
The alert text is [object Object]
The console output is this:
object ready state: 0
getResponseHeader: Function
getAllRequestHeaders: Function
SetRequestHeader: Function
overrideimetype: function
http://i.imgur.com/Ei2bBAR.jpg
(I took a screenshot because it wouldn't stay in the console long enough for me to read it)
your response data is on result variable as in your callback function, so change:
console.log(json);
to
console.log(result);