This is the first time I worked with Ajax in combination with PHP and I'm having a hard time getting it to work.
I have this piece of Ajax code:
$.ajax({
url: '/dev/php/login.php',
type: 'POST',
dataType: 'json',
error: function(date) {
console.log(date);
alert("Het emailadres of wachtwoord is onjuist");
},
data: {email:email,password:password},
success: function(response) {
console.log(response);
alert(response);
}
})
With this PHP code:
<?php
$servername = "blur";
$username = "blur";
$dbpassword = "blur";
$dbname = "blur";
$emailadres = $_POST['email'];
$password = $_POST['password'];
// Create connection
$conn = new mysqli($servername, $username, $dbpassword, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$encodedpass = md5($password);
$sql = "SELECT first_name, last_name FROM account WHERE `email`='$emailadres' AND `password`='$encodedpass'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "Name: " . $row["first_name"]. " " . $row["last_name"] . " WEEEE";
}
}
else {
if (!function_exists('http_response_code'))
{
function http_response_code($newcode = NULL)
{
static $code = 200;
if($newcode !== NULL)
{
header('X-PHP-Response-Code: '.$newcode, true, $newcode);
if(!headers_sent())
$code = $newcode;
}
return $code;
}
}
}
$conn->close();
?>
For some reason the error function in Ajax always gets called, even when the response text echoes me the name from the database. It looks like this:
Related
I have not touched PHP or AJAX that much in about 8 years, so my memory on this is pretty low at the moment.
What I'm doing is fetching data from my database that works great.
Then I want to use AJAX to get the data from the PHP file.
My PHP file on my server is connecting to the database and fetching the table "Form".
This data is then going to be retrieved by another app trough AJAX.
I have a working PHP file, but how I should order this for the AJAX to fetch it nicely is a big question for me.
The things I have at the moment is:
PHP FILE:
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM form";
$result = $conn->query($sql);
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$name = $row['name'];
$country = $row['country'];
$email = $row['email'];
$need = $row['need'];
$available = $row['available'];
echo "name: " . $name . "<br> Country: " . $country . " <br> Email: " . $email . "<br> Need: " . $need . "<br> Available: " . $available;
$form_data = array();
array_push($form_data)
}
} else {
echo "Null results";
}
$conn->close();
?>
AJAX FILE:
$.ajax({
url: 'url',
data: "",
dataType: 'json',
success: function(data) {
}
});
The AJAX file is not complete since I'm still wondering about these PHP results.
Right now they are just stored in variables.
What is the best way to store these results to get an fetch for AJAX here?
Should I put the results in an array and then push that array into another array?
There can be many lines in forms, and I want 1 person with data: name, country etc to be in one array. Or is it stupid to have it in an array?
I hope someone can give a little clue and help me on my way here. Long time since I have been doing PHP and a little bit unclear about the best approach here.
Been searching for a while, but nothing made so much sense to me, so I'm coming here hoping someone can guide the way.
Happy Easter.
Create an array and save all your data, then json_encode to send the data to JavaScript.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_julekgwa";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM form";
$result = $conn->query($sql);
$rows = array();
if($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$name = $row['name'];
$country = $row['country'];
$email = $row['email'];
$need = $row['need'];
$available = $row['available'];
$rows[] = "{ name: " . $name . ", Country: " . $country . ", Email: " . $email . ", Need: " . $need . ", Available: " . $available . "}";
}
echo json_encode($rows);
} else {
echo json_encode([ "error" => "Null results"]);
}
$conn->close();
?>
In your ajax do the following
$.ajax({
url: 'file.php',
type: "GET",
dataType: 'json',
success: function(data) {
data.forEach(item => {
console.log(item);
});
},
error: function(data) {
console.log(data);
}
});
I have my php file on a server that retrieves data from my database.
<?php
$servername = "myHosting";
$username = "myUserName";
$password = "MyPassword";
$dbname = "myDbName";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name, description FROM tableName;";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
$row_number = 0;
while($row = $result->fetch_assoc()) {
$row_number++;
echo $_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"];
}
} else {
echo "0 results";
}
$conn->close();
?>
Unfortunately, I do not know how to receive data from a php file using javascript.
I would like the script in javascript to display the received data in the console in browser.
The script written in javascript is Userscript in my browser extension(tampermonkey) and php file is on my server.
I've tried to use ajax, unfortunately without positive results.
(the php script works as expected).
JS(not working):
$.ajax({
url: 'https://myserver.com/file.php',
type: 'POST',
success: function(response) {
console.log(response);
}
});
The code within the loop is a little screwy
$_GET[$row_number. ";". $row["id"]. ";". $row["name"]. ";". $row["description"]. "<br>"]
that suggests a very oddly named querystring parameter which is not, I think, what was intended.
Instead, perhaps try like this:
<?php
$servername = 'myHosting';
$username = 'myUserName';
$password = 'MyPassword';
$dbname = 'myDbName';
$conn = new mysqli($servername, $username, $password, $dbname);
if( $conn->connect_error ) {
die( 'Connection failed: ' . $conn->connect_error );
}
$sql = 'select `id`, `name`, `description` from `tablename`;';
$result = $conn->query($sql);
if( $result->num_rows > 0 ) {
$row_number = 0;
while( $row = $result->fetch_assoc() ) {
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
} else {
echo '0 results';
}
$conn->close();
?>
A full example to illustrate how your ajax code can interact with the db. The php code at the top of the example is to emulate your remote script - the query is more or less the same as your own and the javascript is only slightly modified... if you were to change the sql query for your own it ought to work...
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* emulate the remote script */
$dbport = 3306;
$dbhost = 'localhost';
$dbuser = 'root';
$dbpwd = 'xxx';
$dbname = 'xxx';
$db = new mysqli( $dbhost, $dbuser, $dbpwd, $dbname );
$sql= 'select `id`, `address` as `name`, `suburb` as `description` from `wishlist`';
$res=$db->query( $sql );
$row_number=0;
while( $row=$res->fetch_assoc() ){
$row_number++;
/* print out row number and recordset details using a pre-defined format */
printf(
'%d;%d;%s;%s<br />',
$row_number,
$row['id'],
$row['name'],
$row['description']
);
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<script src='//code.jquery.com/jquery-latest.js'></script>
<title>Basic Ajax & db interaction</title>
<script>
$( document ).ready( function(){
$.ajax({
url: location.href,
type: 'POST',
success: function( response ) {
console.log( response );
document.getElementById('out').innerHTML=response;
}
});
} );
</script>
</head>
<body>
<div id='out'></div>
</body>
</html>
Hi you can do it this way:
your php script:
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case 'SLC':
if (isset($_POST["id"])) {
$id = $_POST["id"];
if (is_int($id)) {
$query = "select * from alumni_users where userId = '$id' ";
$update = mysqli_query($mysqli, $query);
$response = array();
while($row = mysqli_fetch_array($update)){
.......
fill your response here
}
echo json_encode($response);
}
}
break;
}
}
Where action is a command you want to do SLC, UPD, DEL etc and id is a parameter
then in your ajax:
function getdetails() {
var value = $('#userId').val();
return $.ajax({
type: "POST",
url: "getInfo.php",
data: {id: value}
})
}
call it like this:
getdetails().done(function(response){
var data=JSON.parse(response);
if (data != null) {
//fill your forms using your data
}
})
Hope it helps
I stuck in the following process:
Here is the well known "Facebook Login for the Web with the JavaScript SDK example":
https://developers.facebook.com/docs/facebook-login/web
I want to get the Facebook USERID as a simple string to pass it to a PHP variable. Altough the USERID is shown when I print the $fbID, but it's not a string.
How can I get the USERID as a simple string (or a number)...?
Here is my code:
<?php
$fbID = "<script>
function testAPI() {
console.log('Welcome! Fetching your information.... ');
FB.api('/me', function(response) {
console.log('Successful login for: ' + response.name);
document.getElementById('status').innerHTML = response.id;
});
}
</script>";
?>
</script>
<div id="status">
</div>
<?php
echo $fbID;
$sql = "select id from customer where fbid = '$fbID' and status = '1'";
$table = mysqli_query($conn,$sql);
list($realid) = mysqli_fetch_array($table,MYSQLI_BOTH);
echo $realid;
?>
Thank you in advance for your answers!
Use ajax to persist the ID in your database. Add the following code to your FB.api('/me', function(response) { } function:
$.ajax({
url: 'persistID.php',
type: "POST",
dataType:'json',
data: ({id: response.id}),
success: function(data){
console.log(data);
}
});
And create a seperate persistID.php file where you persist the FacebookID:
<?php
$ID = $_POST['id'];
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO customer (fbid) VALUES ($ID)";
// Persist userid
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
I have a textbox with the ID and NAME called "name". In my database I have firstname, preposition, lastname. In SQL I am using concat to combine these to a "name".
When I am trying to echo the result $result['name'] I get a browser error.
I guess something is wrong with the multiple variable $name = in my code. But I could not fix it.
Does someone know what is wrong with my code?
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname) ;
// Check connection
if ($conn->connect_error) {
die('Connection failed: ' . $conn->connect_error) ;
}else {
$id = isset($_POST['id']) ? $_POST['id'] : '';
$name = isset($_POST['firstname']) ? $_POST['firstname'] : '';
$name .= isset($_POST['preposition']) ? $_POST['preposition'] : '';
$name .= isset($_POST['lastname']) ? $_POST['lastname'] : '';
$query = 'SELECT concat(firstname, ' ', preposition, ' ', lastname) as name FROM users WHERE id="' . mysqli_real_escape_string($conn, $id) . '"';
$res = mysqli_query($conn, $query) ;
if (mysqli_num_rows($res) > 0) {
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}else{
$result = mysqli_fetch_assoc($res) ;
echo $result['name'];
}
}
?>
Edit 1:
Textbox:
<input type="text" class="form-control" id="name" name="name">
Javascript:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function getUser(value) { // Do an Ajax request to retrieve the product price
console.log("getUser before ajax", jQuery('#id').val());
jQuery.ajax({
url: './get/get5.php',
method: 'POST',
data: {'id' : jQuery('#id').val()},
success: function(response){
console.log("getUser after ajax", jQuery('#id').val());
jQuery('#name').val(response);
},
error: function (request, status, error) {
alert(request.responseText);
},
});
}
</script>
I'm working on an ajax long polling function with mysql and it doesn't really seem to work. My computer is overheating and the website crashes after some minutes. Also, the poll.php doesn't even receive the content from data.php, instead, poll.php shows {"type":"connect_error).
I have not done any long polling before.
I have 3 files:
data.php
<?php
session_start();
define ('DB_HOST', 'localhost');
define ('DB_USER', 'root');
define ('DB_PASSWORD', 'root');
define ('DB_NAME', 'story_creator');
function sqlSelect($query) {
// Create connection
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$result = mysqli_query($conn, $query);
// Check connection
if (mysqli_errno($conn)) {
echo "Failed: " . mysqli_error($conn);
}
$resultArray = array();
if ($result) {
while ($row = mysqli_fetch_array($result)) {
$resultArray[] = $row;
}
}
return $resultArray;
}
$news = sqlSelect("SELECT type FROM users_news_feed WHERE user_id = {$_SESSION['user_id']} AND date > 0;");
echo json_encode($news);
?>
poll.php
<?php
$filename = 'data.php';
$lastmodif = isset($_POST['timestamp'])? $_POST['timestamp']: 0;
$currentmodif = filemtime($filename);
while ($currentmodif <= $lastmodif) {
usleep(10000);
clearstatcache();
$currentmodif = filemtime($filename);
}
$response = array();
$response['type'] = file_get_contents($filename);
$response['timestamp'] = $currentmodif;
echo json_encode($response);
?>
Javascript
<script>
var timestamp = null;
function waitForMsg(){
$.ajax({
type: "POST",
url: "functions/poll.php",
async: true,
cache: false,
timeout: 50000, /* Timeout in ms */
data: { 'timestamp': timestamp },
success: function(data){
// if(data == ''){
// Just console.log the data
console.log(data);
setInterval(
waitForMsg(), /* Try again after.. */
1000); /* milliseconds (15seconds) */
// }
},
complete: function(){
setInterval(waitForMsg(), 7000);
}
});
}
$(document).ready(function() {
waitForMsg();
});
</script>