The following is in my file.js
function mainget(){
$.ajax({
type: 'GET',
url: 'example.php',
data:json,
success:function(data){
}
});
}
example.php
<?php
$con = mysqli_connect('address','DATBASE','pass','futureday');
$result = mysql_query("SELECT * FROM $futureday");
$array = mysql_fetch_row($result);
echo json_encode($array);
?>
I have been struck with this for the past 2 days. I have tried inserting alert as first line of function mainget , which is successful, but after that I get nothing.
You are using data property in AJAX call to indicate the json data type. It is an invalid one. Use dataType to provide the data type. data property is used to pass the datas. And also put quotes to the values like:
dataType:'json'
Also change your example.php file. There you are using mysqli_connect to connect the database, then mysql_* to execute and fetch operations. It is not correct. Use either mysqli_* or mysql_*. Edit as:
<?php
$con = mysqli_connect('address','DATBASE','pass','futureday');
$result = mysqli_query("SELECT * FROM $futureday");
$response = array();
while($array = mysqli_fetch_row($result)){
$response[]=$array;
}
echo json_encode($response);
?>
Use this
$mysqli = new mysqli('address','DATBASE','pass','futureday');
$query = "SELECT * FROM $futureday";
$results=$mysqli->query($query) ;
$res=$mysqli->fetch_array(MYSQLI_ASSOC);
echo json_encode($res);
Related
I have an HTML page that is too big to post on here, however I'll just post the ajax/jquery I am using to try and access the PHP file variables.
threadPage.html
<script type="text/javascript">
$.ajax({
url : '/ThreadCreation.php',
type : 'POST',
data: {'titles': titles}
crossDomain: true,
dataType : 'jsonp',
success : function (data) {
console.log(data) /
},
error : function () {
alert("error");
}
})
</script>
<!-- bunch of html -->
So essentially I am trying to get the variable from the ThreadCreation.php in JSON form. It should be in an array so that I can loop through it in the HTML file.
ThreadCreation.php
<?php
$username = 'root';
$password = '';
$db = 'main_database';
$conn = mysqli_connect('localhost', $username , $password,$db);
if (!$conn){
die("unable to connect");
}
$sql = mysqli_query($conn, "SELECT title FROM thread");
while($row = mysqli_fetch_array($sql)) {
$titles[] = $row['title'];
echo json_encode($titles);
?>
I will repeat though, that this HTML file is only getting information from the database through PHP. So there is no form submission here.
I keep getting that 'titles is not defined'. This makes sense because there is not titles defined in the HTML, however I am unsure how to construct my ajax request to collect the data, as this format is all I have seen people use.
Mention empty array first just to prevent error in case you have no data
in database then empty array will proceed.
$sql = mysqli_query($conn, "SELECT title FROM thread");
$titles = array();
while ($row = mysqli_fetch_array($sql)) {
array_push($titles,$row['title']); // Push data in empty array
}
echo json_encode($titles);
I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}
I have a JavaScript that runs a POST method once my datepicker has been out of focus (I also tried this on a regular submit button) and runs the script rent-fetch-pick-up-point.php. The PHP runs, however it doesn't get past the if-statement because my it's not getting the POST data. The datepicker is tied to a input field time-period-from
datepickerTo.blur(function(){
if (selectedDateFrom.length > 0) {
datepickerFrom.delay(500).queue(function(){
$.ajax({
type: "POST",
url: "include/rent-fetch-pick-up-point.php",
data: {action: selectedDateFrom},
success: function(data) {
$("#pick-up-point-container").html(data);
}
});
});
}
});
Here is the PHP code:
if (isset($_POST['time-period-from'])) {
require '../include/connection.php';
$dateFrom = $_POST['time-period-from'];
$sql = "SELECT * FROM order WHERE $dateFrom BETWEEN date_from AND date_to";
$result = mysqli_query($connection, $sql);
$numRows = mysqli_num_rows($result);
echo $sql; // For testing purposes
}
And here's the HTML:
<input type="text" name="time-period-from" id="datepicker-from" class="datepicker"></p>
I also tried using $.post() instead of $.ajax(), but I ran into the same issue:
$.post("include/rent-fetch-pick-up-point.php", {name: selectedDateTo}, function(data) {
$("#pick-up-point-container").text(data)
});
The keys of $_POST come from the keys of the object you pass to the data: option, not the names of the form fields where the values originally came from. Since you used:
data: { action: selectedDateFrom }
the value will be in $_POST['action'], not $_POST['time-period-from']. So you need to use:
if (isset($_POST['action']))
and:
$dateFrom = $_POST['action'];
or you could change the Javascript to:
data: { "time-period-from": selectedDateFrom }
I think your selectedDateFrom variable is array that cause your post info can't you get properly .
data: {action: $('#selectedDateFrom').serializeArray()}
then you get your form data properly
You aren't grabbing the right variable on the PHP side:
if (isset($_POST['action'])) {
require '../include/connection.php';
$dateFrom = $_POST['action'];
$sql = "SELECT * FROM order WHERE $dateFrom BETWEEN date_from AND date_to";
$result = mysqli_query($connection, $sql);
$numRows = mysqli_num_rows($result);
echo $sql; // For testing purposes
}
I am trying to populate datatables on button click which will send a date to process.php which in turn will query the database and output a json array.
Here are my code:
Javascript:
var dailyCollTable = $("#dailyColl").DataTable();
$("#dailyBills").click(function(){
var date = $("#billDate").val();
$.ajax({
type:'post',
url:'process.php',
data:{date:date},
dataType:'json',
success:function(s){
console.log(s);
dailyCollTable.fnClearTable();
for(var i = 0; i < s.length; i++){
dailyCollTable.fnAddData([ s[i][0], s[i][1], s[i][2], s[i][3], s[i][4], s[i][5] ]);
}
}
});
});
And this is my process.php
<?php
$connection = mysqli_connect("localhost", "root", "", "database");
$date = $_POST['date'];
$query = mysqli_query($connection,"SELECT CustomerName,BillNumber,BillDate,BillAmount,PaidAmount,PaymentDate FROM billentry WHERE Status=1 AND PaymentDate='$date'");
while($fetch = mysqli_fetch_array($query)){
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5]);
}
echo json_encode($output);
?>
I checked browser console. the array is coming fine. The error I am getting is
Uncaught TypeError: dailyCollTable.fnClearTable is not a function
I have included all the necessary libraries.
The exact same code worked on my earlier tables.
There is mistake at the end of query ...PaymentDate='$date'
You should write ...PaymentDate='" . $date . "'
I'm having trouble getting data from my database. My goal is to get all groups from my database and return them in JSON (in an alert box or whatever).
Now it won't convert to JSON and I am getting weird response text from the ajax call. If you need anything else to solve this problem, please do not hesitate to ask.
Here is what I did.
PHP
$servername = "redacted";
$username = "redacted";
$password = "redacted";
$dbname = "redacted";
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'getGroups' : getAllGroups();break;
}
}
function getAllGroups() {
$mysqli = new mysqli($servername, $username, $password, $dbname);
$query = $mysqli->query("SELECT * FROM groups");
while($row = $query->fetch_object()) {
$result[] = $row;
}
echo "{\"results\":";
echo json_encode($result);
echo "}";
$mysqli->close();
}
JS
function getPosts() {
$.ajax({
url: 'functions.php',
data: {action: 'getGroups'},
type: 'post',
success: function(output) {
var result = JSON.parse(output);
result = result.resultaten;
alert(result);
}
});
}
getPosts();
Thanks in advance,
Mistergrave.
No need for that extra echos. Try with -
echo json_encode(array('results' => $result));
Instead of -
echo "{\"results\":";
echo json_encode($result);
echo "}";
No need for - if(isset($_POST['action']) && !empty($_POST['action'])) {
if(!empty($_POST['action'])) { - do the all.
Define $result first.
$result = array();
while($row = $query->fetch_object()) {
$result[] = $row;
}
Okay guys, I managed to solve everything. Apparently the php function couldn't find my credentials to log in to the database server because I defined them on top of the php file (and since javascript only executed the function, these credentials were undefined).
Solution:
I just copy-pasted the credentials at the start of each function so these were defined. And tadaah! It worked :).
Now I realize why the responseText was full of tables, because it started to return error tables about the connection.
I hope my explanation will help other people who have this issue as well.
Cheers, and thanks for all the helpfull answers,
Mistergrave.
use
echo json_encode(array('result'=>$result));
As it takes array as parameter. Check here
Just a note :
If are sure you will return json data, use dataType:json , so you wont need JSON.parse(output).