The value of radio button don't insert in database. I am using PHP PDO, Jquery and Ajax
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var gender = $(this).val();
$.ajax({
url: "insert.php",
method: "POST",
data: {
gender: gender
},
success: function(data) {
$('#result').html(data);
}
});
});
});
<title>OnClick Insert Radio Button value into Database using PDO in Jquery Ajax PHP | SoftAOX Tutorial</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<h1> On Click Insert Radio Button Value into Database</h1>
<input type="radio" name="gender" value="Male">Male<br/><br/>
<input type="radio" name="gender" value="Female">Female<br/><br/>
<input type="radio" name="gender" value="Others">Others<br/>
<input type="submit"><br/>
<h3 id="result"></h3>
<br/>
<?php
//Insert Data
$hostname = "localhost";
$username = "root";
$password = "";
$databasename = "tut";
try {
$conn = new PDO("mysql:host=$hostname;dbname=$databasename", $username, $password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (isset($_POST["gender"])) {
$query = "INSERT INTO gender(gender) VALUES (:gender)";
$statement = $conn->prepare($query);
$statement->execute(array(
'gender' => $_POST["gender"]
));
$count = $statement->rowCount();
if ($count > 0) {
echo "Data Inserted Successfully..!";
} else {
echo "Data Insertion Failed";
}
}
}
catch (PDOException $error) {
echo $error->getMessage();
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('input[type="submit"]').click(function() {
var gender = $("[name=gender]:checked").val() || "na";
$.ajax({
url: "insert.php",
method: "POST",
data: {
gender: gender
},
success: function(data) {
$('#result').html(data);
}
});
});
});
</script>
Related
I have fetch(placing in inputboxes) the customer name and Dob from database through Customer phone . I am done the work but if I put the wrong customer number(there is no number in database) there will be show a alert box...that didn't know to me for how to do that...Can you please anyone solve my code...
<input type="text" class="search">phone
<input type="text" id="cname">name
<input type="text" id="cdob">date of birth
This is the script tag
<script>
$(document).ready(function() {
$('.search').keyup(function() {
var mobile_no = $(this).val();
$.ajax({
url: "get_customer_info.php",
method: "POST",
dataType: "json",
data:{
search : mobile_no
},
success:function(data){
$.each(data,function(id, val){
$("#cname").val(val.cname);
$("#cdob").val(val.cdob);
});
}
});
});
});
</script>
and this is query page
<?php
include("config.php");
$mobile=$_POST['search'];
$sql="SELECT * FROM `cm` WHERE cphone ='$mobile'";
$result = mysqli_query($conn,$sql,true);
if($result===true)
{
$mainarray=array();
while($row=$result->fetch_assoc())
{
$row['cm_id'];
$row['cname'];
$row['cdob'];
array_push($mainarray, $row);
}
echo json_encode($mainarray);
}
else
{
echo 'There is no data';
}
?>
Front end file:
<input type="text" class="search">phone
<input type="text" id="cname">name
<input type="text" id="cdob">date of birth
Your Script file:
<script>
$(document).ready(function() {
$('.search').keyup(function() {
var mobile_no = $(this).val();
if(mobile_no.length >= 10 ){
$.ajax({
url: "get_customer_info.php",
method: "POST",
dataType: "json",
data:{
search : mobile_no
},
success:function(responce){
if($.trim(responce)){
$.each(responce,function(id, val){
$("#cname").val(val.cname);
$("#cdob").val(val.cdob);
});
} else{
alert("no data");
}
}
});
}
});
});
</script>
This is your get_customer_info.php file
<?php
include("config.php");
$mobile=$_POST['search'];
$sql="SELECT * FROM `cm` WHERE cphone ='$mobile'";
$result = mysqli_query($conn,$sql,true);
if($result==true)
{
$mainarray=array();
while($row=$result->fetch_assoc())
{
$row['cm_id'];
$row['cname'];
$row['cdob'];
array_push($mainarray, $row);
}
echo json_encode($mainarray);
}
else
{
echo 'There is no data';
}
?>
I'm trying to insert data without refreshing the page using ajax and php, but the data is not getting inserted into the database.
Here is my code
<?php
require 'validation_class.php';
$obj_menufacture = new Validation_Class();
if (isset($_POST['btn'])) {
$menufacture = $obj_menufacture->menufacture_add($_POST);
}
?>
<!DOCTYPE html>
<html>
<head>
<script src='js/jquery-3.0.0.js'></script>
</head>
<body>
<div id='form_id'>
<form action='' method='post'>
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
</div>
<div id='cool'></div>
<style>
.border_input{
border-color:red;
}
.border_input1{
border-color:green;
}
</style>
<script>
$(document).ready(function () {
$('#save').on('click', function (e) {
e.preventDefault();
var m_name = $.trim($('#m_name').val());
var dataString = 'name='+ m_name;
if (m_name === '') {
if (m_name == '') {
$('#m_name_error').html('Please enter your name');
$('#m_name').addClass('border_input');
}
} else {
$.ajax({
url: 'validation.php',
method: 'post',
data:dataString,
success: function () {
$("#form_id").slideUp("slow");
}
});
}
});
});
function names(id) {
var val = $.trim($('#' + id).val());
if (val === '') {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input');
} else {
$('#' + id + '_error').html('');
$('#' + id).addClass('border_input1');
}
}
</script>
</body>
</html>
Here is my insert code
<?php
class Validation_Class{
public $link;
public function __construct() {
$HOST = "localhost";
$USER = "root";
$PASS = "";
$DATABASE = "store";
$this->link = mysqli_connect($HOST, $USER, $PASS, $DATABASE);
if (!$this->link) {
die('database query problem' . mysqli_error($this->link));
}
}
public function menufacture_add($data) {
$sql = "INSERT INTO menufacture(m_name)VALUES('$data[m_name]')";
if (mysqli_query($this->link, $sql)) {
$menufacture = "Menufacture insert successfully";
return $menufacture;
} else {
die('menufacruere query problem' . mysqli_error($this->link));
}
}
}
please help me what can i do to solve this
<form name="signup" id="reg" action="" method="post"enctype="multipart/form-data">
<input type='text' class='m_name' name='m_name' id='m_name' onchange="names('m_name')" onkeyup="names('m_name')"/>
<span style='color:red;' id='m_name_error'></span>
<input type="submit" name='btn' value="submit" id='save'/>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$("#save").submit(function () {
var form_data = $('#reg').serialize();
$.ajax({
type: "POST",
url: 'setting.php',
data: $('#reg').serialize(),
success: function (data) {
alert('Data save Successfully');
}, error: function () {
alert('Some Internal Error.');
}
});
});`
</script>
settting.php
<?php
include("db_connection.php"); // include connection file
if(isset($_POST)) {
$fname = $_POST['m_name'];
$insert = "INSERT INTO `table_name`(`column_name`)VALUES('".$fname."')";
$insertion = mysqli_query($conn, $insert);
}
?>
$("#save").on("click", function () {
var form_data = $('#reg').serialize();
$.ajax({
type:"POST",
url:'setting.php',
data: $('#reg').serialize(),
success: function(data){
alert("Data save Successfully");
},error: function () {
alert('Some Internal Error.');
}
});
});
I am trying to update mysql database table with button click. But database is not getting updated...
HTML Code :
<tr >
<td>Advt Heading :</td>
<td>
<input type="hidden" name="idnew" id="idnew" value="<?=$member_data['id']?>"> //retrieved from mysql database
<input type="text" name="advt_headingnew" id="advt_headingnew" value="<?=stripslashes($member_data['advt_heading']);?>" /> //retrieved from mysql database ...**I want to edit its previus retreived value...and update database**
<input name="submit" type="button" id="submit" value="Update" />
</td>
</tr>
SCRIPT :
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$(document).ready(function () {
$('#submit').click(function(){
var advt_headingnew = $("#advt_headingnew").val();
var idnew = $("#idnew").val();
$.ajax({
type:'POST',
url:'update-advt-heading.php',
data: "advt_headingnew="+advt_headingnew+"&idnew="+idnew,
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
});
});
</script>
PHP - update-advt-heading.php CODE :
<?
$user_name = "databaseusername";
$password = "databasepassword";
$database = "databasename";
$server = "localhost";
mysql_connect($server, $user_name, $password);
$db_found = mysql_select_db($database);
$heading = $_POST['advt_headingnew'];
$id=$_POST["idnew"];
if (isset($_POST['submit'])){
$queryStr = "UPDATE tablename SET advt_heading='$heading' WHERE id='$id'";
if ( mysql_query($qyeryStr)){
return "success!";
}else{
return "failed!";
}
}
?>
Change your js code to this
$(document).ready(function () {
$('#submit').click(function(){
var advt_headingnew = $("#advt_headingnew").val();
var idnew = $("#idnew").val();
var submitval = $(this).val();
$.ajax({
type:'POST',
url:'update-advt-heading.php',
data: "advt_headingnew="+advt_headingnew+"&idnew="+idnew+"&submit="+submitval,
success:function( msg ) {
alert( "Data Saved: " + msg );
}
});
});
});
I have changed
var advt_headingnew = $("#advt_headingnew").val();
var idnew = $("#idnew").val();
To
var advt_headingnew = document.getElementsByName("advt_headingnew")[0].value;
var idnew = document.getElementsByName("idnew")[0].value;
NOW IT IS WORKING..
I want to pass variables from post.php to addcomment.php through the AJAX request. I have tried the code below but it does not seem to work. It reloads the page but nothing happens nor is data inserted in database
post.php
//variables to pass
$userid = $row['userid'];
$uid = $row['uid'];
$postid = $row['postid'];
<form method='post' name='form' action='' class='commentbox'>
<textarea name='content' id='content'></textarea><br />
<input type='submit' value='Comment' name='submit' class='comment_button'/>
</form>
<script type="text/javascript" >
var userfrom = '<?php echo $uid ?>';
var userto = '<?php echo $userid ?>';
var postid = '<?php echo $postid ?>';
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
dataString: dataString,
userfrom: userfrom,
userto: userto,
postid: postid
}
cache: false,
success: function(html){
$(".display").show(html);
}
});
}
return false;
});
});
</script>
addcomment.php
if (isset($_POST['dataString'], $_POST['userto'], $_POST['userfrom'], $_POST['postid'])) {
$userid = $_POST['userto'];
$uid = $_POST['userfrom'];
$postid = $_POST['postid'];
$comment = $_POST['dataString'];
$com = $db->prepare("INSERT INTO comments (comment,userto, userfrom, post) VALUES (:comment, :userto, :userfrom, :post)");
$com->execute(array(':comment'=>$comment,':userto'=>$userid,':userfrom'=>$uid,':post'=>$postid));
}
Create hidden fields for userid, uid and postid and assign the values.
Get the values as var userfrom = $("#uid").val(); in script (post.php). It will Work
Please try below code, just replace below code.
your page is reloaded because of add button type submit, for ajax event you need to set type button, Please check below code :
<?php
//variables to pass
$userid = $row['userid'];
$uid = $row['uid'];
$postid = $row['postid'];
?>
<form method='post' name='form' action='' class='commentbox'>
<textarea name='content' id='content'></textarea><br />
<input type='button' value='Comment' name='submit' class='comment_button'/>
</form>
<script type="text/javascript" >
var userfrom = '<?php echo $uid ?>';
var userto = '<?php echo $userid ?>';
var postid = '<?php echo $postid ?>';
$(function() {
$(".comment_button").click(function() {
var test = $("#content").val();
var dataString = 'content='+ test;
if (test == '') {
alert("Please Enter Some Text");
} else {
$.ajax({
type: "POST",
url: "addcomment.php",
data: {
dataString: dataString,
userfrom: userfrom,
userto: userto,
postid: postid
},
cache: false,
success: function(html){
$(".display").show(html);
}
});
}
return false;
});
});
</script>
I made a simple sample on how to insert using AJAX and retrieving it then append it in a <div> after getting it. But I am having trouble on getting all the content of the table, it's returning a null values.
<div id="wrap-body">
<form action method="post">
<input type="text" name="username" id="username">
<input type="text" name="msg" id="msg">
<input type="button" id="submit" value="Send">
</form>
<div id="info">
</div>
</div>
jQuery:
<script>
$(document).ready(function (){
$('#submit').click(function (){
var username = $('#username').val();
var msg = $('#msg').val();
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$('#info').append("<p> you are:"+data.username+"</p> <p> your message is:"+data.mesg);
}
});
});
});
</script>
PHP:
<?php
$host='localhost';
$username='root';
$password='12345';
$db = 'feeds';
$connect = mysql_connect($host,$username,$password) or die("cant connect");
mysql_select_db($db) or die("cant select the".$db);
$username = $_POST['username'];
$msg = $_POST['msg'];
$insert = "INSERT INTO info(user_name,message) VALUES('$username','$msg')";
if(#!mysql_query($insert)){
die('error insertion'.mysql_error());
}
$get = "SELECT * FROM info ";
$result=mysql_query($get)or die(mysql_error());
while ($row = mysql_fetch_array($result))
{
$return = $row['user_name'];
$return = $row['message'];
}
echo json_encode($return);
?>
Your while should create array and then do json_encode
Try below code
$data=array();
while ($row = mysql_fetch_array($result))
{
$data[] = array(
'username'=>$row['user_name'],
'mesg'=>$row['message']
);
}
echo json_encode($data);
exit
Now write your javascript success handler as below
$.ajax({
type: 'POST',
url: 'get.php',
dataType: 'json',
data:'username='+username+'&msg='+msg,
success: function (data){
$.each(data, function(i, item) {
$('#info').append("<p> you are:"+data[i].username+"</p> <p> your message is:"+data[i].mesg);
});
}
});
There are several issues you have to fix, but you have to start with returning the same type as expected by the ajax call:
$return = array()
if ($row = mysql_fetch_array($result))
{
$return['username'] = $row['user_name'];
$return['mesg'] = $row['message'];
}
echo json_encode($return);