New values don't update on db - javascript

I want to get data from database and change it, all with ajax but when I try to change the input ajax send the same data that was on database.
<script>
function showMore(str) {
var xhttp;
if (str.length == 0) {
document.getElementById("txtMore").innerHTML = "";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("txtMore").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "getmore.php?q="+str, true);
xhttp.send();
}
</script>
<body>
<div class="content">
<button id="edit">Update</button>
<form action="">
<h3>Last Name:</h3><input type="text" id="txt1" onkeyup="showHint(this.value)">
</form>
<span id="txtMore"></span>
</div>
</body>
<script type="text/javascript">
$('#edit').click(function(){
var ID = $('#id_field').attr('value');
var name_field = $('#FirstName').attr('value');
var last_field = $('#LastName').attr('value');
var telefone_field = $('#Telefone').attr('value');
var email_field = $('#Email').attr('value');
var check = $('#CheckIn').attr('value');
var dataString = 'id=' +ID+ '&FirstName=' +name_field+ '&LastName=' +last_field+ '&Telefone=' +telefone_field+ '&Email=' +email_field+ '&CheckIn=' +check;
alert(dataString);
$.ajax({
type: "GET",
url: "edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#txtHint").html('Actualizado');
}
});
});
</script>
And the php file where I get the data from database
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$con = mysqli_connect('localhost','root','root','client_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$q = mysqli_real_escape_String($con, $_GET['q']);
mysqli_select_db($con,"client_db");
$sql='SELECT * FROM user WHERE id = "'.$q.'" ';
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
echo'<form method="GET" class="form_user">';
echo'<input type="hidden" name="id" id="id_field" value="'.$row['id'].'" class="inputForm"><br><br>';
echo'Primeiro Nome<br>';
echo'<input type="text" name="FirstName" id="FirstName" value="'.$row['FirstName'].'" class="inputForm"><br><br>';
echo'Ultimo Nome<br>';
echo'<input type="text" name="LastName" id="LastName" value="'.$row['LastName'].'" class="inputForm"><br><br>';
echo'Telefone<br>';
echo'<input type="text" name="Telefone" id="Telefone" value="'.$row['Telefone'].'" class="inputForm"><br><br>';
echo'Email<br>';
echo'<input type="text" name="Email" id="Email" value="'.$row['Email'].'" class="inputForm"><br><br>';
echo'<input type="checkbox" name="Check" id="CheckIn" value="Check">Check-in<br><br>';
echo'</form>';
}
mysqli_close($con);
?>
Thanks.
EDIT: The problem isn't the sql query but the values inside <input> if I change that values javascript read the old values and send them to php.

You're missing an UPDATE request on your DB.
Right now your request only do a SELECT, so no matter what data are sent to your server, you're not using it.
$sql='SELECT * FROM user WHERE id = "'.$q.'" ';
$result = mysqli_query($con,$sql);
You could to something like this :
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$con = mysqli_connect('localhost','root','root','client_db');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$q = mysqli_real_escape_String($con, $_GET['q']);
$Username = $GET['Firstname'];
$Lastname= $_GET['Lastname']
// Do so for every inputs your form will give you
$sql = "UPDATE 'user' SET 'Firstname' = '$Firstname','Lastname' = '$Lastname', etc...";
$result = mysqli_query($con,$sql);
mysqli_close($con);

Related

Ajax email Availability check with php not working

I want to check email availability but it's not working. and also I am new to javascript and ajax please help me.
his is my code
email input with span to show output(for now there is no output)
<input class="input--style-4" id="email" type="email" name="email" required>
<span id="user-availability-status"></span>
JS
<script>
$(document).ready(function() {
$('#email').blur(function() {
var email = $(this).val();
$.ajax({
url: 'includes\emailAvailability.php',
method: "POST",
data: {
email_val: email
},
success: function(data) {
if (data != 0) {
$('#user-availability-status').html('<span>Username blah not available</span>');
$('#register').attr("disabled", true);
} else {
$('#user-availability-status').html('<span>Username blah Available</span>');
$('#register').attr("disabled", false);
}
}
})
});
});
</script>
PHP file
<?php
if (isset($_POST["email_val"])) {
include("DbConn.php");
$email = mysqli_real_escape_string($conn, $_POST["email_val"]);
$query = "SELECT * FROM customer WHERE email = '" . $email . "'";
$result = mysqli_query($conn, $query);
echo mysqli_num_rows($result);
}
You should check link I refered in comment its your complete answer.
here is a Simple example with your code.
include("DbConn.php");
// Set alerts as array
$error = "";
// I should just trrim and let you check if email is empty .lol
if (empty($_POST["email_val"])) {
$error .= "<p class='error'>Fill email value.</p>";
//Check if this is a real email
} elseif(!filter_var($_POST["email_val"],FILTER_VALIDATE_EMAIL)){
$error .= "<p class='error'>Wrong email type.</p>";
}else{
$email = mysqli_real_escape_string($conn, $_POST["email_val"]);
//You should use prepare statement $email, Shame on you .lol
$query = "SELECT * FROM customer WHERE email = '{$email}'");
$result = mysqli_query($conn, $query);
echo mysqli_num_rows($result);
$error .= "ok";
}
$data = array(
'error' => $error
);
This Jquery :
$(document).ready(function(){
$('#myform').submit(function(event){
event.preventDefault();
var formValues = $(this).serialize();
$.ajax({
url:"includes\emailAvailability.php",
method:"POST",
data:formValues,
dataType:"JSON",
success:function(data){
if(data.error === 'ok'){
$('#result').html(data.error);
} else {
$('#result').html(data.error);
$('#myform')[0].reset();
}
}
});
});
});
And Html :
<form id="myform">
<input class="input--style-4" id="email" type="email" name="email_val">
<span id="result"></span>
<button type="button" class="btn btn-primary">Send</button>
</form>
you can use type:"POST" instead of method:"POST" I think work thanks

Fetching data using onChange jquery ajax issue

here in my code i am trying to fetch and display the data after selecting a option from the dropdown using onChange, fetching data from a PHP file and via ajax displaying it in textarea in same select.php file but unfortunately it is not working out for me am quit confused were i made a mistake, please help me out on this.
select.php
<head>
<script type="text/javascript">
$(document).ready(function() {
$("#channel").change(function(){
$.post("ajax.php", { channel: $(this).val() })
.success(function(data) {
$(".result").html(data);
});
});
});
</script>
</head>
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" id = 'channel' name="ProductCategoryID" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="1234">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group result"></div>
ajax.php
<?php
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode = '$channel' ";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
while($row = mysql_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
Try using:
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
May be it would help
replace,
$.post("ajax.php", { channel: $(this).val() })
with
$.post("ajax.php", { 'channel': $(this).val() })
$.post("ajax.php", { channel: $(this).val() },function(data) {
$(".result").html(data);
});
Please remove .success(function(data){ }) from the code and it will work :)
Try to initiate $msg first and use mysqli module.
define('HOST','localhost');
define('USER','***');
define('PASS','***');
define('DB','***');
$response = array();
$conn = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
//get value from page
$channel = $_POST['channel'];
$query = "SELECT * FROM gst_itemmaster where ItemCode =$channel";
$result = mysqli_query($conn,$query);
$msg = '';
while($row = mysqli_fetch_array($result)) {
$msg = $msg. '<textarea type="text" class="form-control" name="Description"></textarea>'.$row['ItemDescription'].'</textarea>';
}
echo $msg;
UPDATE
Update your post request with:
$.post("ajax.php",
{ channel: $(this).val() },
function(data) {
$(".result").html(data);
}
);
OR
$.post("ajax.php",
{ channel: $(this).val() },
successCallback
);
function successCallback(data){
//process data..
}
see https://api.jquery.com/jquery.post

AJAX won't submit data

I am just learning AJAX. Our assignment this week was submitting a form with Ajax. However I can't seem to figure out what I am doing wrong, as it won't submit.
The PHP works on its own. And it needs to be available as a backup option in case JavaScript is disabled.
<?php
$final_content='';
if( isset($_POST["u_name"]) && isset($_POST["u_lastname"]) && isset($_POST["u_email"]) ){
$servername = "";
$username = "";
$password = "";
$dbname = "";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO testTable (Name, Lastname, Email)
VALUES ('".$_POST["u_name"]."','".$_POST["u_lastname"]."','".$_POST["u_email"]."')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."";
}
$conn->close();
}else {
$final_content = '<form action="script.php" method="post" id="user_form">
<input type="text" name="u_name" placeholder="Name" id="user_name"> <br>
<input type="text" name="u_lastname" placeholder="Lastname" id="user_lastname"> <br>
<input type="email" name="u_email" placeholder="Email" id="user_email"> <br>
<input type="submit" value="Submit" name="submit">
</form>';
}
?>
<html>
<head>
<script type="text/javascript" src="jquery-1.11.2.min.js"></script>
<script>
$(document).ready(function(){
//Set form variable
var form = $("#user_form");
form.submit(function(event){
//Set data variables
var user_name = $("#user_name").val();
var user_lastname = $("#user_lastname").val();
var user_email = $("#user_email").val();
//Check if values are set
if( ($.trim(user_name) != "") && ($.trim(user_lastname) != "") && ($.trim(user_email) != "") ){
$.post("script.php", {u_name: user_name}, {u_lastname: user_lastname}, {u_email: user_email}, function(data){
$("#results").html(data);
});
}
event.preventDefault();
});
});
</script>
</head>
<body>
<div id="results"></div>
<?php echo $final_content ?>
</body>
</html>
Try this :
$.post("script.php", {u_name: user_name}, {u_lastname: user_lastname}, {u_email: user_email}, function(data){
$("#results").html(data);
});
Replace the above lines with following code :
$.post("script.php", {u_name: user_name,u_lastname: user_lastname,u_email: user_email}, function(data){
$("#results").html(data);
});
and for more detail about different options with $.post() function you can refer to following link :
http://api.jquery.com/jquery.post/

Insert record into mysql using json

I want to insert the record using json into mysql and the system could display the new record without refreshing the page.
My code is shown as below:
Part 1, the script get two values from form and convert it into json, passing them to action.php
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script type="text/javascript">
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var name = $("#name").val();
var dataString = {'content': textcontent, 'name': name};
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'json',
cache: true,
success: function(html){
$("#show").html(html);
$("#flash").hide();
$("#content").focus();
}
});
}
return false;
});
});
</script>
<div>
<?php
$conn=mysqli_connect('localhost','Practical4','1234') or die('Not connected');
$database=mysqli_select_db($conn,'Practical4') or die('Database Not connected');
$id=$_GET['id'];
$query = "select * from hotel where name='$id'";
$data=mysqli_query($conn,$query);
while($rows=mysqli_fetch_array($data)){
$name=$rows['name'];
$price=$rows['price'];
$duetime=$rows['dueTime'];
$address=$rows['location'];
}
?>
<form method="post" name="form" action="">
<h3>Add Comment for <?php echo $name;?><h3>
<textarea cols="30" rows="2" name="content" id="content" maxlength="145" >
</textarea><br />
<input type="text" name="name" id="name" value="<?php echo $name;?>" hidden > <br>
<input type="submit" value="Add Comment" name="submit" class="submit_button"/>
</form>
</div>
<?php
$host="localhost";
$username="Practical4";
$password="1234";
$db_name="Practical4";
$con=mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
$sql = "select * from comment where name='$name'";
$result = mysql_query($sql);
$json = array();
if(mysql_num_rows($result)){
while($row=mysql_fetch_row($result)){
$json[] = $row[1];
}
}
mysql_close($con);
echo implode('<br />', $json);
?>
<div class="space" ></div>
<div id="flash"></div>
<div id="show" ></div>
Part2, action.php, which insert the record into mysql database.
<?php
$DBServer = 'localhost'; // e.g 'localhost' or '192.168.1.100'
$DBUser = 'Practical4';
$DBPass = '1234';
$DBName = 'Practical4';
$conn = new mysqli($DBServer, $DBUser, $DBPass, $DBName);
// check connection
if ($conn->connect_error) {
trigger_error('Database connection failed: ' . $conn->connect_error, E_USER_ERROR);
}
$v1="'" . $conn->real_escape_string($_POST['content']) . "'";
$v2="'" . $conn->real_escape_string($_POST['name']) . "'";
$sql="INSERT INTO comment (content,name) VALUES ($v1,$v2)";
if($conn->query($sql) === false) {
trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $conn->error, E_USER_ERROR);
} else {
$last_inserted_id = $conn->insert_id;
$affected_rows = $conn->affected_rows;
echo '<div class="showbox">'.$v1.'</div>';
}
?>
So far the code can insert new data, but it won't display the new record dynamically without refreshing page. Any idea to fix that?
Change your dataType to html since this parameter tells the server what kind of response it will accept in return:
$.ajax({
type: "POST",
url: "action.php",
data: dataString,
dataType: 'html',
cache: true,
success: function(data){
$("#show").html(data);
$("#flash").hide();
$("#content").focus();
}
});
In the above case the return value should be plain html:
print '<div class="showbox">' . $v1 . '</div>';
You then add it to your page using:
$('#show').html(data);
If you still would like to use json you could encode your response using something like this:
print json_encode(array('html' => '<div class="showbox">' . $v1 . '</div>'));
Then you would need to parse this value:
$("#show").html(data.html);
In the above example it seems clearer to name the success functions argument to something like data since it won't contain just html in the case.

trouble converting jQuery ajax to plain JavaScript

I'm working on converting a jQuery ajax request into plain JavaScript just so I know how to do it both ways. What I'm trying to do is pass a JSON object from my PHP script into my JavaScript file and display the values of the JSON object on the page.
I'm just beginning to dive into AJAX and I've gotten the jQuery version to work on my own easily enough, but I'm having difficult with the plain JavaScript version. For the plain JavaScript part, I'm following along with a JavaScript book that I have. That's why the code structure may seem different.
Also, I'm aware there are no real security implementations and that is fine. This is just for my own learning purposes.
Here is the HTML:
<body>
<h3>Grab the location of a person in the database below</h3>
<form action="ajax/name.php" method="POST" name="ajaxForm" id="ajaxForm">
<label for="name">Name: </label>
<input type="text" id="name" name="name">
<input type="submit" id="name-submit" name="name-submit" value="Grab">
</form>
<div id="results">
<label for="location">Location: </label>
<input type="text" name="name-data" id="name-data" disabled>
</div>
<div id="insert">
<h3>Insert a new person with a new location below</h3>
<form action="ajax/name.php" method="POST" name="insForm" id="insForm">
<label for="name">Name: </label>
<input type="text" name="ins-name" id="ins-name">
<label for="location">Location: </label>
<input type="text" name="ins-location" id="ins-location">
<input type="submit" id="ins-submit" name="ins-submit" value="Insert">
</form>
<div id="insresults_name"></div>
<div id="insresults_loc"></div>
</div>
<script src="js/ajax.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/global.js"></script>
</body>
Here is my jQuery code that works fine:
$('document').ready(function() {
var locForm = $('#ajaxForm');
var insForm = $('#insForm');
locForm.submit(function() {
$.ajax({
type: 'POST',
url: locForm.attr('action'),
data: locForm.serialize(),
success: function (response) {
$('#name-data').val(response);
}
});
return false;
});
insForm.submit(function() {
$.ajax({
type: 'POST',
url: insForm.attr('action'),
data: insForm.serialize(),
dataType: 'json',
success: function (response) {
$('#insresults_name').text('Name: ' + response[0]);
$('#insresults_loc').text('Location: ' + response[1]);
}
});
return false;
});
});
Here is my PHP Script:
<?php
if (isset($_POST['name'])) {
require '../db/connect.php';
$conn = new Con();
$name = filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
$stmt->bindParam(':name', $name);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
echo (isset($result['location'])) ? $result['location'] : 'That name isn\'t listed';
}
if (isset($_POST['ins-name']) && isset($_POST['ins-location'])) {
require '../db/connect.php';
$conn = new Con();
$name = filter_input(INPUT_POST, 'ins-name', FILTER_SANITIZE_STRING);
$loc = filter_input(INPUT_POST, 'ins-location', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare('INSERT INTO names (name, location) VALUES (:name, :loc)');
$stmt->bindParam(':name', $name);
$stmt->bindParam(':loc', $loc);
try {
$stmt->execute();
$result = $stmt->rowCount();
if ($result) {
$stmt = $conn->prepare('SELECT * FROM names WHERE name=:name');
$stmt->bindParam(':name', $name);
$stmt->execute();
$res = $stmt->fetch(PDO::FETCH_ASSOC);
$val = array();
$val[0] = $res['name'];
$val[1] = $res['location'];
echo json_encode($val);
} else {
echo 'Fail';
}
} catch (Exception $e) {
echo 'Error: ' . $e->getMessage() . '';
}
}
?>
And here is the plain JavaScript that I've come up with, but doesn't work:
function getData() {
'use strict';
var name = document.getElementById('ins-name').value();
var location = document.getElementById('ins-location').value();
var url = document.getElementById('ins-name').getAttribute('action');
if ((name.length > 0) && (location.length > 0)) {
var ajax = getXMLHttpRequestObject();
ajax.ononreadystatechange = function () {
if (ajax.readyState == 4) {
// Check the status code:
if ((ajax.status >= 200 && ajax.status < 300) || (ajax.status == 304)) {
// if ajax.responseText isn't empty
if (ajax.responseText) {
var arr = Array();
arr = JSON.parse(responseText);
document.getElementById('insresults_name').innerHTML('Name: ' + arr[0]);
document.getElementById('insresults_loc').innerHTML('Location: ' + arr[1]);
} else {
alert('Something went wrong!');
}
} else {
alert('Bad Status Code!');
}
}
};
ajax.open('POST', '../ajax/name.php', true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
var data = 'name=' + encodeURIComponent(name) + 'location=' + encodeURIComponent(location);
ajax.send(data);
return false;
} else {
alert('Please complete the form!');
}
}
function init() {
'use strict';
if (document && document.getElementById) {
var form = document.getElementById('insForm');
form.onsubmit = getData;
}
}
window.onload(init);

Categories