I'm a beginner in jQuery area and I have simple question like this :
I want to load (AJAX) MySQL result in array, let's say :
$row[0] = first name
$row[1] = last name
$row[2] = phone number
I have no problem with PHP part, but I have difficulties to display each of that array content on different id. because syntax I found loads everything processed by PHP :
<script type="text/javascript">
$(document).ready(function(){
$('#mysql-result').load('ajax.php');
});
</script>
how to get 'First Name', 'Last Name' and 'Phone Number' from PHP with only one time load and still I can put the result in different . thank you.
UPDATE
I give you real example about what I need. Here's my HTML file named ajax.html :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Ajax Trial</title>
</head>
<body>
<div id = "fistname"><!-- ajax result goes here --></div>
<div id = "lastname"><!-- ajax result goes here --></div>
<div id = "phonenumber"><!-- ajax result goes here --></div>
</body>
</html>
and here's my PHP file, named ajax.php :
<?php
require_once 'config-min.php';
$con = mysql_connect($DbServer,$DbUser,$DbPassword);
mysql_select_db($DbName, $con);
$result = mysql_query("SELECT FirstName, LastName, PhoneNumber FROM User WHERE ID = '201' LIMIT 1");
$row = mysql_fetch_array($result);
echo $row[0];
echo $row[1];
echo $row[2];
mysql_close($con);
?>
now, my question still same... how to get this PHP result (3 echos), load once, then displayed in those 3 different divs
I too wanted to do something like you wish to.And I did the following code and It worked. Hope this helps you too.
<script type="text/javascript" src="/jquery.js"></script>
<script>
$(document).ready(function(){
$("#form_plat").submit(function(e){
var str = $(this).serialize();
row[0]=$('#First_name').val();
row[1]=$('#last_name').val();
row[2]=$('#phonenumber').val();
$.ajax({
type: "POST",
url : 'Insert_Into.pl', //if you wish to store in database
data : {'firstname_name':row[0],'last_name': row[1],'phonenumber':row[2]},
beforeSend: function() {
console.log("hey i am here");
},
success: function(){
$('#note').html('Thank you for your submission!');
$('#note').hide();
$("#fields").fadeOut('slow');
}
});
return false;
});
});
</script>);
Have you tried adding to your php code:
echo $firstname.' '.$lastname.' '.$phonenumber;
Related
I am trying to use Facebook login on my website with inserting Facebook user data on my database.
I have those files as shown below :
index.php:
session_start();
?>
<!doctype html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link rel="stylesheet" type="text/css" href="css/preload.css?ve=5"/>
<title>Myexpect</title>
</head>
<body>
<?php
if ($_SESSION['FBID']):
require_once('connections/connect.php');
?> <!-- After user login -->
<div id="warper">
<div class="logo">
<img width="150px" height="150px"src="images/Logo - Copy.png">
</div>
<div class="welcome">
<h2>Welcome to our website</h2>
</div>
<div class="preload">
<img width="50" height="50px"src="loading.gif">
</div>
</div>
<?php
echo '<meta http-equiv = "refresh" content = "3; url = games.php" />'
?>
<?php else: ?> <!-- Before login -->
<div class="container">
<div><img src="images/fb-login-btn.png" ></div>
</div>
<?php endif ?>
</body>
</html>
fbconfig.php :
<?php
session_start();
// added in v4.0.0
require_once 'autoload.php';
require 'dbconfig.php';
use Facebook\FacebookSession;
use Facebook\FacebookRedirectLoginHelper;
use Facebook\FacebookRequest;
use Facebook\FacebookResponse;
use Facebook\FacebookSDKException;
use Facebook\FacebookRequestException;
use Facebook\FacebookAuthorizationException;
use Facebook\GraphObject;
use Facebook\Entities\AccessToken;
use Facebook\HttpClients\FacebookCurlHttpClient;
use Facebook\HttpClients\FacebookHttpable;
// init app with app id and secret
FacebookSession::setDefaultApplication( 'xxxxxxxxxxxx','xxxxxxxxxxxxxx' );
// login helper with redirect_uri
$helper = new FacebookRedirectLoginHelper('https://xxxxx/fbconfig.php' );
try {
$session = $helper->getSessionFromRedirect();
} catch( FacebookRequestException $ex ) {
// When Facebook returns an error
} catch( Exception $ex ) {
// When validation fails or other local issues
}
// see if we have a session
if ( isset( $session ) ) {
// graph api request for user data
$request = new FacebookRequest( $session, 'GET', '/me' );
$response = $request->execute();
// get response
$graphObject = $response->getGraphObject();
$fbid = $graphObject->getProperty('id'); // To Get Facebook ID
$fbfullname = $graphObject->getProperty('name'); // To Get Facebook full name
$femail = $graphObject->getProperty('email'); // To Get Facebook email ID
/* ---- Session Variables -----*/
$_SESSION['FBID'] = $fbid;
$_SESSION['FULLNAME'] = $fbfullname;
$_SESSION['EMAIL'] = $femail;
$check = mysqli_query($connection,"select * from Users where Fuid='$fbid'");
$check = mysqli_num_rows($check);
if (empty($check)) { // if new user . Insert a new record
$query = "INSERT INTO Users (Fuid,Ffname,Femail) VALUES ('$fbid','$fbfullname','$femail')";
mysqli_query($connection,$query);
} else { // If Returned user . update the user record
$query = "UPDATE Users SET Ffname='$ffname', Femail='$femail' where Fuid='$fuid'";
mysqli_query($connection,$query);
/* ---- header location after session ----*/
header("Location: index.php");
} } else {
$loginUrl = $helper->getLoginUrl();
header("Location: ".$loginUrl);
}
?>
The problem i have is when user try to login successfully it is not redirect to index.php file but fbconfig.php with a code :
https://xxxx/fbconfig.php?code=AQAAuanQBQ9lmXsAgbCuRB3aYy3YEEhrd81VBMMjih5oHo4dK_C7zMkQPZnuX5EdVvRJ2v4ybyAQ3EZ7qTzIrK9Oo-uY0KWiA6ZjNVh_4I6J7_AZDsJ12f7LGfc8EAGwgAfWwAm2Scwkx0UON9Vpjj75SBg7TX7n....etc
when i click back it work correctly and index.php work
how can i solve this
Sorry it was variables name mistake
this code is wrong :
$query = "UPDATE Users SET Ffname='$ffname', Femail='$femail' where Fuid='$fuid'";
i changed it to :
$query = "UPDATE Users SET Ffname='$fbfullname', Femail='$femail' where Fuid='$fbid'";
and it is work now
Hello guys my friend using a trick his upload cookies on his side sometime visitor click on log out button then cookies
not work his create a cookies activator please anyone tell me how its done this
i Just trying to say like this
set cookies(my target side like example.com )
how to log in on anyone using my username password using my HTML page
without knowing my account detail ....
So, first of all you need to make a page that'll set a cookie. For example consider this file named setCookie.php:
<?php
setcookie("user", "Alex Porter", time()+3600);
Now in your regular page HTML button:
<button id="cookieSetter">Set Cookie</button>
Now using jQuery send an AJAX request to setCookie.php file:
$('#cookieSetter').click(function(e) {
e.preventDefault();
$.ajax({
type: "GET",
url: "setCookie.php.php"
});
});
<?php
// you should start the session before any html
session_start();
// Creating some session variables like this
$_SESSION['pseudo'] = 'pseudo';
$_SESSION['password'] = 'password';
setcookie('pseudo', 'whatever', time() + 365*24*3600, null, null, false, true); // Setting up a cookie
setcookie('location', 'Russia', time() + 365*24*3600, null, null, false, true); // Just another one...
// And only after that you cant write html code.
?>
<!DOCTYPE html>
<html>
<head>
<title>Your page Title</title>
</head>
<body>
<p>
Hello <?php echo $_SESSION['pseudo']; ?> !<br />
You are in (login.php).
</p>
<p>
Hey ! I remember you !<br />
Your name is <?php echo $_COOKIE['pseudo']; ?> and you are located in <?php echo $_COOKIE['location']; ?> is that true?
</p>
<p>
Log out<br />
</p>
</body>
</html>
I´m using the tooltip script qtip2. I want to show inside the tooltip informations from a Mysql database.
For that im using a ajax.php
$var = mysql_real_escape_string($_GET['var']);
//connection to the database
$dbhandle = mysql_connect($localhost, $XXXXX, $XXXX)
or die("Unable to connect to MySQL");
//select a database to work with
$selected = mysql_select_db("tester",$dbhandle)
or die("Could not select examples");
//execute the SQL query and return records
$result = mysql_query("SELECT information FROM data_table WHERE value='$var'");
//fetch tha data from the database
while ($row = mysql_fetch_array($result)) {
echo $row{'Name'};
echo $row{'Beschreibung'};
}
//close the connection
mysql_close($dbhandle);
And the test.html
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<link type="text/css" rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/qtip2/2.1.0/jquery.qtip.min.css" />
<!-- /stylings -->
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/qtip2/2.1.0/jquery.qtip.min.js"></script>
<!-- /scripts -->
</head>
<body>
<a href="test/ajax.php" class="ajax_TT">
Enterprise hosting</a>
<script type="text/javascript">
$(function () {
$(".ajax_TT").on("click",function (e) {
e.preventDefault(); // normalized for IE
var $this=$(this);
var link = $this.attr('href');
$.ajax({
url: link,
cache: false,
data: {
html: "<p>Text echoed back to request</p>"
},
method: 'post'
}).done(function (html) {
$this.qtip({
content: {
text: html
},
style: 'qtip-wiki',
show: {
ready: true
}
});
});
});
});
</script>
</body>
</html>
On the test.html everything works, but if i use the test.html code inside a Joomla article, the tooltip just show the code from the ajax.php, and not the Mysql data.
Here is a screenshot, how it looks like in a Joomla article.
(http://s14.directupload.net/images/130810/8dicx7la.jpg)
Thanks for the help.
This is because Joomla is escaping the PHP code. I'm guessing the file is in the same directory as Joomla. Try moving the PHPfile outside of Joomla.
If you are on CPanel, you could probably create a different subdomain that would still have access to the DB. Another alternative is to use a Joomla plugin that allows you to execute PHP code like the following but I'm not sure how that would work out.
http://extensions.joomla.org/extensions/core-enhancements/coding-a-scripts-integration/custom-code-in-content/4470
I'm not a Joomla expert but hopefully that points you in the right direction.
I think the problem is in the "aif.php" file"
I am trying to fetch and display an array using PHP but the HTML element <br> is showing up in my result from the following scrip. I know I have to escape the HTML tags but I'm just not sure how! Also, any other advice on this code would be greatly appreciated (i.e. is there any redundancy or areas to improve? Thanks.
HTML
<DOCTYPE! html>
<html>
<head>
<title>The Auditors' Report: Data Entry</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<header><h1>Work Station<h1></header>
<div = id="leftnav">
<h2>Select Action</h2>
Name: <input type="text" id="name">
<input type="submit" id="grab" Value="Grab">
</div>
<div id="content"></div>
<script src="http://code.jquery.com/jquery-1.7.2.min.js"></script>
<script src="aif.js"></script>
</body>
</html>
PHP - config (filename: "config.php")
<?php
$dbhost = "localhost";
$dbname = "x";
$dbuser = "y";
$dbpass = "z";
$dsn = "mysql:host=$dbhost;dbname=$dbname";
$dbh = NULL
?>
PHP - query / resulting content (filename: "aif.php")
<?php
require "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$sql = "SELECT * FROM table1 LIMIT 0,10";
$sth = $dbh->prepare($sql);
$sth->execute();
while ($row = $sth->fetch(PDO::FETCH_ASSOC)) {
echo $row['field1'],"<br>";
echo $row['field2'],"<br>";
echo $row['field3'],"<br>";
}
?>
Javascript
$('input#grab').on('click', function() {
var name = $('input#name').val();
if ($.trim(name) !='') {
$.post('aif.php', {name: name}, function(data) {
$('div#content').text(data);
});
}
});
If you want to html encode a line like this:
this is <br /> a test
into a line like this:
this is <br /> a test
Use the nifty little function described here: HTML-encoding lost when attribute read from input field
I made a simple error in the Javascript. I wanted to pass back HTML and not TEXT.
With the following change, the PHP is rendered properly:
$('div#content').text(data);
to
$('div#content').html(data);
I am trying to make -
an android WEB application
with phonegap
layout with JqueryMobile
What Im doing -
An html form that takes ID, name, and address as input
'Serialize's this data using ajax
makes a json object out of it
Should send it to a file called 'connection.php'
Where, this data is put into a database (MySql)
Other details -
My server is localhost, Im using xampp
I have already created a database and table using phpmyadmin
The problem -
My html file, where my json object is created, does not connect to the php file which is hosted by my localhost
Here is my COMPLETE html file:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<!-- Change this if you want to allow scaling -->
<meta name="viewport" content="width=default-width; user-scalable=no" />
<meta http-equiv="Content-type" content="text/html;charset=utf-8">
<title>Trial app</title>
<link rel="stylesheet" href="thestylesheet.css" type="text/css">
<script type="text/javascript" charset="utf-8" src="javascript1.js"></script>
<script type="text/javascript" charset="utf-8" src="javascript2.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova-1.8.0.js"></script>
<script>
$(document).ready(function () {
$("#btn").click( function() {
alert('hello hello');
$.ajax({
url: "connection.php",
type: "POST",
data: {
id: $('#id').val(),
name: $('#name').val(),
Address: $('#Address').val()
},
datatype: "json",
success: function (status)
{
if (status.success == false)
{
alert("Failure!");
}
else
{
alert("Success!");
}
}
});
});
});
</script>
</head>
<body>
<div data-role="header">
<h1>Heading of the app</h1>
</div><!-- /header -->
<div data-role="content">
<form id="target" method="post">
<label for="id">
<input type="text" id="id" placeholder="ID">
</label>
<label for="name">
<input type="text" id="name" placeholder="Name">
</label>
<label for="Address">
<input type="text" id="Address" placeholder="Address">
</label>
<div id="btn" data-role="button" data-icon="star" data-theme="e">Add record</div>
<!--<input type="submit" value="Add record" data-icon="star" data-theme="e">
-->
</form>
</div>
</body>
</html>
And here is my 'connection.php' hosted by my localhost
<?php header('Content-type: application/json');
$server = "localhost";
$username = "root";
$password = "";
$database = "jqueryex";
$con = mysql_connect($server, $username, $password);
if($con) { echo "Connected to database!"; }
else { echo "Could not connect!"; }
//or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
/*
CREATE TABLE `sample` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`name` varchar(45) DEFAULT NULL,
`Address` varchar(45) DEFAULT NULL,
PRIMARY KEY (`id`)
)
*/
$id= json_decode($_POST['id']);
$name = json_decode($_POST['name']);
$Address = json_decode($_POST['Address']);
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
if (!mysql_query($sql, $con)) {
die('Error: ' . mysql_error());
} else {
echo "Comment added";
}
mysql_close($con);
?>
My doubts:
No entry is made in my table 'sample' when i view it in phpmyadmin
So obviously, i see no success messages either
I dont get any errors, not from ajax and neither from the php file.
Stuff Im suspecting:
Should i be using jsonp instead of json? Im new to this.
Is there a problem with my php file?
Perhaps I need to include some more javascript files in my html file?
I assume this is a very simple problem so please help me out! I think there is just some conceptual error, as i have only just started with jquery, ajax, and json.
Thank you.
A FEW EDITS:
I was getting the following syntax errors:
Connected to database!
Notice: Undefined index: id in C:\xampp\htdocs\connection.php on line 28
Notice: Undefined index: name in C:\xampp\htdocs\connection.php on line 31
Notice: Undefined index: Address in C:\xampp\htdocs\connection.php on line 34
Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ' '', '')' at line 1
So i changed my code to
if (isset($_POST['id']))
$id= json_decode($_POST['id']);
if (isset($_POST['name']))
$name = json_decode($_POST['name']);
if (isset($_POST['Address']))
$Address = json_decode($_POST['Address']);
Still getting the same errors
Please help!
As you're using android so direct connection.php won't work, here is the general method to get this done:
http://www.mobitechie.com/android-2/how-to-access-localhost-on-android-over-wifi/
After you setup things given in above link, the network address you'll get will be something like 10.0.0.2 then change your server to http://10.0.0.2/connection.php where connection.php is placed in htdocs directory.
Above step is necessary because android treats localhost as its own device localhost and doesn't pick the system's localhost directly.
Comment under this answer further to ask if you have more issues.
You can use JSONP for ajax request in Phonegap. But for that, you have to use Cross domain request to the server page using JSONP. Here you have to use callback method.
Just go through my post $.ajax() on phonegap.
And one more thing, dont make request from android to the localhost. Just put your file in webserver and try to make request.
Please change this script from :
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ($id, '$name', '$Address')";
To:
$sql = "INSERT INTO sample (id, name, Address) ";
$sql .= "VALUES ('$id', '$name', '$Address')";
Add the character ' around $id