I have been fighting with this issue for many days and got really stuck.
I'm trying to call a php script which contains code to access mysql database from a html file through javascript. But when I run the following on my NetBeans, I always get error at "$.ajax({" place. And NetBean doesn't specify what error it is. It only says Request was cancelled. Please help me out!!!!
HTML:
<form>
<p><input type="text" name="username" value=""></p>
<p><input type="password" name="password" value=""></p>
<p class="remember_me">
<label>
<input type="checkbox" name="remember_me" id="remember_me">
Remember me on this computer
</label>
</p>
<p><input type="submit" onClick="connect_to_db()" name="submit" value="Login" id="submit"></p>
<script>
function connect_to_db(){
utils.connectToDb(document.getElementsByName("username")[0].value,
document.getElementsByName("password")[0].value);
}
</script>
</form>
api/connect.php:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
try {
$dbh = new PDO('mysql:host=localhost;dbname=mydb', $username, $password);
$insert_cmd = "INSERT INTO version VALUES(1)";
$read_cmd = "SELECT * FROM version";
foreach($dbh->query($insert_cmd) as $row) {
print_r($row);
}
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}
?>
util.js:
window.utils = {
connectToDb: function (username, password) {
$.ajax({
url: 'api/connect.php',
data: {'username': username, 'password': password},
type: 'post',
success: function(output) {
alert(output);
}
});
},
};
NOTE: I have used similar code on Windows, and it worked. I'm currently exporting this to my Mac. I have also enabled php5 module in https.conf and configured my php.ini. I have tested my php and apache using a simple .php file which contains in it. And it is able to display the php information.
If it worked before and you didn't changed the code then its probably a setting.
Check if
Database server running
Database exists (with the same credentials)
Differences in the php version can effect this
AJAX call is to the new server (same domain/host)
the chmod rights are ok
This may not be the best answer but I'm sure this will work because this is the best way to connect to mysql database:
$dblocation="localhost"; //Your db location
$yourusername= "root"; //db name
$yourpass= ""; //blah3x
$dbname = "sample"; //database name
$connect = mysqli_connect($dblocation,$yourusername,$yourpass,$dbname);
You can use either mysql or mysqli but mysqli is much more better.
Related
I need to insert logged in user's username and email in an existing input automatically.
I tried the following code, but it doesn't insert the value in the input. I test echo $username and $user_email, it shows correct user info).
Would you please let me know how to solve this?
Existing input code (created by YITH plugin):
<from id="yith-ywraq-default-form">
<input type="text" class="input-text " name="first_name" id="first_name" placeholder="" value="">
<input type="email" class="input-text " name="email" id="email" placeholder="" value="">
</form>
Code I tried:
$autofillNameEmail = <<<EOD
<script>
(function thisFunction() {
$("input[name=first_name]").val(Print($username););
$("input[name=email]").val(Print($user_email););
})();
</script>
EOD;
$user = wp_get_current_user();
$username = $user->user_login;
$user_email = $user->user_email;
if( $user->ID ) {
echo $autofillNameEmail;
}
Thank you.
My initial thought is the javascript part of your code. Although it's not a good practice to pass php variables to a page in a way you did, but the main point in your code is whenever you want to use jQuery in wordpress, you need to explicitly tell wordpress that you need $ from jQuery. So i'd say, run the following snippet instead.
This is NOT a good practice to pass php variables to a page nor the correct way to inject javascript to a page. It is NOT recommended to use this in production! Instead consider it as a learning opportunity and go learn about wp_localize_script and wp_enqueue_script.
global $current_user;
$user_name = $current_user->user_login;
$user_email = $current_user->user_email;
if ($current_user->ID) { ?>
<script>
jQuery(document).ready($ => {
let userName = "<?php echo $user_name ?>";
let userEmail = "<?php echo $user_email ?>";
$("input[name=first_name]").val(userName);
$("input[name=email]").val(userEmail);
});
</script>
<?php }
Tested and works!
i'm trying to check if a username exists in the db with ajax. I don't know why it doesn't work i tried many things and still get nothing.
this is the code that i'm actually trying. the php code works but doesn't send the result to the ajax function
html >Registration.php
<input class="form-control" onblur="checkUser()" id="Pseudo" type="text name="Pseudo" value="" required>"
<span id="availability" name="availability" value=""> </span>
php >Welcome.php
if(!empty($_POST['Pseudo']))
{
$pseudo = $_POST['Pseudo'];
$connexion = mysqli_connect('localhost', 'root', '', 'database');
if(!$connexion)
{
die('Error during connexion ');
}
$sql = "SELECT * FROM Web_database WHERE Pseudo='$pseudo'";
$result = mysqli_query($connexion, $sql);
echo mysqli_num_rows($result);
}
Javascript > Registration.php
function checkUser()
{
var Pseudo = $('#Pseudo').val();
$.ajax({
url:'Welcome.php',
method:"POST",
data:{Pseudo:Pseudo},
success:function(data)
{
if(data == '0')
{
$('#availability').html('Pseudo correcte');
}
else
{
$('#availability').html('Pseudo déja utilisé');
}
}
});
}
First of all, you can probably optimize your SQL:
$sql = "SELECT COUNT(*) FROM Web_database WHERE Pseudo='$pseudo'"
Instead of using mysqli_num_rows().
You are also opening yourself up to SQL injection unless you use prepared statements.
As for your AJAX, it doesn't seem to be wrong. I found this question to be very similar so you might want to check that out. When in doubt, console.log() the response from PHP to see what's actually being returned. Or better yet, add a breakpoint.
I posted two javascript variables to a php file aswell as a html form using Ajax separately. I want to use the two javascript variables with the posted form values but I'm not sure how to go about this.
<script>
$(document).ready(function() {
var aucid = "<?php echo $auctionID; ?>";
var userid = "<?php echo $userID; ?>";
$.ajax({
url: "JqueryPHP/HighestBid.php",
method: "POST",
data: {'auctionid': aucid, 'userid' : userid },
success: function (result) {
$('#price').html(result);
}
});
$('form').bind('submit', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
type: 'POST',
url: 'JqueryPHP/HighestBid.php',
data: $('form').serialize(),
success: function () {
alert('form was submitted');
}
});
});
});
I posted the two javascript variables separately to the form.
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
</form>
<h4 class="price">Highest bid : <span id="price"></span></h4>
When I echo the value of userID into the span class, you can see it has a value of 2.
//JqueryPHP/HighestBid.php'
$auctionid;
$userID;
$auctionid = $_POST['auctionid'];
$userID = $_POST['userid'];
echo $userID;
if (isset($_POST['newbid']))
{
$newbid=$_POST['newbid'];
$conn = new mysqli('localhost', 'root', '', 'auctionsite');
$sql = 'INSERT INTO auction (useridhighestbid)VALUES("'.$userID.'")';
if(#$conn->query($sql)){ //execute the query and check it worked
return TRUE;
}
}
however when I try use the userID when the form is submitted and try insert it into the database for testing purposes, the value is 0.
How would I go about posting the form value with the javascript variables so I can use an update statement to update my database?
Set two hidden inputs to save aucid and userid like this:
<form>
<input type="number" min="<?php echo $startingprice ?>" step="any" style="width: 10em;" size="35" name="newbid" id="newbid" tabindex="1" class="form-control" placeholder="New Bid €" value="" required>
<input type="submit" name="submit" id="submit" tabindex="2" class="form-control btn btn-login" style="width: 14em" value="submit">
<input name='aucid' style="display:none"/>
<input name='userid' style="display:none"/>
</form>
<script>
$(document).ready(function() {
$("input[name='aucid']").val("<?php echo $auctionID; ?>");
$("input[name='userid']").val("<?php echo $userID; ?>");
.......................
});
</script>
Send your form to a php script. When the user logs in, retrive his ID from DB and put it in session like this
switch(isset($_POST['login'])):
case 'Register':
$email = htmlspecialchars(trim($_POST['em']), ENT_QUOTES, 'UTF-8');
$password = htmlspecialchars(trim($_POST['pw']), ENT_QUOTES, 'UTF-8');
// check if the combination fname/lname/email is already used
include('./Models/log_check.php');
unset($_SESSION['ID'],$_SESSION['role']);
$_SESSION['ID'] = $row['ID'];
$_SESSION['role'] = $row['role'];
So you can use ID in your Model/query:
<?php
/* Jointure sama RDV des vets */
$query =
"SELECT
appointment.start,
appointment.app_day,
patients.pet_name,
patients.breed,
patients.ID,
clients.last_name,
clients.first_name,
appointment.type,
appointment.canceled
FROM appointment
JOIN patients
JOIN clients
WHERE clients.users_ID = patients.owner_ID
AND patients.ID = appointment.patients_ID
AND appointment.vets_ID = (SELECT ID FROM vets WHERE users_ID = :ID)
AND appointment.canceled = 'n'
AND WEEK(appointment.app_day) = WEEK(:date)
ORDER BY appointment.app_day,appointment.start";
$query_params = array(':ID' => $_SESSION['ID'],
':date' => $date);
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}catch(PDOException $ex){
die("Failed to run query: " . $ex->getMessage());
}
?>
Insert instead of SELECT
Assuming you parsed the variables correctly, you can use:
$_POST['JavaScript_variable_name_goes_here'];
or
$_GET['JavaScript_variable_name_goes_here'];
to retrieve the variables in a PHP format, depending on your AJAX method.
A direct example from your AJAX function would be:
<?php $auctionId=$_POST['auctionid']; ?>
However, what I would encourage you to do, is that once a user is logged in, you set their userId as a session variable that you can use wherever the user "goes". That way, you are not parsing a crucial data element through JavaScript, which is handled client side, meaning that it's fully editable by the user through the use of a browsers dev tools. The same goes for the auctionId. I would recommend a php session variable logic for the exact same reasons. You can always overwrite the auctionId session variable with another auctionId depending on which auction is "in use".
Another good reason to why setting userId as a session variable, is that you will never have any trouble accessing the variable anywhere, as long as you remember to set the following at the very beginning of your PHP files:
<?php session_start(); ?>
The PHP/SQL syntax for the mysqli_* extension would then be the following:
$conn=mysqli_connect("localhost", "root", "", "auctionsite");
$sql="INSERT INTO auction SET useridhighestbid='$userID'";
mysqli_query($conn, $sql);
Let me know if you need anything elaborated, or if you run into any other problems.
You can append the data with the serialize like this in ajax call
data: $("#form_id").serialize() + '&xyz=' + xyz
I cannot figure out why the data is not getting inserted to my mysql database when it is being logged to the console properly.
My form as follows:
<form id="insertForm" type="post">
name: <input type="text" id="name" name="name">
activity: <input type="text" id="activity" name="activity">
level: <input type="number" id="level" name="level">
<input type="button" name="add" id="add" value="add">
</form>
My ajax call:
<script type="text/javascript">
$(document).ready(function() {
$("#add").click(function(e){
var Data = $("#insertForm").serializeArray();
console.log(Data);
$.ajax({
url : "insert.php",
type: "POST",
data : Data,
success:function(data, textStatus, jqXHR)
{
$('#msg').html(data);
}
});
$("#msg").slideDown("slow");
e.preventDefault();
});
});
</script>
My PHP insert:
<?php
if (!empty($_POST))
{
$dbhost = 'localhost';
$dbuser = 'lot_root';
$dbpass = '';
$con = mysql_connect($dbhost, $dbuser, $dbpass);
$name = mysql_real_escape_string($_POST['name']);
$activity = mysql_real_escape_string($_POST['activity']);
$level = $_POST['level'];
$sql = "INSERT INTO lottt ".
"(name, activity, level) ".
"VALUES('$name','$activity', '$level')";
mysql_select_db('lot');
mysql_close($con);
}
?>
When i insert the data via the input fields it gets logged to the js console fine like so [Object, Object, Object]0: Objectname: "character_name"value: "aSD"__proto__: Object1: Object2: Objectlength: 3__proto__: Array[0]
but nothing is inserted into the mysql database after a quick check.
You need to run the query to save it. I'll answer it to the mysql_* library, even though it is deprecated.
This is how the flow is supposed to go:
$con = mysql_connect(....) or die();
mysql_select_db('database');
$name = mysql_real_escape_string($_POST['name']);
$activity = mysql_real_escape_string($_POST['activity']);
$level = $_POST['level'];
$sql = "INSERT INTO lottt ".
"(name, activity, level) ".
"VALUES('$name','$activity', '$level')";
if(!mysql_query($sql)) {
die('Error: ' . mysql_error());
} else {
echo 'saved';
}
You should stop using mysql_* functions. The library is deprecated.
You should look into using PDO or MySQLi as they are more modern libraries and while you might have to overcome a hurdle to learn it, being competent in those libraries will do you the world of good!
Resources:
PDO
MySQLi
I'm stuck on this problem. I've been trying to use http() but doesn't seem to do anything.
Here's the form (It calls ajax_request when I submit, this works fine):
<form name='form-main'>
<input id='host' type='text' placeholder='Host' />
<input id='user' type='text' placeholder='Username' />
<input id='db' type='text' placeholder='Database' />
<input id='pass' type='password' placeholder='Password' />
</form>
and here's ajax_request part:
function ajax_request() {
var host = document.getElementById('host').value;
var user = document.getElementyById('user').value;
var db = document.getElementById('db').value;
var pass = document.getElementById('pass').value;
var submitTo = 'DB.php';
//alert(submitTo);
http('POST', submitTo, ajax_response, 'Host='+host);
}
Here's ajax_response:
function ajax_response(data) {
document.getElementById('web').value = data;
}
Finally, here's the PHP DB.php I'm trying to call:
<?php
$Host = $_POST['Host'];
$User = $_POST['User'];
$DB = $_POST['DB'];
$Pass = $_POST['Pass'];
$iDB = new mysqli($Host, $User, $DB, $Pass);
if($iDB->connect_errno) echo "no";
else echo "yes";
?>
What I'm trying to achieve here is to get the response either "yes" or "no" from the PHP and have it output on ajax_response
Would you clearly and precisely describe the problem you're having?
At quick glance, I see you're performing an HTTP POST, but your PHP is looking for HTTP GET data. Changing your Javascript to perform an HTTP GET or your PHP to look at $_POST instead of $_GET may help or prevent additional problems.
PHP has the following variables: $_GET, $_POST, and $_REQUEST. $_GET contains HTTP GET data. $_POST contains HTTP POST data. $_REQUEST contains both HTTP GET and POST data.