Using AJAX and JSON to display HTML content from PHP - php

I am trying to retrieve information from my php file which contains the following code. My code contains the colums Email, FirstName, LastName, and State.
$query = 'SELECT * FROM users WHERE LOWER(Email) = :email';
$stmt = $dbh->prepare($query);
$stmt->bindValue(':email', $email);
$stmt->execute();
if ($stmt->rowCount() == 1) {
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$firstName = $row['FirstName'];
$lastName = $row['LastName'];
$state = $row['State'];
} echo json_encode($row);
My Ajax code is:
$.ajax({
datatype: 'json',
type: "POST",
url: 'json-data.php',
success: function(data) {
//called when successful
$('#firstname').append(data.FirstName);
},
error: function(e) {
//called when there is an error
//console.log(e.message);
}
});
When I type $('#firstname').append(data);, it shows me the following output:
{"FirstName":"Foo","LastName":"Bar","State":"Florida","Email":"foo#bar.com"}
How do I make it so I can get only the first name and append it to a div?

try with:
var obj = jQuery.parseJSON(data);
$('#firstname').append(OBJ.FirstName);

Related

Returning AJAX Success and Error

I have built a login script that uses AJAX to submit form data.
The PHP part works fine without AJAX. But the system doesnt work with AJAX Implementation.
It always Displays the below message even though the PHP file returns true[correct username & password] ... Seems like the if condition in Jquery is not working.
Incorrect Username/Password
HTML Result Div
<div id="user-result" align="center"></div>
Jquery
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data == "true") {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>
fn_login.php
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo "true";
}
else {
die();
}
}
}
?>
Can someone please point out the mistake in the code/practice.
EDIT
Just Tried disabling AJAX, the PHP file works correctly echoing true when username/pass is correct
You have spaces after ?>
So, the AJAX response is having spaces after true.
Solution:
Remove ?> from the end of PHP file.
It will not affect any PHP functionality.
And you AJAX response will be without spaces.
Excluding closing tag ?> from the end of PHP file is standard practice for modern PHP frameworks and CMSs.
Tips for debugging AJAX:
1) Always use Firefox (with Firebug Add) on Or Chrome.
2) Use Console tab of Firebug, to check which AJAX requests are going.
3) Here, you can see input parameters, headers and most important response.
4) So, in short you can debug a whole AJAX request life cycle.
You can echo json_encode(array('success'=>true)) from php code and modify your if condition in jquery with if(data.success){} Your modified code becomes
<?php
{
session_start();
include_once 'db_connect.php';
if (isset($_POST))
{
$email = filter_input(INPUT_POST, 'email', FILTER_SANITIZE_STRING);
$logpwd = filter_input(INPUT_POST, 'password', FILTER_SANITIZE_STRING);
$stmt = $conn->prepare("SELECT password FROM manager WHERE email = ? LIMIT 1");
$stmt->bind_param("s", $email);
$stmt->execute();
$stmt->store_result();
// get variables from result.
$stmt->bind_result($password);
$stmt->fetch();
// Check if a user has provided the correct password by comparing what they typed with our hash
if (password_verify($logpwd, $password))
{
$sql = "SELECT * from manager WHERE email LIKE '{$email}' LIMIT 1";
$result = $conn->query($sql);
$row=mysqli_fetch_array($result);
$id = $row['id'];
$conn->query("UPDATE manager SET lastlogin = NOW() WHERE id = $id");
$_SESSION['manager_check'] = 1;
$_SESSION['email'] = $row['email'];
$_SESSION['fullname'] = $row['fullname'];
$_SESSION['designation'] = $row['designation'];
$_SESSION['id'] = $row['id'];
echo json_encode(array('success'=>true));
}
else {
die();
}
}
}
AND JQuery becomes
<script type="text/javascript">
$(document).ready(function () {
var form = $('#loginform');
form.submit(function (ev) {
ev.preventDefault();
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
cache: false,
data: form.serialize(),
success: function (data) {
if (data.success) {
$("#user-result").html("<font color ='#006600'> Logged in | Redirecting..</font>").show("fast");
setTimeout(
function () {
window.location.replace("index.php");
}, 1500);
} else {
$("#user-result").html("<font color ='red'> Incorrect Username/Password</font>").show("fast");
}
}
});
});
});
</script>

json check empty data

I would check if my JSON response (data) is empty
$.ajax ({
type : 'POST',
url : get.php,
dataType: 'json',
success : function(data) {
console.log(data.lenght);
}
});
GET.PHP
$query = "SELECT * FROM TABLE";
$stmt = $this->db->mysqli->prepare($query);
$stmt->execute();
$result = $stmt->get_result();
$_assoc = array();
while($row = $result->fetch_array(MYSQLI_ASSOC)) {
$_assoc = $row;
}
$stmt->close();
echo json_encode($_assoc);
JSON RESPONSE
{"foo":"6","bar":"3436","id":4,"code":""}
EMPTY JSON RESPONSE
[]
I tried with data.length but returned undefined.
UPDATE
I solved this way.
Object.keys(data).length
Thanks for yours downvote!

Get URL Parameter with PHP for Mysqli database search

I'm trying to work out how to get the parameter from a URL with PHP.
So my code starts with a bit of ajax firing the php and an alert with the response:
$.ajax({
url: 'blog/assets/php/load-blog.php',
dataType: 'json',
success: function(data){
alert(data);
}
});
Then I have my php:
<?php
//==== CONNECTION VARIABLE
$con = new mysqli($host,$user,$pass,$database);
//==== GET URL PARAMETER
$urlParam = $_GET["date"];
//==== FETCH DATA
$result = $con->query("SELECT * FROM $table WHERE DATE = '$urlParam'");
//==== CREATE ARRAY
$blogArray = array();
while ($row = $result->fetch_row()) {
$blogArray[] = $row;
}
//==== ECHO AS JSON
echo json_encode($blogArray);
?>
The URL would look something like this:
http://www.mysite.com/blog/?date=2013-05-14
The issue in all of this is the URL parameter isn't being selected correctly but I don't know what I've done wrong.
Javascript
var date = '2013-05-14';
$.ajax({
type: "GET",
url: 'blog/assets/php/load-blog.php',
dataType: 'json',
data: { date: date }
success: function(data){
alert(data);
}
});
PHP
<?php
//==== CONNECTION VARIABLE
$con = new mysqli($host,$user,$pass,$database);
//==== GET URL PARAMETER
$urlParam = $_GET["date"];
//==== PREPARED STATEMENT
$stmt = $con->prepare("SELECT id,name FROM __TABLE_NAME__ WHERE date = ?");
$stmt->bind_param("s", $urlParam );
$stmt->execute();
$stmt->bind_result($id, $name);
//==== CREATE ARRAY
$blogArray = array();
//==== FETCH DATA
while ($stmt->fetch()) {
$blogArray[] = array(
'id' => $id,
'name' => $name
);
}
//==== CLOSE STATEMENT
$stmt->close();
//==== ECHO AS JSON
echo json_encode($blogArray);
?>

php jquery iterate php array in success function

I have jquery pop form . It takes one input from the user ,mapping_key , Once the user enters the mapping key ,i make an ajax call to check if there is a user in the database with such a key.
This is my call .
Javascript:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
success: function(response) {
alert(response)
}
});
PHP:
$sql = "select first_name,last_name,user_email,company_name from registered_users where mapping_key = '$mapping_key'";
$res = mysql_query($sql);
$num_rows = mysql_num_rows($res);
if($num_rows == 0)
{
echo $num_rows;
}
else{
while($result = mysql_fetch_assoc($res))
{
print_r($result);
}
}
Now i want to loop through the returned array and add those returned values for displaying in another popup form.
Would appreciate any advice or help.
In your php, echo a json_encoded array:
$result = array();
while($row = mysql_fetch_assoc($res)) {
$result[] = $row;
}
echo json_encode($result);
In your javascript, set the $.ajax dataType property to 'json', then you will be able to loop the returned array:
$.ajax({
url : base_url+'ns/config/functions.php',
type: 'POST',
data : {"mapping_key":mapping_key} ,
dataType : 'json',
success: function(response) {
var i;
for (i in response) {
alert(response[i].yourcolumn);
}
}
});
change
data : {"mapping_key":mapping_key} ,
to
data: "mapping_key=" + mapping_key,
You have to take the posted mapping_key:
$mapping_key = $_POST['mapping_key'];
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = '$mapping_key'";
or this:
$sql = "select first_name,last_name,user_email,company_name from registered_users
where mapping_key = $_POST['mapping_key']";

Insert HTML input using ajax. Something wrong with code

If I click on submit button using only php, data are recorded in mysql.
Through ajax _autosave.php only update works. Insert does not work. going crazy.... can not understand
ajax code in first.php
<script type="text/javascript">
$(document).ready(function() {
setInterval(function (){
var date_day1=$("#date_day1").val();
var amount1=$("#amount1").val();
DATA = 'date_day1=' + date_day1 + '&amount1=' + amount1;
$.ajax({
type: "POST",
url: "_autosave.php",
data: DATA,
cache: false,
/*success: function(){
$(".done").show().html("Saved as a draft!");
}*/
});
setTimeout(function(){
$(".done").hide();
}, 1000);// 15 seconds
}, 3000);// 1 minute
});
</script>
HTML input
<td><input type="text" name="date_day1" id="date_day1" value="<?php echo $_POST['date_day1']?>" size="1"></td>
<td><input type="text" name="amount1" id="amount1" value="<?php echo $_POST['amount1']?>" size="5"></td>
Part of php code that is identical in first.php and _autosave.php
$date_day1 = $_POST['date_day1'];
$amount1 = $_POST['amount1'];
if ($stmt = mysqli_prepare($mysqli, "SELECT RecordDay FROM 2_1_journal WHERE RecordDay = ? ")) {
$stmt->bind_param('s', $date_day1);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($RecordDay);
$stmt->fetch();
//echo $RecordDay .' $RecordDay<br>';
}
if ($RecordDay == $date_day1) {
if ($stmt = mysqli_prepare($mysqli, "UPDATE 2_1_journal SET Amount = ? WHERE RecordDay = ? ") ) {
$stmt->bind_param( 'ds', $amount1 , $date_day1 );
$stmt->execute();
/*echo $date_day1 .' date_day1<br>';
echo $amount1 .' amount1<br>';*/
}
}
else {
if ($stmt = mysqli_prepare($mysqli, "insert into 2_1_journal
(RecordDay, Amount, DebitAccount, CreditAccount)
values(?,?,?,? )")) {
$stmt->bind_param('sdss', $date_day1, $amount1, $debit1, $credit1 );
$stmt->execute(); //execute above insertion
}
}
Update works in both files (called from both files). Insert works only if called without ajax. What is wrong?
Update
Finally found what was wrong. If $_POST is not set (not send), nothing is recorded in mysql. However no error message after execution. Simply need to remember that all variables here $stmt->bind_param('sdss', $date_day1, $amount1, $debit1, $credit1 ); must exist.
The data syntax might be the reason, use this format:
data: { key1: "value1", key2: "value2" }
See this example from: http://api.jquery.com/jQuery.ajax/
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
so, for your case try:
$.ajax({
type: "POST",
url: "_autosave.php",
data: {date_day1:$("#date_day1").val(), amount1: $("#amount1").val()},
cache: false,
});
in insert you binding 5 parameters instead of 4

Categories