I have a form that adds device name and device id in mysql database. I have written a jquery script that will check whether the device id is already in the db. If exists it will return false. I have the following code-
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function(){ //newly added
$('#Submit').click(function() {alert('in');
var checkID = $('#device_id').val(); // assuming this is a input text field
$.post('includes/checkid.php', {'device_id' : checkID}, function(data) {
if(data=='exist') alert("already exists"); return false;
else $('#add_dev').submit();
});
});});
</script>
<form method="post" action="includes/process_add.php" name = "add_dev" id = "add_dev">
<tr><td width="150">Device ID</td><td>:<input type="text" name="device_id" id= "device_id"></td></tr>
<tr><td>Device Name</td><td>:<input type="text" name="device_name"></td></tr>
<tr><td></td><td><br><input type="submit" name="submit" id= "submit" value="Add device"></td></tr>
</form>
and checkid.php is -
<?php
include("connection.php");
$id = $_POST['device_id'];
$sql = mysql_query("SELECT device_id FROM devices WHERE device_id = '$id'");
if (mysql_num_rows($sql) > 0) {
echo "exist";
}else echo 'notexist';
?>
its not working..
Ajax is async, return false outside ajax success callback:
$(document).ready(function () { //newly added
$('#submit').click(function () {
alert('in');
var checkID = $('#device_id').val(); // assuming this is a input text field
$.post('includes/checkid.php', {
'device_id': checkID
}, function (data) {
if (data == 'exist') alert("already exists");
else $('#add_dev').submit();
});
return false;
});
});
Related
Form to send the name for the table to create
<script>
$(document).ready(function () {
$('#cdbt').click(function (e) {
e.preventDefault();
$.post("insert.php",
{ input_value : $("#myInput").val()},
function(data) {
$('#response').html(data);
console.log("Success");
});
});
});
</script>
<form action="" id= "cdbt" method="post">
<input type="text" id="myInput" placeholder="Title...">
<input type="submit" name="submit">
</form>
insert.php
$value = $_POST['input_value'];
$sql1 = "CREATE TABLE $value";
Create database Table by user input value in php
You have to attach submit event on form:
$(document).ready(function () {
$('#cdbt').submit(function (e) {
e.preventDefault();
$.post("insert.php",
{ input_value : $("#myInput").val()},
function(data) {
$('#response').html(data);
console.log("Success");
});
});
});
Your code is vulnerable to SQL injection you should escape values like:
$value = mysqli_real_escape_string($con,$_POST['input_value'])
This is index.php . when i give a input, it fetch the specific name and year. that's OK . but when i submit the form ,without any input it gives all the name of the movie and years but i don't want that ,the user can not show all the data saved in the database. i gave priventdefault() method but it's not working. how can i solve this problem ?
<!DOCTYPE html>
<html>
<head>
<title>ajax</title>
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(function() // this function excited if the jquery is ready i mean after jquery successfully loaded
{
function loaddata()
{
var moviename= $("#moviename").val(); // read moviename value and assign;
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
$("#submit").click(function(event) // Click Event Listener.
{
event.preventDefault();
loaddata()
});
});
</script>
</head>
<body>
<p>Enter movie name </p>
<form action="" method="POST">
<input type="text" name="moviename" id="moviename" placeholder="Enter Movie Name" required autocomplete="off">
<input type="submit" name="submit" id="submit" value="Search"/>
<!-- if you want ot use jquery you have to use event listener. like $("#submit").click(function(event){}); code from line 31 to 35 -->
</form>
<br>
<div id="result">
</div>
</body>
</html
///this is query.php
<?php
include 'dbcon.php';
$name =isset($_GET['name'])?$_GET['name']:'';
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
?>
Execute the query only if $name is not null.
if(!empty($name)) {
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query)){
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
$name =isset($_GET['name'])?$_GET['name']:'';
if(!empty($name)){
$query = mysqli_query( $conn,"SELECT * FROM movie WHERE name like '%$name%'");
while($row = mysqli_fetch_array($query))
{
echo "<p>".$row['name']."</p>";
echo "<p>".$row['year']."</p>";
}
}
in javascript
var moviename= $("#moviename").val(); // read moviename value and assign;
if(moviename){
$.ajax({
type: "GET",
url: "query.php",
data: {
name:moviename // there is no variable name so you have to assign the moveiname to name vairable ;
},
success: function (data) {
$("#result").html(data);
}
});
}
In query.php, you always assign empty string to $name in the line if empty 'name' value passed into query.php
$name =isset($_GET['name'])?$_GET['name']:'';.
So query will return you all the results in db as $name is an empty string and matches with all the data in db.
You can validate if $name is empty, not to run the query.
I real need your help since I'm a beginner in php and Ajax. My problem is that, I can not send data in the database via my appended form in post.php, also when the button of id #reply clicked it sends empty data to database by refreshing the page. When the reply link is pressed I only get the Result of reply link to be shown without other information (name and comment). I need your help to make my appanded form to be able to add/send data to the database without refreshing the page, I also need to disable the form from index.php to make replies when the reply button / link is pressed. Thank you.
post.php
<?php include("config.php"); //inserting
$action=$_POST["action"];
if($action=="addcomment"){
$author = $_POST['name'];
$comment_body = $_POST['comment_body'];
$parent_id = $_POST['parent_id'];
$q = "INSERT INTO nested (author, comment, parent_id) VALUES ('$author', '$comment_body', $parent_id)";
$r = mysqli_query($conn, $q);
if(mysqli_affected_rows($conn)==1) { header("location:index.php");}
else { }
}
// showing data
error_reporting( ~E_NOTICE );
function getComments($conn, $row) {
$action=$_POST["action"];
if($action=="showcomment"){ $id = $row['id'];
echo "<li class='comment'><div class='aut'>".$row['author']."</div><div class='comment-body'>".$row['comment']."</div>";
echo "<a href='#comment_fo' class='reply' id='".$row['id']."'>Reply</a>";
$result = mysqli_query($conn, "SELECT * FROM `nested` WHERE parent_id = '$id' ORDER BY `id` DESC");
}
if(mysqli_num_rows($result)>0) { echo "<ul>";
while($row = mysqli_fetch_assoc($result)) { getComments($conn,$row); }
echo "</ul>"; } echo "</li>";
}
if($action=="showcomment"){
$q = "SELECT * FROM nested WHERE parent_id = '".$row['id']."' ORDER BY `id` DESC";
$r = mysqli_query($conn, $q);
while($row = mysqli_fetch_assoc($r)){ getComments($conn,$row); }
}
?>
<!DOCTYPE HTML><head><script type='text/javascript'>
$(document).ready(function(){
$("a.reply").one("click", function() {
var id = $(this).attr("id");
var parent = $(this).parent();
$("#parent_id").attr("value", id);
parent.append(" <br /><div id='form'><form><input type='text' name='name' id='name'><textarea name='comment_body' id='comment_body'></textarea><input type='hidden' name='parent_id' id='parent_id' value='0'><button id='reply'>Reply</button></form></div>");
$("#reply").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){ showComment(); }
});
});
});
});
</script></head></html>
//index.php
<html><head><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function showComment(){
$.ajax({
type:"post",
url:"post.php",
data:"action=showcomment",
success:function(data){ $("#comment").html(data); }
});
}
showComment();
$(document).ready(function(){
$("#button").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
</script></head><body>
<form id="form_comment">
<input type="text" name="name" id='name'/>
<textarea name="comment_body" id='comment_body'></textarea>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
<input type="button" id="button" value="Comment"/>
</form>
<div id="comment"></div> </body></html>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault(); //add this line to prevent reload
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
Here is a simple incomplete ajax example.
FromPage.php
Here is the ajax that I'd use. The variables can be set however you like.
<script type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
var name = "John Smith";
$.ajax({
url: 'toDB.php',
type: 'post',
dataType: 'html',
data: {
carArray: cars,
firstName: name
},
success: function(data) {
console.log(data); //Testing
}
});
</script>
toDB.ph
This is the second page - the one that writes the values to the database etc.
<?php
$cars = $_POST['carArray'];
$FirstName=$_POST['firstName'];
//Used to test - it will print out the array
print("<pre>");
print_r($cars);
print("</pre>");
//Do something with $cars array and $FirstName variable
?>
I am doing form validation through ajax and php and it works fine.
Now there are two files i.e., ajax.html and codeValidate.php.
html form is in ajax and it checks the code validation using another file i.e. codeValidation.php.
Now I would like to have both in the same file and name it as Ajax.php. The code is as below.
//Ajax file
<html>
<form id="form_submit">
<input id="coupon" name="coupon" type="text" size="50" maxlength="13" />
<input id="btn_submit" type="button" value="Submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("form_submit").submit(function(e){ e.preventDefault(); return false;});
$("#btn_submit").click(function(e) { e.preventDefault();
var coupon = $("#coupon").val();
// validate for emptiness
if(coupon.length < 1 ){ window.location.href="success.html"; }
else{
$.ajax({
url: './codeValidate.php',
type: 'POST',
data: {coupon: coupon},
success: function(result){
console.log(result);
if(result){ window.location.href="success.html"; }
else{ alert("Error: Failed to validate the coupon"); }
}
});
}
});
</script>
</html>
My working php file :-
<?php
require("dbconfig.php");
if(isset($_POST['coupon']) && !empty($_POST['coupon']) ){
$coupon = trim($_POST['coupon']);
$checkcoupon = "SELECT couponCode FROM cc WHERE couponCode='".$coupon."'";
$results_coupon = mysqli_query($dbc,$checkcoupon);
if(mysqli_num_rows($results_coupon)) { echo true; }
else { echo false; }
}
?>
Hi have a form to submit with the help of jquery plugin "openid".now every thing works fine when i click on google_button but when i click on aol it will open dialog and will submit the form (when form.submit with return false is commented out) . when i remove the comments the aol will work fine with only aol dialog getting open and form not getting submitted but google form will also will not be submitted in that case.
Please help me out
================================================================================
<form action="example.php" method="post" >
<input type="image" src="images/google_button.png" id='https://www.google.com/accounts/o8/id' class="google"/>
<input type="image" src="images/AOL_button.png" id='http://openid.aol.com/' class='aol' />
</form>
================================================================================
<script type="text/javascript">
$(document).ready(function(){
$('form').openid();
})
</script>
================================================================================
(function($){
$.fn.openid = function() {
$('input').click(function(e){
var provider = $(this).attr('class');
if (provider == 'aol') {
$("#dialog").dialog();
/*$('form').submit(function(){
return false;
})*/
}
else{
var provider_url = $(this).attr('id'); //get id
var myinput = $('<input type="hidden" name="provider_url"/>').val(provider_url);
$('form').append(myinput);
$('form').submit();
}
})
}
})(jQuery);
===============================================================================
Try to send the form after if else construction.
(function($){
$.fn.openid = function() {
$('input').click(function(e){
var provider = $(this).attr('class');
if (provider == 'aol') {
$("#dialog").dialog();
/*$('form').submit(function(){
return false;
})*/
***return false;*** //add return false in this section
}
else{
var provider_url = $(this).attr('id'); //get id
var myinput = $('<input type="hidden" name="provider_url"/>').val(provider_url);
$('form').append(myinput);
$('form').submit();
}
})
}
})(jQuery);