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);
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!');
}
});
}
});
});
My javascript:
$(document).on("click", "#login-submit", function() {
var username = $('#username').val();
var password = $('#password').val();
$.post (
'db/ajax/login.php',
{username:username,password:password},
function(data) {
$('#login-container').html(data);
});
});
My PHP:
if ( $_REQUEST['password'] ) {
echo $_POST['password'];
}
However i am not getting anything back out in my div that the data is to be displayed to. I know Im getting values for the variables and that the on click works because i testing alerting the variables. I just cant seam to get it to the pp PHP. I know the path is correct also.
// PHP
if ( $_REQUEST['password'] ) {
echo $_POST['password'];
}else {
echo 1;
}
// JS
$.post (
'db/ajax/login.php',
{username:username,password:password},
function(data) {
alert(data);
$('#login-container').html(data);
});
Check the alert. If alert is still not working. Please make sure you don't have any js errors in your code
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 " .
When a form is submitted, I can get its field values with $_POST. However, I am trying to use a basic jQuery (without any plugin) to check if any field was blank, I want to post the form content only if theres no any blank field.
I am trying following code, and I got the success with jQuery, but the only problem is that I am unable to post the form after checking with jQuery. It does not get to the $_POST after the jQuery.
Also, how can I get the server response back in the jQuery (to check if there was any server error or not).
Here's what I'm trying:
HTML:
<form action="" id="basicform" method="post">
<p><label>Name</label><input type="text" name="name" /></p>
<p><label>Email</label><input type="text" name="email" /></p>
<input type="submit" name="submit" value="Submit"/>
</form>
jQuery:
jQuery('form#basicform').submit(function() {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
return false;
});
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return true;
}
To be very specific to the question:
How can I get the server response back in the jQuery (to check if
there was any server error or not). Here's what I'm trying:
Sound like you're talking about Server-Side validation via jQuery-Ajax.
Well, then you need:
Send JavaScript values of the variables to PHP
Check if there any error occurred
Send result back to JavaScript
So you're saying,
However, I am trying to use a basic jQuery (without any plugin) to
check if any field was blank, I want to post the form content only if
there's no any blank field.
JavaScript/jQuery code:
Take a look at this example:
<script>
$(function()) {
$("#submit").click(function() {
$.post('your_php_script.php', {
//JS Var //These are is going to be pushed into $_POST
"name" : $("#your_name_field").val(),
"email" : $("#your_email_f").val()
}, function(respond) {
try {
//If this falls, then respond isn't JSON
var result = JSON.parse(respond);
if ( result.success ) { alert('No errors. OK') }
} catch(e) {
//So we got simple plain text (or even HTML) from server
//This will be your error "message"
$("#some_div").html(respond);
}
});
});
}
</script>
Well, not it's time to look at php one:
<?php
/**
* Since you're talking about error handling
* we would keep error messages in some array
*/
$errors = array();
function add_error($msg){
//#another readers
//s, please don't tell me that "global" keyword makes code hard to maintain
global $errors;
array_push($errors, $msg);
}
/**
* Show errors if we have any
*
*/
function show_errs(){
global $errors;
if ( !empty($errors) ){
foreach($errors as $error){
print "<p><li>{$error}</li></p>";
}
//indicate that we do have some errors:
return false;
}
//indicate somehow that we don't have errors
return true;
}
function validate_name($name){
if ( empty($name) ){
add_error('Name is empty');
}
//And so on... you can also check the length, regex and so on
return true;
}
//Now we are going to send back to JavaScript via JSON
if ( show_errs() ){
//means no error occured
$respond = array();
$respond['success'] = true;
//Now it's going to evaluate as valid JSON object in javaScript
die( json_encode($respond) );
} //otherwise some errors will be displayed (as html)
You could return something like {"error": "1"} or {"error": "0"} from the server instead (meaning, put something more readable into a JSON response). This makes the check easier since you have something in data.
PHP:
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
//no any error
return json_encode(array("error" => 0));
} else {
return json_encode(array("error" => 1));
}
JavaScript:
jQuery('input#frmSubmit').submit(function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
var myData = data;
if(myDate.error == 1) {//or "1"
//do something here
} else {
//do something else here when error = 0
}
});
}
$("form#basicform").submit();
return false;
});
There are two ways of doing that
Way 1:
As per your implementation, you are using input[type="submit"] Its default behavior is to submit the form. So if you want to do your validation prior to form submission, you must preventDefault() its behaviour
jQuery('form#basicform').submit(function(e) {
//code
e.preventDefault();
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$(this).submit();
return false;
});
Way 2:
Or simply replace your submit button with simple button, and submit your form manually.
With $("yourFormSelector").submit();
Change your submit button to simple button
i.e
Change
<input type="submit" name="submit" value="Submit"/>
To
<input id="frmSubmit" type="button" name="submit" value="Submit"/>
And your jQuery code will be
jQuery('input#frmSubmit').on('click',function(e) {
//code
var hasError = false;
if(!hasError) {
var formInput = jQuery(this).serialize();
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast", function() {
//how to check if there was no server error.
});
});
}
$("form#basicform").submit();
return false;
});
To get the response from the server, you have to echo your response.
Suppose, if all the variables are set, then echo 1; else echo 0.
if(isset($_POST['submit'])){
$name = trim($_POST['name'];
$email = trim($_POST['email'];
echo 1;
} else {
echo 0;
}
And in your success callback function of $.post() handle it like
jQuery.post(jQuery(this).attr('action'),formInput, function(data){
//this does not post data
jQuery('form#basicform').slideUp("fast",{err:data}, function(e) {
if(e.data.err==1){
alert("no error");
} else {
alert("error are there");
});
});
I have a rather confusing problem.
I have a php file (http://example.com/delete.php)
<?php
session_start();
$user_id = $_SESSION['user_id'];
$logged_in_user = $_SESSION['username'];
require_once('../classes/config.php');
require_once('../classes/post.php');
$post = new Post(NULL,$_POST['short']);
#print_r($post);
try {
if ($post->user_id == $user_id) {
$pdo = new PDOConfig();
$sql = "DELETE FROM posts WHERE id=:id";
$q = $pdo->prepare($sql);
$q->execute(array(':id'=>$post->id));
$pdo = NULL;
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
and I'm trying to get this jquery to post data to it, and thus delete the data.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This post? (" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("post Has Been Deleted!");
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
and when I do that, it returns "Post Has Been Deleted!" but does not delete the post.
Confused by that, I made a form to test the php.
<form action="http://example.com/delete.php" method="POST">
<input type="hidden" value="8" name="short"/>
<input type="submit" name="submit" value="submit"/>
</form>
which works beautifully. Very odd.
I have code almost identical for deleting of a comment, and that works great in the javascript.
Any ideas? Beats me.
Thanks in advance,
Will
EDIT:
this works... but doesn't follow the href at the end, which is the desired effect. Odd.
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short');
var conf = confirm("Delete This Post? (http://lala.in/" + num + ")");
if (conf == true) {
var invalid = false;
$.post("http://example.com/delete/post.php", {short: num},
function(data){
if (data == 'false') {
alert('Deleting Failed!');
invalid = true;
}
});
if (invalid == false) {
alert("Post Has Been Deleted!");
******************************************
event.preventDefault();
return false;
******************************************
}
else {
event.preventDefault();
return false;
}
}
else {
event.preventDefault();
return false;
}
});
If your PHP script delete the post, it doesn't return anything.
My bad, it's not answering the real question, but still is a mistake ;)
Actually, it seems that PHP session and AJAX doesn't quite work well together sometimes.
It means that if ($post->user_id == $user_id) will never validate, hence the non-deleting problem.
2 ways to see this :
Log $user_id and see if it's not null
Try to send the $_SESSION['user_id'] with your ajax post and check with it. But not in production, for security reason.
1-
Your PHP should return something in every case (at least, when you're looking for a bug like your actual case).
<?php
[...]
try {
if ($post->user_id == $user_id) {
[...]
echo 'true';
}
else {throw new Exception('false');}
}
catch (Exception $e) {
echo 'false';
}
?>
2-
jQuery is nice to use for AJAX for many reasons. For example, it handles many browsers and make checks for you but moreover, you can handle success and error in the same .ajax() / .post() / .get() function \o/
$('.post_delete').bind('click', function(event) {
var num = $(this).data('short'); // If that's where your data is... Fair enough.
if (confirm("Delete This Post? (http://lala.in/" + num + ")")) {
$.post("delete/post.php", {short: num}, // Relative is nice :D
function(data){
if (data == 'false') {
alert('Deleting Failed!');
}else{
alert("Post Has Been Deleted!");
// Your redirection here ?
}
});
}
});
3-
If you need to send data from a form to a script and then do a redirection, I won't recommand AJAX which is usually use not to leave the page !
Therefore, you should do what's in your comment, a form to a PHP script that will apparently delete something and then do a redirection.
In your code I don't see num defined anywhere...and invalid isn't set when you think it is, so you're not passing that 8 value back and you're getting the wrong message, either you need this:
$.post("http://example.com/delete.php", {short: $("input[name=short]").val()},
Or easier, just .serialize() the <form>, which works for any future input type elements as well:
$.post("http://example.com/delete.php", $("form").serialize(),
I'm not sure where your code is being called, if for example it was the <form> .submit() handler, it'd look like this:
$("form").submit(function() {
$.post("http://example.com/delete.php", $(this).serialize(), function(data){
if (data == 'false') {
alert('Deleting Failed!');
} else {
alert("Post Has Been Deleted!");
}
});
Note that you need to check inside the callback, since invalid won't be set to true until the server comes back with data the way you currently have it, because it's an asynchronous call.