I'm trying to make a simple MySQL Admin thing with php and jQuery. I've never used jQuery so my code is probably quite lol-worthy. The problem I'm having with the code is that when I click the button, nothing happens. I know the even fires because if I open the html file in firefox (not going to the url, using the file:/// thing) and click it, it shows my php code in the box I want the returned content to go into. The first thing i'm trying to do is connect to the database specified and return a list of the tables. Heres my code
index.html
<html>
<head>
<script type='text/javascript' src='jquery.js'></script>
<script type='text/javascript'>
var Server = 'None';
var Username = 'None';
var Password = 'None';
var Database = 'None';
$("#connect").click(function() {
Server = $('#server').val();
Username = $('#username').val();
Password = $('#password').val();
Database = $('#database').val();
loadTables();
});
function loadTables() {
$.get("display.php", { server: Server, username: Username, password: Password, database: Database, content: "tables" },
function(data){
html = "<ul>";
$(data).find("table").each(function() {
html = html + "<li>" + $(this).text() + "</li>";
});
html = html + "</ul>";
$('#content').html(html);
}
);
}
</script>
</head>
<body>
<center>
<div class='connection'>
<form name='connectForm'>
Server: <input type='text' size='30' id='server' />
Username: <input type='text' id='username' />
Password: <input type='password' id='password' />
Database: <input type='text' id='database' />
<input type='button' id='connect' value='Connect' />
</form>
</div>
<div id='content'>
</div>
</center>
</body>
</html>
display.php
<?
mysql_connect($_GET['server'], $_GET['username'], $_GET['password'])
or die("Error: Could not connect to database!<br />" . mysql_error());
mysql_select_db($_GET['database']);
$content = $_GET['content'];
if ($content == "tables") {
$result = mysql_query("show tables");
$xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
$xml .= "<tables>";
while ($row = mysql_fetch_assoc($result)) {
$xml .= "<table>" . $row['Tables_in_blog'] . "</table>";
}
$xml .= "</tables>";
header('Content-type: text/xml');
echo $xml;
}
?>
EDIT:
I have updated the code according to a mix of a few answers, but I'm still having the same problem.
Ok, firstly don't do that and by "that" I mean:
Don't put DB connection details in Javascript; and
Don't use input from the user without sanitizing it. You're just asking to be hacked.
That being said, your main problem seems to be that $(#content) should be $("#content"). Also putting an onclick on the button isn't really the jQuery way. Try:
<body>
<div class='connection'>
<form name='connectForm'>
Server: <input type='text' id="server" size='30' name='server' />
Username: <input type='text' id="username" name='username' />
Password: <input type='password' id="password" name='password' />
Database: <input type='text' id="database" name='database' />
<input type='button' id="connect" value='Connect' />
</form>
</div>
<div id='content'></div>
<script type="text/javascript" src="/jquery-1.3.1.js"></script>
<script type="text/javascript">
$(function() {
$("#connect").click(function() {
$.get(
"display.php",
{
server: $("#server").val(),
username: $("#username").val(),
password: $("#password").val(),
database: $("#database").val(),
content: "tables"
},
function(data) {
$("#content").html("<ul></ul>");
$(data).find("table").each(function() {
$("#content ul").append("<li>" + $(this).text() + "</li>");
});
}
);
});
});
</script>
</body>
Edit: minor corrections to the above and tested with this script:
<?
header('Content-Type: text/xml');
echo "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n";
?>
<root>
<?
$tables = array('one', 'two', 'three', 'four');
foreach ($tables as $table) {
echo " <table>$table</table>\n";
}
?>
</root>
I hope this helps. I noticed three things about your code:
1) display.php doesn't close the tag.
2) You refer to the 'content' div using $(#content), which throws a Javascript error. Make sure to encapsulate this selector in quotes, like $('#content').
3) I'm not sure about "$("table", xml).text()". Instead, used the very cool find('tag').each() syntax to walk through the XML response. This worked for me as a replacement for your function(data) statement:
function(data) {
htmlTable = '<ul>';
$(data).find('table').each(function(){
htmlTable = htmlTable + '<li>' + $(this).text() + '</li>'; });
htmlTable = htmlTable + '</ul>'
$('#content').html(htmlTable);
});
Here is a working piece of code:
<script type='text/javascript'>
function connect() {
$.ajax({
url:'display.php',
type: 'POST',
dataType:'xml',
success: {
server: $('#server').val()||'None',
username: $('#username').val()||'None',
password: $('#password').val()||'None',
database: $('#database').val()||'None',
content: "tables"
},
function(data){
$('#content').html('<ul></ul>');
var contentUL = $('#content>ul');
$(data).find('table').each(function(){
$('<li></li>').html($(this).html()).appendTo(contentUL);
});
},
'xml'
});
}
</script>
</head>
<body>
<center>
<div class='connection'>
<form id="connectForm" name='connectForm'>
Server: <input id="server" type='text' size='30' name='server' />
Username: <input id="username" type='text' name='username' />
Password: <input id="password" type='password' name='password' />
Database: <input id="database" type='text' name='database' />
<input type='button' onclick='connect();' value='Connect' />
</form>
</div>
<div id='content'>
</div>
</center>
</body>
But in my opinion it's better and easier to use JSON instead of xml, it's more easier to work with it (last lines of get function):
function(data){
$('#content').html('<ul></ul>');
var contentUL = $('#content>ul');
$.each(data.tables, function(){
$('<li></li>').html(this).appendTo(contentUL);
});
},
'json');
Also you can use jquery.form plugin to submit a form. It also can update specified elements using response, example:
$(document).ready(function() {
$('#connectForm').ajaxForm({
target: '#content'
});
});
I'm not sure exactly what the question is. But you don't need the $(function() {}) inside your $.get callback - passing a function to $() actually binds an event handler to the "ready" event which only gets called when your page is first loading. You just provide a function that takes your XML as a parameter (here you have it as "data" but reference it as "xml"?) and use it. I'd start by reading http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype, and http://docs.jquery.com/Events/ready#fn. Also, install Firebug and check out the error console to see where your JavaScript is having problems - you can go to the "Script" tab and set breakpoints to see how your code is executing to get a feeling for where things are going wrong.
You should use the jQuery.forms.js plugin.
http://malsup.com/jquery/form/
$(#content) // This is definitely a problem.
Selectors must be strings, so $("#content") would be correct.
Related
I have a page with a POST form, when I submit the form the details are updated in a database.
And I have another page where I use AJAX TAB, which means I load the first page with AJAX, when I do this and use the Form, the details are not updated in the database.
I would appreciate help.
<?php
if( isset($_POST['newcst']) )
{
/*client add*/
//getting post from user add form
$c_name = $_POST['c_name'];
$c_adress = $_POST['c_adress'];
$c_idnum = $_POST['c_idnum'];
$c_phone = $_POST['c_phone'];
$c_mail = $_POST['c_mail'];
echo $c_num;
//insert client into SQL
$wpdb->insert('se_clients',array(
'c_name' => $c_name,
'c_adress' => $c_adress,
'user_id'=>$cur_id,
'c_num'=>$c_idnum,
'c_phone'=>$c_phone,
'c_mail'=>$c_mail,
));
}
?>
<html>
</head>
<body>
<div id="newcst">
<form action="" method="post">
<label>Full name:</label>
<input type='text' name='c_name' /><br><br>
<label>ID: </label>
<input type='text' name='c_idnum' /><br><br>
<label>PHONE:</label>
<input type='text' name='c_phone' /><br><br>
<label>ADRESS: </label>
<input type='text' name='c_adress' /><br><br>
<label>EMAIL: </label>
<input type='text' name='c_mail' /><br><br>
<input name="newcst" type="submit" value="create">
</form>
</div>
</body>
</html>
Ajax tab:
$(document).ready(function() {
$("#nav li a").click(function() {
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$("#nav li a").removeClass('current');
$(this).addClass('current');
$.ajax({ url: this.href, success: function(html) {
$("#ajax-content").empty().append(html);
}
});
return false;
});
$("#ajax-content").empty().append("<div id='loading'><img src='http://wigot.net/project/wp-content/themes/projthem/vendor/images/loader.gif' alt='Loading' /></div>");
$.ajax({ url: 'invoice', success: function(html) {
$("#ajax-content").empty().append(html);
}
});
});
hover(), click(), bind(), on() and others works only after reloading page.
So you can use live()
or
$(document).on('click', 'element', function () {
...
});
I found the solution, you need to add the PHP code that is responsible for entering data to the database on the main page that contains the AJAX and not the page with the form itself.
I've input some code so that I can measure the current temperature of a location. I have the script which allows my user to check the location but the alert is not working.
<h3> Weather Data </h3>
<form method="POST" action="about.php">
<input type="text" name="city" value= 'city'/>
<input type="submit" name="submit" value="submit" />
</form>
<?php
$city=$_POST['city'];
var_dump($city);
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
$.ajax({
url : "http://api.wunderground.com/api/5e8af95dbdebbd73/geolookup/conditions/forecast/q/UK/<?php echo $city; ?>.json",
dataType : "jsonp",
success : function(parsed_json) {
var location = parsed_json['location']['city'];
var temp_f = parsed_json['current_observation']['temp_f'];
alert("Current temperature in " + location + " is: " + temp_f);
}
});
});
?>
</script>
The alert should be appearing but nothing is am I doing something wrong.
You have an unnecessary closing php tag before your closing script tag:
}
});
});
?> // this is a problem!
</script>
I would like to get select form with variable amount of fields. To achive this first I connect to db and converting data from php to javascript. Then i got array (wynik) with values, but when i try to print it i get empty select form and all values shown next to it. There is my javascript function:
<script language="javascript">
function addInput() {
document.getElementById('text').innerHTML += "<select name='add' /><br />";
for (i=0;i<wynik.length;i++)
{
document.getElementById('text').innerHTML += "<option value=" + "wynik[i]" + " />" + wynik[i] + "</option />";
}
document.getElementById('text').innerHTML += "</select />";
}
</script>
And HTML code:
<form name="add" action="add_form.php" method="post">
<div id="text">
</div>
<br>
<input type="submit" value="Submit" />
</form>
<input type="button" onclick="addInput()" name="add" value="Add value" />
Please help me to put that into form.
The browser will attempt to fix the DOM each time you write HTML to it, consequently you cannot write just a start tag to innerHTML.
Build all your HTML up in a string and then insert it in one go.
Better yet, use createElement, appendChild and friends instead.
Perhaps you need to remove <br /> after <select name='add' /> . Also </select /> does not need a / in the end (it has it in the begining) - </select>.
Another approach you can try with ajax:
<!-- Script -->
<script type="text/javascript">
$(function(){
$("#add").on('click', function(){
$.ajax({
url : 'ajax.php',
type : 'POST',
success : function(resp){
$("#backend").html(resp);
},
error : function(resp){
}
});
});
});
</script>
<!-- HTML -->
<div id="text"><select id="backend" name=""></select></div>
<input type="button" id="add" value="Add value" />
<!-- Backend ajax.php -->
<?php
#your query here to fetch $wynik
$str = "";
foreach($wynik as $value){
$str .= '<option value="'.$value.'">'.$value.'</option>';
}
return $str;
I have a form with an onkeyup event.
I try to send a variable to my php script and show result in a div.
Thanks to this forum I got my test function to half work:
jQuery.post(the_ajax_script.ajaxurl,
If I continue with:
1) jQuery("#theForm").serialize(),
I get response text which is "Hello World"
If I try to pass a variable:
2) { name: "p" },
I get: -1
JavaScript
function submit_me(){
jQuery.post(
the_ajax_script.ajaxurl,
{ name: "p" },
function(response_from_the_action_function){
jQuery("#txtHint").html(response_from_the_action_function);
}
);
}
PHP
<?php
function the_action_function(){
$name = $_POST['name'];
echo "Hello World, " . $name;
die();
}
?>
FORM
<form id="theForm">
<input type="text" name="user">
<input name="action" type="hidden" value="the_ajax_hook">
<input id="submit_button" value = "Click This" type="button" onkeyup="submit_me()">
<form>
I actually want onkeyup="submit_me(this.value, 0)"
I am doing this on a WordPress through their admin-ajax.php file.
Where is the problem in this?
EDIT
Apparently I had to add action to data
{ action:'the_ajax_hook', name:"p" }
I guess its WP requirement, rather than jQuery, because I saw examples as this:
$.post("test.php", { name: "John", time: "2pm" }
everywhere.
Something like this should work:
<html>
<head>
<script>
$(document).ready(function() {
$("#my_form").submit(function(event) {
event.preventDefault() // to prevent natural form submit action
$.post(
"processing.php",
{ name: "p" },
function(data) {
var response = jQuery.parseJSON(data);
$("#txtHint").html(response.hello_world);
}
);
});
});
</script>
</head>
<body>
<form id="my_form" action="/" method="post">
<input type="text" name="user" />
<input name="action" type="hidden" value="the_ajax_hook" />
<input type="button" name="submit" value = "Click This" />
</form>
<div id="txtHint"></div>
</body>
</html>
And then in processing.php:
<?php
$name = $_POST['name'];
$response['hello_world'] = "Hello World, " . $name;
echo json_encode($response);
?>
Alright, so I'm using jQuery and Cordova to try and login to a mySQL database. Having some issues maybe someone can help me out with.
<script type="text/javascript" charset="utf-8" src="cordova-2.0.0.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" charset="utf-8" src="jquery.mobile-1.1.1.js"></script>
<script type="text/javascript" charset="utf-8">
function login() {
$(document).ready(function() {
var user = $("#user")[0].value;
var pass = $("#pass")[0].value;
$.ajax({
type: "GET",
url: "http://www.greekhighlight.com/mob_login.php",
data: "users"+user+"&pass="+pass,
success: function(result){
if (value){
$("#message")[0].value = "Success "+result;
} else {
$("#message")[0].value = "error";
}
});
}
};
</script>
Here is my javascript in the head tag.
<form>
Username: <input type="text" size="25" id="user" onkeyup= "login()" />
<br />
Password: <input type="text" size="25" id="pass" onkeyup= "login()"/>
<br />
<input type="text" size="25" id="message" value="error" />
</form>
Here is my HTML form.
<?php
$user = $_REQUEST['user'];
$pass = $_REQUEST['pass'];
include('php/connect.php');
$result = mysql_query("SELECT email, password, userid FROM users WHERE email = '$user'");
while($row = mysql_fetch_array($result)){
if(md5($pass) == $row["password"]){
echo $row["userid"];
} else {
echo "";
}
}
?>
And here is my PHP file.
This is my first experience in using Phonegap and such, so I hope this is not something I am just overlooking. My connect file is correct. And the tutorial I was following had success, so I am not sure as to why mine is not.
If someone can just give me a push in the right direction, I hope I can figure it out.
Thanks in advance.
UPDATE: Decided to use Aurigma Up and just a mobile version of the site since this project is just in the beginning stages. Will hopefully come back to this problem at some point and make it work correctly. Thanks again for the help.
There are several issues with your code:
You should probably use POST for this request and I assume you want to use the result value in your success function check (maybe consider returning a JSON obj with status).
Your ajax.data should be more along this line {"user":user,"pass":pass}
Your php code is insecure and should use prepared statements.
Storing a password as md5(password) is a big no no these days, do some research on better/secure hash functions.
Your login event is onkeyup
Some examples to point you in the right direction
HTML:
...
<input type="text" size="25" id="pass"/>
...
<input type="button" id="#login_button" value="Login">
...
JS:
$(document).ready(function() {
$('#login_button').click(function() {
// ... ajax request here ...
});
});
PHP:
$stmt = $con->prepare('SELECT email, password, userid, salt FROM users WHERE email = ?');
$stmt->bind_param($email);
$stmt->bind_result($hash,$salt);
$stmt->execute();
if ($stmt->fetch_result()) {
if (hash('sha512',$password.$salt)==$hash) {
// ... OK ...
}
}
Goodluck.
Notes:
PHP prepared statement reference, Google "secure password storage with salt", Play around on jsfiddle.net
try this I would also make sure you use some protection against query injections on your php end
html
<form>
Username: <input type="text" size="25" id="user" onkeyup= "login()" />
<br />
Password: <input type="text" size="25" id="pass" onkeyup= "login()"/>
<br />
<input type="text" size="25" id="message" value="error" />
<input type="button" value="Submit" onclick="login()"/>
</form>
javascript
function login() {
$(document).ready(function() {
var user = $("#user").val();
var pass = $("#pass").val();
$.ajax({
url: "http://www.greekhighlight.com/mob_login.php",
type: "GET",
data: { username: user, password: pass }
cache: false,
success: function (html) {
alert(html);
}
});
});
}
and your php
<?php
$user = $_GET['username'];
$pass = $_GET['paswords'];
include('php/connect.php');
$result = mysql_query("SELECT email, password, userid FROM users WHERE email = '$user'");
while($row = mysql_fetch_array($result)){
if(md5($pass) == $row["password"]){
echo $row["userid"];
} else {
echo "";
}
}
?>