Issue with using ajax to update without refresh - php

I have this code here which is supposed to help me update a phone number.
It doesn't do it though, well, i get the successfully changed message but no insertion on the database.
Here is my code:
index.php
<script type="text/javascript" >
$(function() {
$(".submit").click(function() {
var phone = $("#phone").val();
var dataString = 'phone='+ phone ;
if(phone=='') {
$('.success').fadeOut(200).hide();
$('.error').fadeOut(200).show();
} else {
$.ajax({
type: "POST",
url: "update-phone.php",
data: dataString,
success: function() {
$('.success').fadeIn(200).show();
$('.error').fadeOut(200).hide();
}
});
}
return false;
});
});
</script>
<div class="modal" style="display: none;">
<?php
if (empty($phone)) {
?>
<form method="post" name="form">
<input id="phone" name="phone" type="text" />
<div>
<input type="submit" value="Submit" class="submit"/>
<span class="error" style="display:none"> Please Enter Valid Data</span>
<span class="success" style="display:none"> Registration Successfully</span>
</div>
</form>
update-phone.php
<?php
require_once('db.php');
if($_POST) {
$phone = $_POST['phone'];
mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
}else {}
?>
What am i missing?
Thanks

Try this..
<?php
require_once('db.php');
if($_POST) {
$phone = $_POST['phone'];
mysql_query("UPDATE `users` SET `phone` = '$phone' WHERE `ID` = 5884 ");
}else {}
?>

Have you tried inspecting the ajax request with firebug/developer tools/etc?
Try adding echo mysql_error(); right after your mysql_query.
Not 100% sure but it could be the if ($_POST) should be replaced with if (isset($_POST['phone']))
Try the following php:
<?php
require_once('db.hp');
if (isset($_POST['phone']))
{
$phone = $_POST['phone'];
mysql_query("UPDATE users SET phone = '$phone' WHERE ID = 5884 ");
echo mysql_error();
}
else
{
echo "Failed";
}
?>
EDIT: Have you confirmed if it actually updates the DB?
Also you should also sanitise your input and consider rolling with mysqli instead of mysql_*

Related

jQuery(AJAX) post to php issue when I try to insert data into DB

when I echo the php variable it work properly , but when I try to insert the data into database it doesn't work , what is the solution please I get stuck
I got this error on console
POST http://localhost/validate.php 500 (Internal Server Error)
send # jquery-3.1.1.min.js:4
ajax # jquery-3.1.1.min.js:4
(anonymous) # jquery.PHP:26
dispatch # jquery-3.1.1.min.js:3
q.handle # jquery-3.1.1.min.js:3
HTML/JQUERY
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
<script>
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val();
var age = $('#age').val();
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
</script>
PHP
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
mysqldb.php
<?php
$conn = mysql_connect('localhost', 'root', 'password' , 'datab');
if (!$conn) {
die("Connection failed: ".mysqli_connect_error());
}
?>
Please add the details of the error message you get.
Make little changes to your code so that it can show the query error if any
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "INSERT INTO `uss` (`first`, `last`) VALUES('{$name}','{$age}')";
if($conn->query($sql))
{
echo "Record inserted";
}
else
{
echo $conn->error;
}
?>
Sugesstions: Your query have the chances of the SQL Injection. Make it secure.
if you are using ajax , try the following,
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit" id="submit">
</form>
<div id="result"></div>
$("#submit").click(function(){
var name = $('#name').val(); // getting name
var age = $('#age').val();
$.ajax({
url : "validate.php",
type: "POST",
data: {name:name, age:age},
success: function(data)
{
$("#result").html(data);
}
});
});
in your controller function,echo the result
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
$sql = "insert into uss (first, last) values('$name','$age')";
$result = $conn->query($sql);
echo $result;
?>
jQuery Ajax
Form with id myFrom
<form action="" id="myForm">
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="submit" value="Submit">
</form>
<div id="result"></div>
jQuery Ajax section
$(function() {
$("#myForm").submit(function(e) {
e.preventDefault();
var name = $('#name').val(); // getting name
var age = $('#age').val(); // getting age
/* Ajax section */
$.ajax({
url: 'validate.php',
method: 'POST',
data: {postname:name, postage:age},
success: function(res) {
$("#result").append(res);
}
});
});
});
validate.php
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
$sql = "insert into uss (first, last) values('".$name."','".$age."')";
$result = $conn->query($sql);
echo $result ;
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<form >
<input type="text" id="name" ><br/>
<input type="text" id="age" ><br/>
<input type="button" value="Submit" onclick="postdata();">
</form>
<div id="result"></div>
<script type="text/javascript">
function postdata() {
alert("ashad");
var name = $('#name').val();
var age = $('#age').val();
$.post('validate.php',{postname:name,postage:age},
function(data){
$('#result').html(data);
});
}
</script>
<?php
include 'mysqldb.php';
$name = $_POST['postname'];
$age = $_POST['postage'];
//check ajax response by `echo $name` and `$age`
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
} else
{
$sql = "insert into uss(first, last) values('$name','$age')";
$result = $conn->query($sql);
}
echo $result ;
?>

How to check if jquery ajax send POST request or not?

I have created a simple Login Register program using PHP.
Now I am trying to validate if username already exists or not using jquery ajax. The jquery code runs but keeps on showing 'Checking Availability'.
Here is the code I have used. Please ignore the vulnerability and other errors in my PHP code ( which may not affect jquery ajax process ) as I am new to this. I'm working for improving those things.
Register.php
<?php
include('config.php');
if(isset($login_session))
{
header("Location: login.php");
}
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
$username = mysqli_real_escape_string($obj->conn,$_POST['username']);
$password = mysqli_real_escape_string($obj->conn,$_POST['password']);
$name = mysqli_real_escape_string($obj->conn,$_POST['name']);
$email = mysqli_real_escape_string($obj->conn,$_POST['email']);
$password = md5($password);
$sql ="SELECT uid from users WHERE username = '$username' or email = '$email'";
$register_user = mysqli_query($obj->conn,$sql) or die(mysqli_error($sql));
$no_rows = mysqli_num_rows($register_user);
if($no_rows == 0)
{
$sql2 = "INSERT INTO users(username, password, name, email) values ('$username', '$password', '$name', '$email')";
$result = mysqli_query($obj->conn, $sql2) or die(mysqli_error($sql2));
echo "Registration Successfull!";
}
else{
echo "Registration Failed.";
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Register</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/username.js"></script>
</head>
<body>
<form action="register.php" method="post">
<label>UserName:</label>
<input type="text" id="username" name="username" required/>
<span id="status"></span><br />
<label>Password :</label>
<input type="password" name="password" required/><br/>
<label>Full Name :</label>
<input type="text" name="name" required/><br/>
<label>Email :</label>
<input type="email" name="email" required/><br/>
<input type="submit" value=" Submit "/><br />
</form>
</body>
</html>
username.js
$(document).ready(function()
{
$("#username").change(function()
{
var username = $("#username").val();
var msgbox = $("#status");
if(username.length > 3)
{
$("#status").html('<img src="img/loader.gif" align="absmiddle"> Checking availability...');
$.ajax({
type: "POST",
url: "php/username-check.php",
data: "username="+ username,
success: function(msg){
$("#status").ajaxComplete(function(event, request){
if(msg == 'OK')
{
msgbox.html('<img src="img/yes.png" align="absmiddle"> <font color="Green"> Available </font> ');
}
else
{
$("#username").removeClass("green");
$("#username").addClass("red");
msgbox.html(msg);
}
});
}
});
}
else
{
$("#status").html('<font color="#cc0000">Enter valid User Name</font>');
}
return false;
});
});
username-check.php
<?php
include("config.php");
if(isSet($_POST['username']))
{
$username = $_POST['username'];
$username = mysqli_real_escape_string($obj->conn,$username);
$sql = "SELECT username FROM users WHERE username='$username'";
$sql_check = mysqli_query($obj->conn,$sql);
if (!$sql_check)))
{
echo 'could not complete query: ' . mysqli_error($obj->conn,$sql_check);
}else{
echo 'query successful!';
}
if(mysqli_num_rows($obj->conn,$sql_check))
{
echo '<font color="#cc0000"><b>'.$username.'</b> is already in use.</font>';
}
else
{
echo 'OK';
}
}
?>
and I want to know if there is a way to check if jQuery Ajax sent the POST request to that file or not?
You are confusing ajax functions...Syntax will be like this
$.ajax({
url: url,
data: data,
type: "POST",
beforeSend: function () {
},
success: function (returnData) {
},
error: function (xhr, ajaxOptions, thrownError) {
},
complete: function () {
}
});
Examine the request using a browser utility
- Launch the chrome browser
- Right click and select inspect element menu
- click on Network tab
- Load your URL
- Perform the Ajax request
- You can see the request here (new request will be last in the list).
- Click on it
- Right side window shows you request and response data
You did correct.Easy way to check them is use firebug tool on your browser...I recommend firefox with firebug.install it first and then open it before you post your form.then goto console log and send your form...Check it out,best software.

Ajax Post with PHP and MySQL

Im trying to post data to mysql by using PHP and Ajax, the only thing problem that data does not enter into database it so the problem seems in the javascript which i think ajax please help me.
Please there some one can fix it if there any error on code?
FORM:
<form id="contactForm" action="ajax.php" method="post">
<input name="name" id="name" type="text"/>
<input name="email" id="email" type="text"/>
<input type="button" value="Send" name="submit" id="submit" />
<span id="error" class="warning">Message</span></p>
</form>
<p id="sent-form-msg" class="success">Thanks for your comments.We will update you within 24 hours. </p>
JS:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
// on submit...
$("#contactForm #submit").click(function() {
$("#error").hide();
var name = $("input#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
return false;
}
var email = $("input#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
var dataString = 'name=' + name + '&email=' + email;
$.ajax({
type:"POST",
data: dataString,
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
return false;
});
AJAX.php
$con=mysqli_connect("localhost","admin","admin","test");
$name = mysqli_real_escape_string($con, $_POST['name']);
$email = mysqli_real_escape_string($con, $_POST['email']);
$sql="INSERT INTO test (name, email) VALUES ('$name', '$email')";
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
echo "1 record added";
mysqli_close($con);
Thank you in Advance.
You must include the URL you want to POST to in the AJAX call.
$.ajax({
url: "ajax.php",
type:"POST",
data: dataString,
success: success()
});
Here is what I suggest doing:
HTML:
<input name="name" id="name" type="text"/>
<input name="email" id="email" type="text"/>
<input type="button" value="Send" onclick="validate();" id="submit" />
<span id="error" class="warning">Message</span></p>
<p id="sent-form-msg" class="success">Thanks for your comments.We will update you within 24 hours. </p>
Javascript:
jQuery(document).ready(function($){
// hide messages
$("#error").hide();
$("#sent-form-msg").hide();
}
// on submit...
function validate()
{
$("#error").hide();
var name = $("#name").val();
if(name == ""){
$("#error").fadeIn().text("Name required.");
$("input#name").focus();
}
var email = $("#email").val();
if(email == ""){
$("#error").fadeIn().text("Email required");
$("input#email").focus();
return false;
}
// var dataString = 'name=' + name + '&email=' + email;
$.ajax({
url: "phpScript.php"
type:"POST",
data: {name:name, email:email},
success: success()
});
});
// on success...
function success(){
$("#sent-form-msg").fadeIn();
$("#contactForm").fadeOut();
}
}
PHP:
$con = mysqli_connect("localhost","admin","admin","test");
$name = $_POST['name'];
$email = $_POST['email'];
$sql = "INSERT INTO test (name, email) VALUES ('$name', '$email')";
//I like to do it like this:
$result = mysql_query($query, $connect);
/*if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}*/
echo "1 record added";
mysqli_close($con);
I give credit also to the other answer by mattmemo. The thing he corrected was definitely a mistake. I think there may have been other mistakes in MARGELANI's script so I chose to post my answer as well. If this script doesn't work let my know and I will recode it. Good luck! :D

jQuery AJAX shown form validation errors

I got problem with shown validation error on below script, for example what I tested, I enter a correct email and wrong password, the request will returned both Wrong email address and Wrong password under each input textbox, it is not only Wrong Password is expected to shown, I tried hardcode required data in request.php and run this script directly, for either giving wrong data in in $_POST, the console response {"error":{"lemail":"Wrong email address","lpassword":"Wrong password"}}, can someone please have a look in my code what's goes wrong?
form with AJAX call:
<body>
<form role="form" method="post" id="login_form" enctype="multipart/form-data">
<div class="modal-body">
<div class="form-group">
<label for="email">Email</label>
<input type="email" class="form-control" id="lemail" name="lemail" placeholder="Your email"><span class="error" id="lemail_error"></span>
</div>
<div class="form-group">
<label for="password">Password</label>
<input type="password" class="form-control" id="lpassword" name="lpassword" placeholder="Password"><span class="error" id="lpassword_error"></span>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-success" id="btn_login" data-loading-text="Loading...">Sign In</button>
</div>
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#btn_login').click(function(){
var parameters = $('#login_form').serialize();
$.ajax({
url: 'inc/callback/request.php',
type: 'POST',
data: {'parameters' : parameters},
dataType: 'json',
success: function(response){
if(response.success == 'logged'){
$('#login_form')[0].reset();
alert(response.success);
}else if(response.inactivate == 'inactive'){
alert('Your account is inactive!');
}else{
$('[id$="_error"]').html(''); //clear valid error msg
// display invalid error msg
$.each(response.error, function(key, value){
if(value){
$('#' + key + '_error').html(value);
}
});
}
},
error: function(){
console.log(arguments);
}
});
});
});
</body>
request.php
parse_str($_POST['parameters'], $output);
$email = $mysqli->real_escape_string(strtolower(trim($output['lemail'])));
$password = $mysqli->real_escape_string(trim($output['lpassword']));
$func = new Functions();
$message = array();
//validate user's email and password from database
$check = $mysqli->query("SELECT * FROM `users` WHERE user_email='".$email."' AND user_password='".sha1(sha1($password))."'") or die($mysqli->error);
$rows = $check->fetch_array(MYSQLI_BOTH);
$num = $check->num_rows;
$uId = $rows['user_id'];
$uEmail = $rows['user_email'];
$uPwd = $rows['user_password'];
$uType = $rows['account_type'];
$uStatus = $rows['account_status'];
// validate user's account
if(empty($email) || $email !== $uEmail){
$message['error']['lemail'] = 'Wrong email address';
}
if(empty($password) || sha1(sha1($password)) !== $uPwd){
$message['error']['lpassword'] = 'Wrong password';
}
if(!isset($message['error'])){
if($uStatus == 0){
$message['inactivate'] = 'inactive';
}else{
$message['success'] = 'logged';
}
}
echo json_encode($message);
Edited:
Solved! nothing went wrong, just out of logic on variables comparison!! ;P
in you php code first you have to deserliazed ur code.. put these lines at top..
$searcharray = array();
parse_str($_POST[parameters], $searcharray);
$email = $mysqli->real_escape_string(strtolower(trim($searcharray['lemail'])));
$password = $mysqli->real_escape_string(trim($searcharray['lpassword']));
You are posting string not array, you need to use parse_str function first.
Remove this enctype="multipart/form-data" from form
<form role="form" method="post" id="login_form">
Replace your data: line with this
data: {'parameters' : parameters},
After add this to your PHP
parse_str($_POST['parameters'], $output);
$email = $mysqli->real_escape_string(strtolower(trim($output['lemail'])));
$password = $mysqli->real_escape_string(trim($output['lpassword']));

How to display search results live

Here i have simple search engine to search usernames. when people type username i want them to see results below search box and have them taken to search page only after they hit enter (like facebooks search engine).
html
<div class="search">
<form action="search.php" method="GET">
<input type="text" name="Search" size="50">
<input type="submit" value="Search">
</form>
</div>
php (search.php)
<?php
require 'includes/connection.php';
$term = $_GET['Search'];
$query_ver = "select * from Members where Name like '%$term%'";
$query = mysqli_query($dbc, $query_ver);
while($row = mysqli_fetch_array($query)) {
$name = $row['Name'];
}
echo $name;
?>
so is there a way to display $name below search box only with php and html
HTML
<div class="search">
<form action="search.php" method="GET">
<input type="text" name="search" size="50" class="search">
<input type="submit" value="Search">
</form>
</div>
Javascript
<script type="text/javascript" src="jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(function(){
$(".search").keyup(function()
{
var searchid = $(this).val();
var dataString = \'search=\'+ searchid;
if(searchid!=\'\')
{
$.ajax({
type: "POST",
url: "result.php",
data: dataString,
cache: false,
success: function(html)
{
$("#result").html(html).show();
}
});
}return false;
});
jQuery("#result").live("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find(\'.name\').html();
var decoded = $("<div/>").html($name).text();
$(\'#searchid\').val(decoded);
});
jQuery(document).live("click", function(e) {
var $clicked = $(e.target);
if (! $clicked.hasClass("search")){
jQuery("#result").fadeOut();
}
});
$(\'#searchid\').click(function(){
jQuery("#result").fadeIn();
});
});
</script>
search.php
<?php
include('db.php');
if($_POST)
{
$q = mysql_real_escape_string($_POST['search']);
$strSQL_Result = mysql_query("select id,name,email from live_search where name like '%$q%' or email like '%$q%' order by id LIMIT 5");
while($row=mysql_fetch_array($strSQL_Result))
{
$username = $row['name'];
$email = $row['email'];
$b_username = '<strong>'.$q.'</strong>';
$b_email = '<strong>'.$q.'</strong>';
$final_username = str_ireplace($q, $b_username, $username);
$final_email = str_ireplace($q, $b_email, $email);
?>
<div class="show" align="left">
<img src="https://fbcdn-sphotos-e-a.akamaihd.net/hphotos-ak-prn1/27301_312848892150607_553904419_n.jpg" style="width:50px; height:50px; float:left; margin-right:6px;" /><span class="name"><?php echo $final_username; ?></span> <br/><?php echo $final_email; ?><br/>
</div>
<?php
}
}
?>
for reference here is good solution
LINK1
LINK2

Categories