how to get values from database phpmyadmin and show - php

i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?
this is my index.php
<script type="text/javascript" src="jquery-1.10.1.js"></script>
<form>
<h1>Insert Data Into mySQL Database</h1>
Name <input name="name" type="text" id="name"> <br><br>
Lastname <input name="lastname" type="text" id="lastname"><br><br>
Email <input name="email" type="text" id="email"><br><br>
<input type="button" name="Submit" value="Submit" onclick="insertData()">
</form>
<button type="button">get values</button>
<div id="jcontent"></div>
<script type="text/javascript">
/* * Checking the Login - * */
function insertData(){
var data_get = {
'name_form': $('#name').val().trim(),
'lastname_form': $('#lastname').val().trim(),
'email_form': $('#email').val().trim()
};
$.ajax({
url : 'insert_ac.php',
type : 'POST',
data : data_get,
timeout : 30000,
success : function(response_data, text, xhrobject) {
console.log(text);
if(text == "success"){
$('#jcontent').html('Data Inserted');
}
else if(text == "ERROR"){
$('#jcontent').html('data not inserted');
}
}
});
}
</script>
/*******************************************************/
this is my insert.php
<?php
mysql_connect('localhost','root','');
mysql_select_db('loginthree');
$table_name = "test_three";
$name_form=$_POST['name_form'];
$lastname_form=$_POST['lastname_form'];
$email_form=$_POST['email_form'];
$sql="INSERT INTO $table_name(name, lastname, email)VALUES('$name_form', '$lastname_form', '$email_form')";
$result=mysql_query($sql);
// if successfully insert data into database, displays message "Successful".
if($result){
echo "Success";
} else {
echo "ERROR";
}
?>
<?php
// close connection
mysql_close();
?>
i need all values from database if i click button(get values) how can
i ? please assist me any one
is there any way to do this ?

Well firstly, insert a:
return false;
at the end of your insertData() function, in that way you prevent the refresh of the page so that the ajax call can load its data.
Second you are returning Success and you are trying to read success, it's case sensitive and your code will not reach that if.
Resolve these issues and get back to me

Make a PHP script (lets name it getvalues.php) to return the values from the database into JSON, such as:
$result = mysql_query("SELECT * FROM $you_table"); //mod query to match what you need to fetch
$array = mysql_fetch_row($result);
echo json_encode($array);
Then in your script above include jQuery and use something along the lines of the following to retrieve the data:
$(function ()
{
$.ajax({
url: 'getvalues.php',
data: "",
dataType: 'json',
success: function ( values )
{
var value1 = values[0]; //value1, value2, etc should represent the field names in your database
var value2 = values[1];
//and so on and so forth. each field in you DB should be one index in your values array
$('#output').html("<b>Value 1: </b>"+value1+"<b> Value 2: </b>"+value2);
}
});
});

Related

store JSON values in input fields

hi i'm looking for some help
I'm learning how to use Ajax and PHP and what I want to do is to run a query in PHP and store the results in a JSON.
Then I want to echo the JSON and set it's values into text fields.
Is this possible?
Since I'm pretty new to Ajax and jQuery I'm not sure how to do this.
I attempted to do it, but I'm only getting the first value of the array.
This is my code:
<input type="text" id="text1">
<button type="button" class="btn btn-success" id="send">Success Button</button>
<input type="text" id="text2">
<input type="text" id="text3">
<input type="text" id="text4">
<script type="text/javascript">
$(document).ready(function(){
$("#send").click(function(event){
event.preventDefault();
var Rfc=$("#text1").val();
$.ajax({
type: 'POST',
url: 'search.php',
data: 'Rfc='+Rfc,
dataType : 'json',
success: function(msg){
var datashow = JSON.parse(msg);
$("#text2").val(msg[0].id_person); ///this is the only value that i get
$("#text3").val([1].person_name); ///i want to get the person's name here
$("#text4").val([2].person_address);///i want to get the person's address here
},
error : function () {
alert("error");
}
});
});
});
</script>
And this is my PHP file:
<?php
$rfc=$_POST['Rfc'];
$connection = mysqli_connect("localhost","root","","transferorders");
$query = mysqli_query($connection,"SELECT * FROM person where rfc_number ='$rfc'");
$Data = array();
while($row = mysqli_fetch_assoc($query)){
$Data[]=$row;
echo json_encode($Data);
}
?>
this is what i get in console
Uncaught TypeError: Cannot read property 'person_name' of undefined
at Object.success (test ajax1.php:40)
bro in the PHP file try to identify every variable in the array to catch them in the script, take a look at this:
<?php
$rfc=$_POST['Rfc'];
$connection = mysqli_connect("localhost","root","","transferorders");
$query = mysqli_query($connection,"SELECT * FROM person where rfc_number ='$rfc'");
$row = mysqli_fetch_array($query)
$Data = '{"id":"'.$row['id_person'].'", "name":"'.$row['person_name'].'", "address":"'.$row['person_address'].'"}';
echo json_encode($Data);
?>
and the script:
success: function(msg){
var datashow = JSON.parse(msg);
$("#text2").val(datashow["id"]); ///this is the only value that i get
$("#text3").val(datashow["name"]); ///i want to get the person's name here
$("#text4").val(datashow["address"]);///i want to get the person's address here
},
I hope it helps!

insert form values with database lookup without refreshing the page

I have a form with 5 fields.
Name
Last Name
Date of Birth
Occupation
Place of Birth
When user fills name and last name, I want the rest of the form to be filled from database without refreshing the page or user doing anything.
I am using php and jquery.
Here is my html page:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<input type="text" name="name" id="name">
<input type="text" name="lastname" id="lastname">
<input type="text" name="occupation" id="occupation">
<input type="text" name="date_of_birth" id="date_of_birth">
<input type="text" name="place_of_birth" id="place_of_birth">
<script type="text/javascript">
$('#lastname').blur(function ()
{
var name = $("#name").val();
var lastname = $("#lastname").val();
$.ajax({
url: "get.php",
type: "POST",
data: "name="+name+"&lastname="+lastname,
success: function(data)
{
if (data == "Error")
{
alert("error-1"+data);
}
else
{
var fields = data.split(",");
if (fields.length < 3)
{
alert("error-2"+data);
}
else
{
$("#occupation").val(fields[0]);
$("#date_of_birth").val(fields[1]);
$("#place_of_birth").val(fields[2]);
}
}
},
error: function(xhr, status, error)
{
alert("error-3"+data);
}
});
});
</script>
</body>
</html>
Here is the php page:
<?php
$name= $_REQUEST['name'];
$lastname= $_REQUEST['lastname'];
if($name == "mike" && $lastname = "brown")
{
echo "cook,1980-10-10,NYC";
}
?>
It works now.
-- Edit #1
Maybe this example can help you to understand how to use it:
$.ajax({
url: "phppage.php",
type: "POST", // Or get as you like
data: "name="+name+"&lastname="+lastname,
success: function(data)
{
// As i said, here in "data" you have what the server returned
// You can return the last field delimited with a , and do something like:
if (data == "Error")
{
// If something went wrong in your Database or invalid "name" or "last name"
// You can return "Error" in the PHP page so the Javascript know something is wrong
// and handle this error
}
else
{
var fields = data.split(",");
if (fields.length < 3) {
// As above.
// Something went wrong or invalid response
}
else
{
// In fields array you have what server said.
// Here you can reload the page, change page do what you want
}
}
},
error: function(xhr, status, error)
{
// Error here
}
});
It pass name and lastname to the server and wait for a response like:
field1,field2,field3
The PHP page should be something like..
<?php
// Connect to the server
// Send query to the server
if ($isEverythingOK) {
echo $field1 . "," . $field2 . "," . $field3;
}
else {
echo "Error";
}
?>
Ajax - jQuery Ajax + PHP page
A php page where you pass the 5 fields, add it in the database and return something like "OK" if everything is OK or an error if something went wrong.
Example
$.ajax({
url : "URL to PHP page",
success : function (data) {
if (data === "OK") { /* all ok, here you can update the page to show the new field */ alert("OK"); }
else { /* Error */ alert("Error"); }
},
error : function (xhr, status, error) {
// Request error
alert("Error");
}
});

php to jquery on form submit

i have this code which ask user to input value and submit.
html
<form id="myForm" method="post" action="saving.php">
<p><label for="input1">Input 1:</label>
<input type="text" size="10" name="input1" id="input1" />
</p>
<input id="save" name="save" type="submit" value="save" />
</form>
<p><span id="thevalue"></span><span id="existornot"></span></p>
js
$("#myForm").submit(function(event) {
event.preventDefault();
$("#myForm").validate(
{ rules: {input1: "required",},
messages: {input1: "message error input"},
});
if( $("#myForm").valid()){
var $form = $("#myForm" ),
url = $form.attr( "action" ),
insertedVal=$("#input1").val();
$.post(url,{input1:insertedVal},
function(){
//displaying value condition
$("#thevalue").html(insertedVal);
// ... msg from php to be inserted to #existornot
});
}
});
saving.php
<?php
if(!empty($_POST['input1']))
{
$inputone= mysql_real_escape_string(trim($_POST['input1']));
$result = mysql_query("SELECT COUNT(*) FROM `test_table` WHERE `name` = '$inputone' ");
if (mysql_result($result, 0, 0) > 0)
{
echo "is duplicate data" ;
}
else
{
mysql_query("INSERT INTO `test_table`(name) VALUES ('$inputone')") ;
echo "is updated to db" ;
}
}
else
{
echo "could not be empty" ;
}
?>
How to pass those message of 'is duplicate data' or ' is updated to db' from the php to the javasript, to tell user that the submit process is fail or success ?
Thanks in advance for any advice.
Change the function call after the jQuery post to accept the data variable and process the results:
$.post(url,{input1:insertedVal},
function(data){
//displaying value condition
$("#thevalue").html(insertedVal);
// ... msg from php to be inserted to #existornot
if (data != 'is updated to db') {
alert(data);
}
});
}
(Data will contain what has been echoed in your save function)
The response from php file is in the ajax callback function. so you should add a parameter to your function like this:
$.post(url,{input1:insertedVal},function(resp)
{
// resp is the callback from php.
console.log(resp);
$("#thevalue").html(insertedVal);
});
For more information that how ajax works, you can follow this link: 5 Ways to Make Ajax Calls with jQuery
hope to help.
Like this:
$.post(url,{input1:insertedVal},
function(data){
//displaying value condition
$("#thevalue").html(insertedVal);
// ... msg from php to be inserted to #existornot
$("#existornot").html(data);
});
}
By adding the "data" variable to the callback function(), that "data" variable will be updated with whatever php echo's as output. You can then insert that "data" into #existornot in the callback function.
Please see the API here: http://api.jquery.com/jQuery.post/
If you want to print the value returned from php please check the jquery $.post
$.post(url,{input1:insertedVal},
function(data){
//displaying value condition
$("#somediv_id").html(data);
$("#thevalue").html();
// ... msg from php to be inserted to #existornot
});
The $.post callback function will be passed a argument containing the server response. So your $.post request should look like
$.post(url, {input1: insertedVal}, function(response) {
console.log(response); // should output the server message echoed.
});
It's also usually best to use JSON as a server response.

How can I check duplicate username in a form without posting form and set focus on username if it already exists?

I have a form to filled out by user. Its user registration form. I want that when user fill username text,my form should search for user name whether it exist or not.If it exist then username text field should get focus.My database table name is users and it contains column named as id,username,password,status.
Here is my code.
<form name="user" action="#" method="post">
<label>Username</label>
<input type="text" maxlength="25" name="username" />
/*here i want to check from my db table weather username exists or not*/
<label>Password</label>
<input type="password" maxlength="25" name="password" />
<input type="submit" value="Submit" />
</form>
I can do it when user submits the form.But my requirement is to check value with out submitting form and username should get focus.
and in php I have following code
<?php
mysql_connect("localhost","root","") or die(mysql_error());
mysql_select_db("test") or die(mysql_error());
$username = $_REQUEST['username'];
$query=mysql_query("SELECT * from user where name='$username'");
$row=mysql_num_rows($query);
if($row==1){
echo "true";
} else {
echo "false";
}
?>
Make an ajax request to a server side script of yours that does the check on the database and returns something you can intepret. Then act on it on the ajax success response (focusing the field).
There are thousands of examples of this online. Check #danish hashmi 's example ( http://blog.webwizo.com/2011/06/03/check-username-availability-in-php-with-jquery-ajax/) or google it for more.
Html Form
<form method="post" action="register.php">
......
<label for="username">Username</label>
<input type="text" maxlength="25" name="username" id="username">
......
</form>
Js
<script src="jquery-1.8.0.min.js"></script>
<script>
$(document).ready(function(){
$('#username').keyup(check_username); //use keyup,blur, or change
});
function check_username(){
var username = $('#username').val();
jQuery.ajax({
type: 'POST',
url: 'check_username.php',
data: 'username='+ username,
cache: false,
success: function(response){
if(response == 0){
alert('available')
}
else {
alert('not available')
//do perform other actions like displaying error messages etc.,
}
}
});
}
</script>
write your table user name checking in check_username.php , the response from this php is count of rows with the provided username,something like below
<?php
/*** mysql hostname ***/
$hostname = 'localhost';
/*** mysql username ***/
$username = 'username';
/*** mysql password ***/
$password = 'password';
/*** mysql databse ***/
$dbname = 'database';
try
{
$dbh = new PDO("mysql:host=$hostname;dbname=mysql", $username, $password);
/*** echo a message saying we have connected ***/
//echo 'Connected to database';
}
catch(PDOException $e)
{
echo $e->getMessage();
}
$stmt = $dbh->prepare("SELECT * FROM user where name = ?");
$stmt->execute(array($_POST['username']));
echo $stmt->rowCount();
?>
I'm thinking of you binding checking for existence of user on keyup event of your name="username" field (should give an id to that). do you use jquery or any other library for js?
It would be much simpler to achieve what you're planning to do with using libraries.
To do so you can set textbox on change event and pass textbox value to ajax call like below.
input type="text" id="username"
Now in js file add below code.
$(document).ready(function(){
$(#username).change(function(e)
{
e.preventDefault();
$.ajax({
url : 'youphpfile.php?username='+$(#username).val();,//or $(#username).attr('value')
dataType: 'json',
success : function()
{}
});
});
});
now in youphpfile.php file do checking for sended username parameter.
$username = $_REQUEST['username']; // $_GET['username']; get will be good for faster response.
mysql_connect
and check username
And you done.
Cheers.
You will probably need a web service to check if the username exists and when the username field loses focus, make an ajax call to the service using jQuery.
$(document).ready(function(){
$('input[name="username"]').blur(function(){
var txt = $(this);
var username = txt.val();
$.ajax({
type: "POST",
url: "myUsernameService.php",
data: { uname: username }
}).done(function(res) {
if (res == "false"){
txt.removeClass("valid").addClass("invalid");
} else {
txt.removeClass("invalid").addClass("valid");
}
});
});
});
I wouldn't suggest focusing on the username textbox again as the AJAX call can take a couple of seconds to return a value, at which point the user might be busy typing in another field.
The above code assumes that you have a method on "myUsernameService.php" that accepts one variable called "uname" and returns a string of "true" or "false".

Ajax Form Sometimes Works, Sometime works and refreshes, Sometimes refreshes and fails ... Bwah?

I've got an ajax form that seems to be very varied in its response. Sometimes it works, sometimes it refreshes but the data is still stored and sometimes if fails all together, and I can't seem to figure out why.
The Form
<form >
<label>Name</label>
<input id="textname" type="text"/><br/>
<label>Message</label>
<textarea id="textmsg"></textarea><br/>
<label> </label>
<input type="submit" value="Send" onclick="return textin();"/><br/><br/>
<label id="textresult"></label>
</form>
Jquery
function textin() {
var name = $("input#textname").first().attr("value");
var msg = $("textarea#textmsg").first().attr("value");
if (msg==null || msg=="")
{
alert("Message cannot be Blank");
return false;
};
$.ajax({
url: '<?=BASEURL?>/le-include/textin.php',
cache: false,
type: "POST",
data: {name : name, msg : msg},
success: function (data) {
$('#textname').attr('value', '');
$('#textmsg').attr('value', '');
$('#textresult').html(data);
$('#textresult').animate({ backgroundColor: $.Color( "rgba(2,232,87,1)" ), color: $.Color( "rgba(0,0,0,1)" ) });
$('#textresult').animate({ backgroundColor: $.Color( "rgba(0,0,0,0)" ), color: $.Color( "rgba(0,0,0,0)" ) });
}
})
};
textin.php
$name = $_POST['name'];
$name = mysql_real_escape_string($name);
$msg = $_POST['msg'];
$msg = mysql_real_escape_string($msg);
$ip = $_SERVER["REMOTE_ADDR"];
databaseSelect("$database");
$sql = "SELECT `ip` FROM `spamip` WHERE ip='$ip' LIMIT 1";
$result = mysql_query($sql);
if(mysql_error()) { print mysql_error(); print '<br/>'; };
$num = mysql_num_rows($result);
if($num == 0) {
$date = date_create();
$stamp = date_format($date, 'U');
$sql = "INSERT INTO `texts` (`name`, `message`, `date`, `ip`) VALUES ('$name', '$msg', FROM_UNIXTIME('$stamp'), '$ip');";
$result = mysql_query($sql);
if(mysql_error()) {
echo "Error";
} else {
echo "Success"; }
} else {
echo "Your IP has been marked as Spam";
}
HTML should be:
<form onsubmit="return textin();">
<label>Name</label>
<input id="textname" type="text"/><br/>
<label>Message</label>
<textarea id="textmsg"></textarea><br/>
<label> </label>
<input type="submit" value="Send"/><br/><br/>
<label id="textresult"></label>
</form>
because otherwise think about what will happen when you press enter while you have focus on text box with id textname
jQuery should be:
function textin() {
var name = $("input#textname").first().attr("value");
var msg = $("textarea#textmsg").first().attr("value");
if (msg==null || msg=="")
{
alert("Message cannot be Blank");
return false;
};
$.ajax({
url: '<?=BASEURL?>/le-include/textin.php',
cache: false,
type: "POST",
data: {name : name, msg : msg},
success: function (data) {
$('#textname').attr('value', '');
$('#textmsg').attr('value', '');
$('#textresult').html(data);
$('#textresult').animate({ backgroundColor: $.Color( "rgba(2,232,87,1)" ), color: $.Color( "rgba(0,0,0,1)" ) });
$('#textresult').animate({ backgroundColor: $.Color( "rgba(0,0,0,0)" ), color: $.Color( "rgba(0,0,0,0)" ) });
}
});
return false;
};
because otherwise the form will be posted normally and not with ajax.
Additional information:
.attr("value") can be replaced in the short command .val()
and
.attr("value", "") can be replaced in the short command .val("")
Impotent! I don't know if you don't want to but you don't check if there is a name given.
You can check with error: function() {} if the internet connection is down or something else happened and give the user an error message.
Check in PHP if the data is send (isset($var)) because otherwise maybe someone is playing around with your website and go to the page and get error messages and that wouldn't be nice.
The answer was given above but let me just add the best way to do something like that is return false. When you return false you will stop the form from submitting (in case of an error).
So let's say I have a form, frmMain; we click a button, it has to do some validation and if successful retrieve some input from the server via AJAX and then post the form. In the jscript ajax function I will call AJAX server.php but also return FALSE to onsubmit (the form). This will stop the form from executing. When AJAX server.php sends back a reply, if it's the correct reply, then in jscript I put frm.submit, or in other words post the form after ajax has returned something. But note, when the form do posts, its done from jscript/after ajax has completed successfully.
Hope this was helpful.

Categories