I have a MYSQL table that has a column defined as TEXT, when i reading the contents into PHP the result is that the data is not being pulled through.
my php code
SELECT establishments.name AS estName,
establishments.address AS estAddr,
establishments.telephone_num AS estTel,
establishments.description AS estDesc,
establishments.Logo AS estLogo,
establishments.title AS estTitle
FROM bucurestideals1.establishments
WHERE establishments.establishment_id ="'.$est_id.'"';
The table row has data so this is not an issue, i am reading the data using php as below:
$.ajax({
type: 'GET',
url: pass_url,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function (data, status) {
// Assign the returned data to the page
$.each(data, function(i,item)
{
alert(item.estDesc);
});
},
Update: PHP Code
<?php
header('Content-type: application/json');
$est_id = $_GET['id'];
$server = "*";
$username = "*";
$password = "*";
$database = "";
$con = mysql_connect($server, $username, $password) or die ("Could not connect: " . mysql_error());
mysql_select_db($database, $con);
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
while($row = mysql_fetch_assoc($result))
{
$records[] = $row;
}
mysql_close($con);
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
?>
You can probably remove the quotes from your where statement. If that is not the issue, can you post the php code that you use to execute the sql?
Related
Jquery Mobile - Ajax call to fetch data from Json data from MySql database returning error.
Here's my code
Server code
<?php
try{
header('Content-type: application/json');
$server = "myurl";
$username = "username";
$password = "password";
$database = "mydb";
$con = mysqli_connect($server, $username, $password, $database) or die ("Could not connect: " . mysql_error());
/*mysql_select_db($database, $con);
$result = mysql_query($sql) or die ("Query error: " . mysql_error());
$records = array();
*/
$sql = "SELECT id, l_name AS name, l_lat AS value1, l_long AS value2 FROM landmarks ORDER BY l_name";
$result= mysqli_query($con, $sql);
$records = array();
while($row = mysqli_fetch_assoc($result)) {
$records[] = $row;
}
mysqli_close($con);
echo json_encode($records);
}
catch(Throwable $e) {
$trace = $e->getTrace();
echo $e->getMessage().' in '.$e->getFile().' on line '.$e->getLine().' called from '.$trace[0]['file'].' on line '.$trace[0]['line'];
}
?>
my ajax call
try {
$.ajax({
url: 'myurl',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var res = '<h1>'+item.name+'</h1>'
+ '<p>'+item.value1+'<br>'
+ item.value2+'</p>';
output.append(res);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
}
catch (e) {
logMyErrors(e);
}
Here ajax is returning the error function.
But while running the server code in the browser, json data is displayed correctly.
Nothing is being logged in the console. Please help to find out what has gone wrong.
I am having a problem trying to get around a "parsererror" that is returned from my ajax request, despite a response in devtools which is an array of strings. I have a click event that makes an ajax request to pull in information from a database. The result in dev tools is:
1["1","admin","admin#admin.com","test","2017-01-11 00:00:00"]
I was expecting it to be a json object { }.
The code I wrote for the click event is:
$('#viewProfile').on('click', function() {
$.ajax({
type: 'GET',
url: 'api.php',
data: "",
cache: false,
dataType: 'json',
success: function(data) {
var id = data[0];
var name = data[1];
$('#userDetails').html("<p>ID: " + id + " Name: " + name + "</p>");
},
error: function(request, error) {
$('#userDetails').html("<p>There was a problem: " + error + "</p>");
}
});
});
The php I wrote for api.php
session_start();
echo $_SESSION['user_session'];
//DECLARE VARS FOR DB
$db_host = "localhost";
$db_name = "dbregistration";
$db_user = "root";
$db_pass = "";
$db_tablename = "tbl_users";
//CONNECT TO DB
include 'dbconfig.php';
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name);
$dbs = mysqli_select_db($db_con, $db_name);
//QUERY DB FOR DATA
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
$array = mysqli_fetch_row($result);
//RETURN RESULT
echo json_encode($array);
I have tried in api.php to use json_encode($array, JSON_FORCE_OBJECT) along with changing the datatype to HTML, which obviously did not work. In short, my goal was to be able to fire the click event, send an ajax request to retrieve information from the database, based on the user id then return that to the #userDetails id on the page. I am stuck trying to get around the array of strings that seems to be the roadblock for me.
Remove this line:
echo $_SESSION['user_session'];
and change this:
$array = mysqli_fetch_row($result);
to this:
$array = mysqli_fetch_assoc($result);
EDIT: you should also be checking for success/failure of your various db-related statements:
$db_con = mysqli_connect($db_host,$db_user,$db_pass,$db_name) or die("there was a problem connecting to the db");
$dbs = mysqli_select_db($db_con, $db_name) or die("Could not select db");
and also
$result = mysqli_query($db_con, "SELECT * FROM $db_tablename where user_id = '".$_SESSION['user_session']."' ");
if (!$result) {
die("query failed");
}
This needs to be removed echo $_SESSION['user_session'] it is getting returned to ajax call and because it is on json the return is incorrect.
i want to insert data to mysql database using php service and json but when i click nothing happens it shows no error no message and the data is not added to the data base help please
here is the save function
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url:"http://localhost:800/test/insert.php",
type: 'POST',
data: data,
dataType: 'json',
success: function()
{alert("success");}
error: function()
{alert("fail");}
});
}
and this my php file insert.php
<?php
$json = $_POST['data'];
$new=json_decode($json, true);
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$sql = "INSERT INTO user (email,mdp) VALUES ($new['email'],$new['mdp'])";
if (mysqli_query($conn, $sql)) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
?>
You don't have "data" key in your $_POST array, you have "email" and "mdp", which you can access directly:
$email = mysqli_real_escape_string($_POST['email']);
$mdp = mysqli_real_escape_string($_POST['mdp']);
There is no json passed in this way, similarly when you have get string, you also don't need to parse it. Turn on error reporting, then you will see that $_POST['data'] is undefined.
BTW, use mysqli_real_escape_string to sanitize the input to prevent from injection.
"Insert.php" - > Not use for get data $json = $_POST['data'];
Only use this and try
$conn= mysqli_connect("localhost","root","") or die ("could not connect to mysql");
mysqli_select_db($conn,"bd") or die ("no database");
$email = $_POST['email'];
$mdp = $_POST['mdp'];
$new1 = json_encode($email);
$new2 = json_encode($mdp);
$sql = "INSERT INTO user ('email','mdp') VALUES ('".$new1."','".$new2."')";
$insert = mysqli_query($sql);
if ($insert) {
echo "created ";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
Your PHP code seems to be correct, but please try the jQuery AJAX code as follows:
function save(){
var eml = document.getElementById("tbemail").value;
var mp = document.getElementById("tbmdp").value;
var data = {email: eml, mdp: mp}
$.ajax({
url: "http://localhost:800/test/insert.php",
type: 'POST',
dataType: 'json',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
error: function () {
alert('fail');
},
success: function (data) {
alert('success');
}
});
}
In your data section has to be passed as JSON String, secondly you missed to in include the data contentType. Here content type is set as application/json, therefore pass the data as JSON string.
I'm trying to get a column from mySQL as an array in php, then read this into javascript with jquery/ajax, and finally display the first four of the array within some HTML divs.
I think I have the php working because when I inspect I get a return that has all the elements in the array.
retrieve.php
//Create connection ("Server", "Login name", "Password", "Database name")
$connect = mysql_connect($host, $username , $password);
//Check connection
if (!$connect)
{
die ('could not connect: '. mysql_error());
}
//create connection and select database
mysql_select_db($database, $connect);
//select text column and orders them by most recent postID
$query = "SELECT text FROM $table ORDER BY postID DESC";
$result = mysql_query($query);
//create an array of recent responses
while($row = mysql_fetch_array($result)){
echo json_encode($row['text']);
}
mysql_close($connect);
scripting.js
$(document).ready(function(){ //This performs specified actions when the page fully loads
$.ajax({
type: 'POST',
url: 'retrieve.php',
data: 'data',
dataType: 'json',
success: function(result){
$("#box0").html(result[0])
$("#box1").html(result[1])
$("#box2").html(result[2])
$("#box3").html(result[3]);
}
});
Try replacing
while($row = mysql_fetch_array($result)){
echo json_encode($row['text']);
}
with
$rows = array();
while($row = mysql_fetch_array($result)){
$rows[] = $row['text'];
}
echo json_encode($rows);
to json encode an array of row texts rather than encoding them separately.
I have this code in jquery:
$.ajax({
type: "POST",
url: "tosql.php",
data: {textnode: textnode},
success: function(){
alert( "Data Saved: " );
}
});
and this php script:
<?php
$textnode = $_POST['textnode'];
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("repository", $con);
mysql_query("INSERT INTO paragraphs (paragraphs) VALUES ('$textnode')");
mysql_close($con);
?>
When I go to mysql to view if the array was stored, I see "Array" as the value. What I'm trying to do is store each value in the array into its own row also. Serialize didn't work in this case.
Edited:
if(get_magic_quotes_gpc())
$magic = 1;
else
$magic = 0;
foreach($textnode as $key => $value) {
if($magic == 0){
$value = mysql_real_escape_string($value, $con);
}
else{
$value = stripslashes($value);
$value = mysql_real_escape_string($value, $con);
}
mysql_query("INSERT INTO paragraphs (paragraphs)
VALUES ('$value')");
}