I have really weird problem with AJAX.
This is fragment of file with js code and post method which sends params to php file via AJAX:
var params = $('#add').serializeArray();
$.post('code/bg/adding_c.php', params, function(ret) {
//body of success function
}, 'json');
And this is fragment of php code (adding_c.php):
<?php
require "functions.php";
//irrelevant operations
$return = array(
'status' => $status,
'msg' => $msg,
'id' => $id
);
echo json_encode($return);
?>
Everything works when I comment or delete the line with require instruction but when it's active, success function isn't fired.
JS post method sends correct params.
Php file receives it, does proper operations and returns correct data to js script (I can see it in FireBug).
Success function isn't fired.
Why instruction which isn't related with AJAX, causes this problem?
Edit.
functions.php:
<?php
$host = 'localhost';
$user = 'root';
$pass = '';
$db = 'dbname';
$conn = new mysqli($host, $user, $pass, $db);
function querySQL($query)
{
global $conn;
$result = $conn->query($query);
return $result;
}
function cleanSQL($conn, $string)
{
return htmlentities(fixSQL($conn, $string), ENT_COMPAT, 'UTF-8');
}
function fixSQL($conn, $string)
{
if(get_magic_quotes_gpc())
$string = stripslashes($string);
return $conn->real_escape_string($string);
}
function fPassword($pass)
{
$salt1 = 'salt1';
$salt2 = 'salt2';
$token = hash('ripemd128', "$salt1$pass$salt2");
return $token;
}
?>
Edit2.
There is no errors and when I paste functions from functions.php to index.php everything works fine. I don't know what to do now. It seems that require word is a problem here. I can't add these functions to every file in which I need them.
It is probably an error within functions.php.
EDIT: If you haven't set display_errors = On in your php.ini file, use these lines in your code:
ini_set("display_errors", "1");
error_reporting(E_ALL);
Also, are you sure it is not a parsing/syntax error? If that is the case, there's a few things you will want to do:
Make sure you are using an IDE that checks syntax (Netbeans, for example).
Separate the file into two, like so:
index.php
<?php
ini_set("display_errors", "1");
error_reporting(E_ALL);
include 'error.php';
error.php
require "functions.php";
//irrelevant operations
$return = array(
'status' => $status,
'msg' => $msg,
'id' => $id
);
echo json_encode($return);
Run this in a browser window and that should give you an idea of what you are dealing with.
Related
this is my code. i've done this before in other computer and it's okay, but now when try it in my laptop,it can't be done. idk what is the problem, it will show blank in phpmyadmin. i'm using xampp v3.2.2, is that will be the problem?
<html><head><title>Your Data</title></head>
<body>
<?php
$n = $_POST["n"];
$c = $_POST["contact"];
$e = $_POST["email"];
$cm = $_POST["campus"];
$m1 = $_POST["member1"];
$m2 = $_POST["member2"];
$m3 = $_POST["member3"];
$connect = mysqli_connect("localhost","root","") or die("Unable to connect MySQL".mysqli_error());
$db = mysqli_select_db($connect,"multimedia_db") or die("Unable to select database");
$query1 = "INSERT INTO teams(advisor_name,advisor_contact,advisor_email,advisor_campus,member1,member2,member3) VALUES ('$n','$c','$e','$cm','$m1','$m2','$m3')";
$data1 = mysqli_query($connect,$query1) or die("SQL statement failed"); //records are assigned to variable data
echo "You've succesfully register";
?>
</body>
</html>
I don't use MySQLi very often. So I'll explain how to use PDO. Just so you know PDO means PHP Data Objects. The reason I'm explaining, PDO is because, if done properly, it makes SQL injection almost impossible.
Connection
connecting to your database is generally done in a separate file. Here is an example:
con.php
<?php
$hostname = '';
$username = '';
$password = '';
$dbname = '';
try {
$dbh = new PDO("mysql:host=$hostname;dbname=$dbname", $username, $password, array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Connection failed: ' . $e->getMessage();
}
?>
This is just connecting to the database, so we don't have to keep connecting to other pages, we just refer to this page with an include, like this:
<?php include 'con.php'; ?>
We can put this on any page and it'll include the connection to the database. For example, if you want to select from a database:
<?php
include 'con.php';
$load_data = $dbh->prepare("SELECT * FROM user_table");
if ($load_data->execute()) {
$load_data->setFetchMode(PDO::FETCH_ASSOC);
}
while ($row = $load_data->fetch()) {
$name = $row['name'];
echo $name;
}
?>
This would simply SELECT everything from the user_table from the column name and would display all the matching records.
If you're trying to do an INSERT instead:
<?php
include 'con.php';
$post_name = $_POST['post_name'];
$stmt = $dbh->prepare("INSERT INTO user_table (name) VALUES (:user_name)");
$stmt->bindParam(':user_name', $post_name, PDO::PARAM_STR);
if ($stmt->execute()) {
echo "Success";
} else {
echo "Failed";
}
?>
So the $post_name would be the name you give your input on a form in this case name="post_name" that would be inserted into the user_table.
Hope this helps and FYI here is a very good tutorial on how to do INSERT, UPDATE and DELETE using PDO.
i've found the solution for my question. It's just that i forgot to put localhost in front of the 'url'. no wonder it showed blank.
like 'localhost/sem5/saveRegistration.php'.
i'm sorry for the inconvenience. still a beginner using this hehe
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 having written a php script which makes an SQL query and fetches a list of unique names from the database.
I am making an AJAX GET request using jQuery to the php script. When I check resources in the console I see that the php script is being called, and when I check the response it contains a list of unique names.
However, the jquery GET request is failing, and is displaying an error message in the console.
It may be easier and clearer to look at my code, as I have no idea what is the issue here. Please see code below.
php
<?php
header('Content-Type: application/json');
$servername = "****";
$username = "****";
$password = "****";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT(name) FROM customer";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo json_encode(array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
$conn->close();
?>
JS
$.ajax({
type: 'GET',
url: 'getcustomers.php',
success: function(data){
console.log(data);
},
error: function() {
console.log('error');
}
});
In the console it simply says error, meaning it has executed the error function.
When I load the php file in the browser it displays the following.
{"name":"Peter"}{"name":"Alan"}{"name":"Mike"}
Your JSON response is not a valid one. You are printing each data row on each iteration. So replace the while statement with this one,
if ($result->num_rows > 0) {
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = array('customer' => $row["name"]);
}
echo json_encode($return);
} else {
echo "0 results";
}
Considering your script returns any result (I hope you've tried running it in broswer) then you can use something like this:
$.get('path/to/file/filename.php').done(function(response) {
$('#exampleDiv').html(response);
});
Although, common errors because you must specify the directory path if the php file you're requesting is outside the current working directory.
change your error handler function header to the following:
error: function (jqXHR, textStatus, errorThrown) {
then print that and see what the error is
you are echoing json_encode string in side while loop, instead of that you will have to push row in an array and at the end you can echo json string only once.
$outputArr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push(outputArr ,array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
echo json_encode($outputArr);
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).
In Php, I encoded a JSON array from MySQL table . i want to decode it in different Php file . and i want to access the data through JavaScript from different file. anyone please help me.
MY code is:
$serverName = "(local)";
$connectionInfo = array( "Database"=>"sample");
$conn = sqlsrv_connect( $serverName, $connectionInfo);
if( $conn )
{
echo "Connection established.<br/>";
}
else
{
echo "Connection could not be established.<br/>";
die( print_r( sqlsrv_errors(), true));
}
$str="Select * from sam1";
$res=sqlsrv_query($conn,$str) or die("Error !");
$response=array();
while( $row = sqlsrv_fetch_array( $res, SQLSRV_FETCH_ASSOC) )
{
$response['tdata'][]=$row;
}
print(json_encode($response));
Output is :
{"tdata":[{"id":"1","name":"aaa"},{"id":"2","name":"bbb"},{"id":"3","name":"ccc"}]}
My decode Function is:
$data = file_get_contents('db2.php');
$data1 = json_decode($data, true);
print($data1);
but its not working..
When you return JSON encoded string it is best if you send a proper headers. You should return JSON like that (you can still use print function):
<?php
header('Content-Type: application/json');
echo json_encode($data);
Now, when you retrieve this output, send it to json_decode function that will return an object.
json_decode.
file_get_contents function retrieves content of the file, it does not parse it. To retrieve the content of the file:
by calling it with an URL (DO NOT USE THIS ONE I am showing this method for the purpose of learning only, this function wont load URL if allow_url_fopen directive is off, instead you can use curl library (here))
$json = file_get_contents('www.example.com/db2.php');
echo json_decode($json, true);
by including it with a relative path
$json = (include "db2.php");
echo json_decode($json, true);
in this particular scenario, db2.php has to use return statement like so
return json_encode($response);
by using ob_* with include, this time you do not need to return in db2.php file
ob_start();
include "db2.php";
$json = ob_get_contents();
ob_end_clean();
echo json_decode($json, true);
It looks like you're populating $data with the text of db2.php instead of the output from running the file in php. Try this:
$data = `php db2.php`