PHP code to insert data into mysql database is not working - php

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.');
}
});
});

Related

How to show error message when the values was not in mysql database?

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';
}
?>

change userlevel on button click in codeigniter

I am trying to update userlevel when click on button. i have a page where it will display all users there i have change level button.by default every user will be in normal level(means 3) so when i click on a button it has to change to 5(lead
) and if i click again it has to change to 9(admin)
here is my view page code:
<div class="col-md-4">
<form method="post" class="change_userlevel" action="" onclick="getConfirmation(9);">
<input type="hidden" name="id" value="<?php echo $user->id; ?>">
<button type="submit" class="widget-icon" name="login"><span class='icon-arrow-up'></span></button>
</form>
</div>
<td>
<?php
if($usertype==9)
{
echo 'Admin';
}
elseif($usertype==5)
{
echo 'Teamlead';
}
else
{
echo 'Normal';
}
?>
</td>
Here is my script code with ajax:
<script type='text/javascript'>
function getConfirmation(id){
$.ajax({
url: "User/change_status",
type: "post",
data: id,
success: function (response) {
location.reload();
}
});
}
</script>
Here is my controller code method change_status:
function change_status(){
$id = $this->input->post('id');
$status = $this->db->query("select userlevel from users where id=9")->row()->userlevel;
if($status==3){
$status = 5;
} else {
$status = 9;
}
$data=array('userlevel'=>$status);
$this->db->where('id','id');
$this->db->update('users',$data);
}
I dont know where i have done mistake it is not working.
can anyone help me how to solve this.
Thanks in advance.
Hope this will help you :
Your ajax code should be like this :
<script type='text/javascript'>
function getConfirmation(id)
{
if (id != '')
{
$.ajax({
url: "<?=site_url('User/change_status');?>",
type: "post",
data: {'id' : id},
success: function (response) {
alert('success');
//location.reload();
}
});
}
}
</script>
Your method change_status should be like this :
function change_status()
{
$id = $this->input->post('id');
$status = $this->db->select('userlevel')->where('id', $id)->get('users')->row()->userlevel;
if($status == 3)
{
$status = 5;
} else
{
$status = 9;
}
$data = array('userlevel' => $status);
$this->db->where('id', $id);
$this->db->update('users',$data);
echo TRUE;exit;
}

OnClick submit Insert Radio Button value into Database

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>

Mysql database update with ajax php not working

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..

sending variables to php via ajax and jquery

i want to request the users geolocation via html5-geolocation and send it to the next page
I've been told that i've to use ajax/jquery, so this is my code:
<form action="response.php">
<button onclick="getLocation()">Start</button>
<script>
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function successFunction(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
$.ajax({
type: "POST",
url: "response.php",
data: { latitude: lat, longitude: longi }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
}
</script>
</form>
and now i want to "echo" the latitude and longitude on my response.php page
but i have no idea how to do :'(
I tried this:
$latitude = $_POST["latitude"];
echo $latitude;
but the page is blank
Try This:
index.html:
<html>
<head></head>
<body>
<form action="response.php" method="post">
<input type="hidden" id="latitude" name="latitude" value="" />
<input type="hidden" id="longitude" name="longitude" value="" />
<input type="submit" value="Start" />
</form>
</body>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function getLocation() {
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
successFunction(pos);
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error,options);
} else {
//x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function successFunction(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
$('#latitude').val(lat);
$('#longitude').val(longi);
}
getLocation();
</script>
</html>
response.php:
<?php
$latitude = $_POST["latitude"];
$longitude = $_POST["longitude"];
echo "Latitude:".$latitude."</br>";
echo "longitude:".$longitude;
?>
Just create index.html copy and paste this code and make sure that response.php like this.
/yourprojectdirectory/index.html
/yourprojectdirectory/response.php
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function successFunction(position) {
var lat = position.coords.latitude;
var longi = position.coords.longitude;
$.ajax({
type: "POST",
url: "response.php",
data:"data="+ '{ "latitude":"'+ lat+'", "longitude": "'+longi+'" }'
}).done(function(msg) {
alert( "Data Saved: " + msg );
});
}
</script>
$location =json_decode( preg_replace('/\\\"/',"\"",$_POST['data']));
print_r($location);
$lat=$location->latitude;
echo $lan=$location->longitude;

Categories