Mysql database update with ajax php not working - php

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

Related

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>

Google map and PHP, SQL

I want to link my json result to the google map. I have a imei_number in the database which is the password of the user. Once the user enter the right password(imei_number in the database), the system will select the longitude and latitude of the imei_number selected and later link it to the google map's longitude and latitude.
The HTML code is:
<form method="post" action="loginServer.php">
<label> Username: </label>
<input type = "text" maxlength = "20" name = "user" id= "user" />
<br />
<label> Password: </label>
<input type = "password" maxlength= "20" name="pass" id= "pass" />
<br />
<input type ="Button" onclick="" value="Clear" />
<input type = "Submit" value = "Login"id= "btn"/>
</p>
</form>
The Google map page is
<script type = "text/javascript">
function LoadMap(){
var mapEdit = {
zoom: 8,
center: new google.maps.LatLng($.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.latitude);
});
});
,
$.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.longitude);
});
});
),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), mapEdit);
var marker = new google.maps.Marker({
position: new google.maps.LatLng( $.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.latitude);
});
});
,
$.getJSON('connect.php', function(data) {
$.each(data, function(key, val) {
$("ul").append(val.longitude);
});
});
),
map: map,
});
marker.addListener('click', function(){
infowindow.open(map, marker);
});
}
</script>
</head>
<body onload = "LoadMap()">
<div id="map" style="width: 400px; height: 500px;"></div>
The connect.php is
<?php
include 'linker.php';
$sql = "SELECT * FROM android_data WHERE $pass = 'imei_number'";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
$row["longitude"]);
$row["longitude"]. " - latitude: " . $row["latitude"]. "<br>";
}
} else {
echo "0 results";
}
echo json_encode($data);
mysqli_close($conn);
?>
The linker.php is
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "project_gps";
$user = $_POST['user'];
$pass = $_POST['pass'];
$user = stripcslashes($user);
$pass = stripcslashes($pass);
$conn = mysqli_connect($servername, $username, $password, $dbname);
$user = mysqli_real_escape_string($conn, $user);
$pass = mysqli_real_escape_string($conn, $pass);
if($conn){
echo "connected";
}
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
?>
But they are not all working. Please, what can I do?

PHP code to insert data into mysql database is not working

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

How to pass variables through ajax?

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>

Getting all the content of table and append it using ajax with jquery

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);

Categories