I applied some jquery on my paragraph fields and converted them in input fields.It works!! But when i post them to next page i.e address_update.php after giving some values through ajax it does not update the values in database. Any suggestions please.
html
<form method="post" action="">
<?php
$em=$_SESSION['login_email'];
$query = mysqli_query($con,"SELECT * FROM customers where email='$em'" );
while($row=mysqli_fetch_assoc($query)){
?>
<h5>Name:</h5><p id="name"><?= $row['name'] ?></p>
<h5>Email:</h5><p id="email"><?= $row['email'] ?></p>
<h5>Telephone:</h5><p id="phone"><?= $row['phone'] ?></p>
<h5>Address:</h5><p id="address"><?= $row['address'] ?></p>
<h5>City:</h5><p id="city"><?= $row['city'] ?></p>
<?php
}
?>
<input type="button" id="up" value="Update" >
<input type="submit" id="update" value="Update Address" >
</form>
Ajax
<script >
$(document).ready(function() {
$('#update').click(function(){
var name = $("#name").val(),
address = $("#address").val(),
phone = $("#phone").val(),
city = $("#city").val();
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name: name, Address: address, Phone: phone, City:city},
dataType: "json",
success: function(data) {
if(data)
{
$("#error").html("Done. ");
// $("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Cant update. ");
}
}
});
});
});
</script>
Js
<script>
$('#up').click(function() {
var $name = $('#name');
var $phone=$('#phone');
var $address = $('#address');
var $city=$('#city');
var $input_name = $("<input>", {value: $name.text(),type: "text", id:"name"});
var $input_phone = $("<input>", {value: $phone.text(),type: "text", id:"phone"});
var $input_address = $("<input>", {value: $address.text(),type: "text" ,id:"address"});
var $input_city = $("<input>", {value: $city.text(),type: "text",id:"city"});
$name.replaceWith($input_name);
$phone.replaceWith($input_phone);
$address.replaceWith($input_address);
$city.replaceWith($input_city);
document.getElementById("update").style.display="block";
document.getElementById("up").style.display="none";
$input_name.select();
$input_address.select();
$input_phone.select();
$input_city.select();
});
</script>
address_update.php
if(isset($_SESSION["login_email"]) || isset( $_SESSION["login_user"]))
{
$name=$_POST['Name'];
$address=$_POST['Address'];
$phone=$_POST['Phone'];
$city=$_POST['City'];
$email=$_SESSION['login_email'];
$sql=mysqli_query($con,"Update `customers` set `name`='".$name."',`address`='".$address."',`phone`='".$phone."',`city`='".$city."' where `email`='".$email."'");
if($sql)
{
echo "updated";
}
else{
echo "no";
}
}
You can not put the jquery selectors in the json array, but anyway supposig you have an "#add" element:
$(document).ready(function() {
$('#add').click(function()
{
var name = $("#name").val(),
address = $("#address").val(),
phone = $("#phone").val(),
city = $("#city").val(),
$.ajax({
url: "address_update.php",
type: "POST",
async: true,
data: { Name: name, Address: address, Phone: phone, City:city},
dataType: "json",
success: function(data) {
if(data)
{
$("#error").html("Done. ");
// $("body").load("index.php?page=form");//.hide();//.fadeIn(1500).delay(6000);
}
else
{
$("#error").html("<span style='color:#cc0000'>Error:</span> Cant update. ");
}
}
});
});
});
Related
I am creating a program and am having trouble passing user credentials into a database. I am using the AJAX .post function and for some reason, the data is not being passed into the PHP script.
The submitInfo() function seems to completely bypass the .post function nested inside, as the page does notify me with the successful sign in alert after pressing submit.
Here is the HTML/JS file, (doesn't show the implementation of jQuery along with an imported MD5 function I'm utilizing to hash the password):
<h2>First name:<h2>
<input id="firstNameInput" type="text" maxLength="20">
<h2>Last name:<h2>
<input id="lastNameInput" type="text" maxLength="20">
<h2>Create a username:<h2>
<input id="createUserInput" type="text" maxLength="20">
<h2>Create a password:<h2>
<input id="createPassInput" type="text" maxLength="20">
</br>
</br>
<input id="submitCredsButton" type="submit" onclick="submitInfo()">
<script>
function submitInfo()
{
var postData = [{
firstName : document.getElementById("firstNameInput"),
lastName : document.getElementById("lastNameInput"),
username : document.getElementById("createUserInput"),
hashPass : MD5((document.getElementById("createPassInput")).value)
}];
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: "postData",
dataType: "text",
});
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
</script>
And here is the PHP script, in a separate file:
<?php
$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);
}
//posts data to db
$stmt = $data->('INSERT INTO userlist
(firstName,lastName,username,hashedPass)
VALUES (:firstName, :lastName, :username, :hashPass)');
$stmt->execute($data);
?>
-edit-
Figured it all out, one simple but overlooked mistake I had was where I had placed the single and double quotes. Thanks to all users that helped with the JS issues I was having!
HTML/JS:
<h2>First name:<h2>
<input id="firstNameInput" type="text" maxLength="20">
<h2>Last name:<h2>
<input id="lastNameInput" type="text" maxLength="20">
<h2>Create a username:<h2>
<input id="createUserInput" type="text" maxLength="20">
<h2>Create a password:<h2>
<input id="createPassInput" type="text" maxLength="20">
</br>
</br>
<input id="submitCredsButton" type="submit" onclick="submitInfo()">
<script>
function submitInfo()
{
var fName = document.getElementById("firstNameInput").value;
var lName = document.getElementById("lastNameInput").value;
var uName = document.getElementById("createUserInput").value;
var pPass = document.getElementById("createPassInput").value;
var hPass = MD5((document.getElementById("createPassInput")).value);
if(fName.length <= 0 || lName.length <= 0 || uName.length <= 0 || pPass.length <= 0)
{
alert("Please verify all fields have been filled out.");
}
else
{
$.ajax
({
type: "POST",
url: "phpScripts/signup.php",
data: {firstName: fName, lastName: lName, userName: uName, hashPass: hPass},
dataType: "text",
success: function(response)
{
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
});
}
}
</script>
PHP Script:
<?php
$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); }
?>
<?php
//posts data to db
$fName = $_POST["firstName"];
$lName = $_POST["lastName"];
$uName = $_POST["userName"];
$hPass = $_POST["hashPass"];
$sql = "INSERT INTO userlist ( firstName,lastName,username,hashedPass )
VALUES ( '$fName', '$lName','$uName','$hPass' )" ;
$result = $conn->query($sql);
if($result){
echo "true";
}
else{
echo "false";
}
?>
You have written "postData" in double quote, so it will consider as string, but actually it is variable.
Try :
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
});
The problem is that you are using "postData" which is just a string but you need to use postData because it already has definition.
Just replace "postData"
with postData
Ajax
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
});
First problem. You are not passing a string to the $.ajax. You have to pass the variable which is an object: data: postData,.
Second problem. Your postData is an array but it has to be an object:
var postData = {
firstName : document.getElementById("firstNameInput"),
lastName : document.getElementById("lastNameInput"),
username : document.getElementById("createUserInput"),
hashPass : MD5((document.getElementById("createPassInput")).value)
};
Third problem. Your are passing DOM objects as postData instead of their values. Just use .value property:
var postData = {
firstName : document.getElementById("firstNameInput").value,
lastName : document.getElementById("lastNameInput").value,
username : document.getElementById("createUserInput").value,
hashPass : MD5((document.getElementById("createPassInput")).value)
};
Fourth problem. The $.ajax is asynchronous so you have to provide a success callback, so the callback will be run just after the finish of the request:
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
success: function () {
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
});
Complete solution:
function submitInfo()
{
var postData = {
firstName : document.getElementById("firstNameInput").value,
lastName : document.getElementById("lastNameInput").value,
username : document.getElementById("createUserInput").value,
hashPass : MD5((document.getElementById("createPassInput")).value)
};
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
success: function () {
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
});
}
$.ajax() in an asynchronous function. You need to use its success(result,status,xhr) callback to show actual success message.
What you are doing is show the success alert outside Ajax call.
The code should be:
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
success: function(html){
$("#results").append(html);
}
});
Your postData is an object does not need to so round in quotes "" and include a success call back and in success call back try to redirect on login page. Try this:
<script>
function submitInfo()
{
var postData = [{
firstName : document.getElementById("firstNameInput"),
lastName : document.getElementById("lastNameInput"),
username : document.getElementById("createUserInput"),
hashPass : MD5((document.getElementById("createPassInput")).value)
}];
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
success: function(response){
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
});
}
</script>
Basically you needs to get value of textboxs. And also in Ajax function you need to pass as a Object (Currently you are passing as String)
<script>
function submitInfo()
{
var postData = [{
firstName : document.getElementById("firstNameInput").value,
lastName : document.getElementById("lastNameInput").value,
username : document.getElementById("createUserInput").value,
hashPass : MD5(document.getElementById("createPassInput").value)
}];
$.ajax({
type: "POST",
url: "phpScripts/signup.php",
data: postData,
dataType: "text",
});
alert("Sign up Successful! Please log in to enter.");
window.open("login.php", "_self");
}
</script>
You need to change
data: "postData",
With
data: postData,
And add success variable after dataType: "text",
success: function(res){
if(res=="true"){
alert("Sign up Successful! Please log in to enter.");
}
else{
alert("something went wrong.");
}
}
and add this line in your php script after $stmt->execute($data);
$result=$stmt->execute($data);
if($result){
echo "true";
}
else{
echo "false";
}
In the below code I have a dropdown (id-name) which populated from listplace.php'. Also made another ajax call which when the dropdown item is selected it lists the specific product fromdataprod.php`
Problem: when I click on the specific item from drop-down it does not trigger the Ajax event
I checked the dataprod.php it works correctly, but even after binding the change event with my dropdown box I m not getting the result. Please help..
<select id="name">
<option selected disabled>Please select</option>
</select>
<?php if (isset($_GET['place']) && $_GET['place'] != '') { ?>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
$.ajax({
type: "POST",
data: {place: '<?= $_GET["place"] ?>'},
url: 'listplace.php',
dataType: 'json',
success: function (json) {
if (json.option.length) {
var $el = $("#name");
$el.empty(); // remove old options
for (var i = 0; i < json.option.length; i++) {
$el.append($('<option>',
{
value: json.option[i],
text: json.option[i]
}));
}
}else {
alert('No data found!');
}
}
});
</script>
<script>
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
</script>
<?php } ?>
dataprod.php
<?php
include("config.inc.php");
$name1 = $_POST['name1'];
$results = $mysqli_conn->query("SELECT product_name, product_desc, product_code,
product_image, product_price FROM products_list where product_name='$name1'");
$products_list = '<ul id ="products_list" class="products-wrp">';
while($row = $results->fetch_assoc()) {
$products_list .= <<<EOT
<li>
<form class="form-item">
<h4>{$row["product_name"]}</h4>
<div>
<img src="images/{$row["product_image"]}" height="62" width="62">
</div>
<div>Price : {$currency} {$row["product_price"]}<div>
</form>
</li>
EOT;
}
$products_list .= '</ul></div>';
echo $products_list;
?>
You need to pass the selected value in the ajax call.
change this line from
var name1 = this.value;
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
to
var name1 = this.value;
$.ajax ({
data: {name1: name1},
type: 'POST',
HTML:
you can store the values in hidden field like:
<input type='hidden' name='name1' id='name1' value='<?= $_GET["name1"] ?>'>
Javascript:
$(document.body).on('change',"#name",function (e) {
//doStuff
var name1 = $('#name1').val();
$.ajax ({
data: {name1: '<?= $_GET["name1"] ?>'},
url: 'dataprod.php',
success: function (response) {
console.log(response);
$('.products-wrp').html('');
$('.products-wrp').hide();
$('.products-wrp').html(response);
$('.products-wrp').show();
},
});
The jQuery autocomplete function brings the item from the database based on my typing word but result shows as just horizontal line of list. Attached image is showing how the result looks like.
HTML:
<form class="navbar-seach pull-center">
<div>
<input type="text" placeholder="Search Productstyle="width:550px; height:40px;padding-left: 10px;margin-top: 20px;" id="searchBox" onkeyup="if (event.keyCode === 13) {searchResults(this.value); this.value = '';}">
</div>
</form>
PHP:
include 'searchbox.php';
$switch_id = filter_input(INPUT_POST, 'switch_id', FILTER_SANITIZE_SPECIAL_CHARS);
if (isset($_POST['name_startsWith']))
$searchWordResults = $_POST['name_startsWith'];
else
$searchWordResults = null;
switch($switch_id){
case 1:
$userObj = new searchBox();
echo $userObj->autoComplete($searchWordResults);
break;
}
jQuery:
$("#searchBox").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
url: "class/searchbox_switch.php",
dataType: "json",
data: { name_startsWith: request.term, switch_id: 1 },
success: function(data) {
response($.map(data, function(item){
return {
label: item.label,
value: item.value
};
}));
},
error: function(response) {
console.log(response.responseText);
}
});
},
autoFocus: true,
minLength: 1,
select: function( event, ui ) {
searchResults(ui.item.label);
}
});
PHP (searchbox.php):
include '../dbConnect.php';
class searchBox {
public function autoComplete($name_startsWith) {
$letterSearch = $name_startsWith . "%";
$connectObj = new db_connect();
$dbh = $connectObj->connect();
$stmt = $dbh->prepare("SELECT product_name FROM products WHERE product_name LIKE :start");
$stnd = array();
$stmt->bindParam(':start', $letterSearch, PDO::PARAM_STR);
$stmt->execute();
$stnd = $stmt->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($stnd);
return $json;
}
}
OK got it. You are passing wrong key in your result. Your result data key is "product_name" And You are trying to access "label ". Try This solution:
success: function( data ) {
response( $.map( data, function(item) {
return {
label: item.product_name,
}
}));
},
My Ajax function does not return any result
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form >
</div>
</div>
$(document).ready(function(){
$("#ok").click(function() {
var login = $("#login").val();
var password = $("#password").val();
var dataString = 'login='+ login + '&password=' + password;
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userId= $row["id"];
$today=time();
$week=strftime('%W',$today) ;
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
}
The issue is because the button click is submitting the form in the standard manner, meaning your AJAX request is prevented from completing. It's better practice to hook to the submit event of the form.
Also note that your PHP code will never return 0, it would be better to have a error handler should the AJAX not complete as expected. Finally, your current code is wide open to attack; you should look in to using SSL and using prepared statements to avoid SQL injection.
That said, here's a fix for your AJAX issues:
<div id="container">
<div id="connexion">
<form id="myform" method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form>
</div>
</div>
$("#myform").submit(function(e) {
e.preventDefault(); // stop standard form submission
$.ajax({
type: "POST",
url: 'login.php',
data: {
login: $("#login").val(),
password: $("#password").val()
},
dataType: "json",
success: function(data) {
$('#errormess').html(data);
}
error: function() {
$('#errormess').html("problem");
}
});
});
I think you are giving the data parameter wrongly. It should be like
var dataString = {"login": login,
"password": password}
HTML
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password">
<br />
<input name="Submit" type="button" id="ok" value="OK" class="btn ">;
<br /> <br />
<span id="errormess"></span>
</form >
</div>
</div>
JS
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var login = $("#login").val();
var password = $("#password").val();
var dataString = {"login": login,
"password": password}
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
Also change the input type from submit to button and have and e.preventDefault() in your JS.
javascript code :
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var data = (this.form).serialize(); // added code
$.ajax({
url: 'login.php',
data: data,
dataType:'json',
type:'POST',
async:false,
success: function(data) {
if (data.success == 0) { // added code
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
},
error: function(data) { // if error occured
}
});
});//ok
});//document
php code :
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND
password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$userId = $row["id"];
$today = time();
$week = strftime('%W', $today);
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
} else { // added code
$arr = array("success" => '0');
echo json_encode($arr);
}
Please do check. I have modified the response from PHP as well as jquery code.
i have two function one is for delete and another for update . My delete function is working correctly but when i have written update function that is not working . Also update not working.
Here is the view
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
<script>
$(document).ready(function()
{
$('table#delTable td button.delete').click(function()
{
if (confirm("Are you sure you want to delete this row?"))
{
var id = $(this).parent().parent().attr('id');
var parent = $(this).parent().parent();
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/delete');?>",
data:'id='+id,
cache: false,
success: function()
{
parent.fadeOut('slow', function()
{$(this).remove();});
}
});
}
});
$('table#delTable tr:odd').css('background',' #FFFFFF');
});
function update(str){
var id=str;
var nm=$('#nm'+str).val();
var em=$('#em'+str).val();
var st=$('#st'+str).val();
var ph=$('#ph'+str).val();
var dp=$('#dp'+str).val();
var un=$('#un'+str).val();
var datas="id="+id+"&nm="+nm+"&em="+em+"&st="+st+"&ph="+ph+"&dp="+dp+"&un="+un;
$.ajax(
{
type: "POST",
url: "<?php echo base_url('Welcome/update');?>,
data:datas,
cache: false,
success: function(msg) {
alert(msg);
}
});
}
</script>
<button type="button" class="delete>Delete</button>
<button type="button" onclick="update(<?php echo $row['id']; ?>)">Save</button>
Controller
public function update(){
$id=$_POST['id'];
$userName=$_POST['nm'];
$tokens=explode("",$userName);
$fName=$tokens[0];
$lName=$tokens[1];
$userEmail=$_POST['em'];
$userUni=$_POST['un'];
$userState=$_POST['st'];
$userDept=$_POST['dp'];
$userPh=$_POST['ph'];
$array = array(
'first_name' => $fName,
'last_name' => $lName ,
'email' => $userEmail,
'phone_number' => $userPh,
'varsity_name' => $userUni,
'state' => $userState,
'dept_name'=> $userDept,
);
$this->load->model('Prime_Model');
$result=$this->Prime_Model->updateProfile($id,$array);
if($result){
return "Data has updated";
}
else{
return "Nothing";
}
}
You miss double quote after ?> below:
$.ajax({
type: "POST",
url: "<?php echo base_url('Welcome/update');?>", // here
data: datas,
cache: false,
success: function(msg) {
alert(msg);
}
});