MySql data using JSON and AJAX in PHP - php

I want to get searched data from mysql database using JSON and show in my php page. I was write this code but it not retrieve any data.please help me
Client page
$(function () {
var roll = document.getElementById("roll").value;
$.ajax({
type: "POST",
url: 'api.php',
data: "roll=" + roll,
dataType: 'json',
success: function (data) {
var id = data[0];
var vname = data[1];`$` ('#output').html("id: " + id + " name: " + vname);
}
});
});
api.php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "ajax";
$tableName = "stud";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if(isset($_POST['roll'])){
$data = $_POST['roll'];
$result = mysql_query("SELECT * FROM $tableName WHERE roll = '".$data."'");
$array = mysql_fetch_row($result);
}
echo json_encode($array);

log this value before sending,
var roll = document.getElementById("roll").value;
console.log(roll);
Use object to send the params in ajax call like this data: {'roll':roll} for best practice
use firebug to check if the value 'roll' passed properly
In your php dump the post variable print_r($_POST) and check the firebug response console whether you got what you sent.
If you got it in $_POST then probably you have some issue with sql connection/query

Related

PHP parsererror ajax get returns array of strings

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.

JSON Object To Javascript Array?

I'm having problems decoding a JSON object. I call a PHP script using an Ajax call. The PHP script returns a JSON encoded object which I can read but only the first record. How can I decode the JSON object? I am using JQUERY Mobile.
PHP script:
<?php
$host = "localhost";
$user = "root";
$pass = "[password]";
$databaseName = "zombieSurvival";
$tableName = "TBLusers";
//Connect to mysql database
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
// 2) Query database
$result = mysql_query("SELECT * FROM $tableName");
$array = mysql_fetch_array($result);
echo json_encode($array);
?>
and here is the Ajax call:
$.ajax({
url: '/PHP/getUserMarkers.php',
data: "",
dataType: 'json',
success: function(data){
//How can I treat 'data' variable to make it a
//javascript array?
}
});
The issue was the JSON object returned by the PHP script. Adjusted the PHP script as below and now I can access all returned rows and individual field names.
<?php
$host = "localhost";
$user = "root";
$pass = "muertealregueton";
$databaseName = "zombieSurvival";
$tableName = "TBLusers";
include 'DB.php';
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$result = mysql_query("SELECT * FROM $tableName");
$array = array();
while(($row = mysql_fetch_array($result))) {
$array[] = $row;
}
echo json_encode($array);
?>
and the ajax code which calls an alert on one of the later records returned:
$.ajax({
url: '/PHP/getUserMarkers.php',
data: "",
dataType: 'json',
success: function(data){
//now I can access each row and field
//like here I access the 3rd field of the 15th record
alert(data[15][2]);
}
});

How to read data from json array in jquery?

I have to retrieve many rows from MySQL and send by encoding with ajax and I done this. but the problem is I am not able to handle the output array data in ajax. can anyone help me please?
1>one.php
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "elearning";
$tableName = "users";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
if(isset($_POST)){
$exam_id=$_POST['exam_id'];
$sql="select * from exam_to_question where exam_id=$exam_id";
$result = mysql_query($sql);
$dataArray = array();
while($array = mysql_fetch_assoc($result)){
$dataArray[] = $array;
}
echo json_encode($dataArray);
}
?>
2> and ajax code is:
$.ajax({
type: 'POST',
url: '../functions/one.php',
data: "exam_id="+exam_id,
dataType: 'json',
success: function(data){
//alert(data[0]['question_id']);
// i have to handle data here
},
error:function(){
alert("AJAX failure");
}
});
If that is an array then you have to use .each() method of jQuery:
$.each(data, function(i, resp){
console.log(resp);
});
You will get jquery object with ajax response. So, you can process it with any of these functions:
http://api.jquery.com/each/
http://api.jquery.com/jQuery.each/
if you have used dataType: json then you can dirctly use
//if it is not a multidimensional array then you can dirctly
data.keyName
//if it is multidimensional array
$(data).each(function(index,element){
console.log(element);
})

Get url parameter and query mysql data with ajax

I want to get a parameter from an url. The url looks like this:
www.example.com/?v=12345
I want to get the parameter and query my mysql database to get the right data with ajax.
So i have my ajax call here:
$.ajax({
type:"POST",
url:"ajax2.php",
dataType:"json",
success:function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error:function(response){
alert("error occurred");
}
});
As you can see, the data which i want to get are in a json array and will be saved in javascript variables.
This is my php file:
<?php
// Connection stuff right here
$myquery = "SELECT * FROM mytable **WHERE id= **$myurlvariable**;
$result = mysql_query($myquery);
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array = array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
echo json_encode($array);
}
?>
The part where i want to query the right variable is bolded. I don't know how to query that. And Furthermore how to even get the url parameter in the proper form.
Can anybody help? Thank you!
You can get the query string using JavaScript and send it in the AJAX request.
Getting the query string(JavaScript) -
function query_string(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Getting the parameter-
v = query_string('v'); // Will return '12345' if url is www.example.com/?v=12345
This needs to be passed as data in the AJAX call.
$.ajax(
{
type: "POST",
dataType: "json",
url: "ajax2.php",
data: "v="+v,
success: function(response){
var id = response['id'];
var url = response['url'];
var name = response['name'];
var image = response['image'];
},
error: function(jqXHR,textStatus,errorThrown){
//alert(JSON.stringify(jqXHR));
//alert(textStatus);
//alert(errorThrown);
alert(JSON.stringify(jqXHR)+" "+textStatus+" "+errorThrown);
//alert("error occurred");
}
}
);
This can be accessed as $_POST['v'] in the php form.
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
...
And in php form, before you echo out the json response, change the content type. Something like this-
header("Content-Type: application/json");
echo json_encode($array);
If there is a database error, then it has to be handled.
So do this -
<?php
// Connection stuff right here
header("Content-Type: application/json");
if(isset($_POST['v'])){
$myurlvariable = $_POST['v'];
$myquery = "SELECT * FROM mytable WHERE id= $myurlvariable";
$result = mysql_query($myquery) or die(json_encode(Array("error": mysql_error()));
while($row = mysql_fetch_object($result))
{
$currentid = "$row->id";
$currentname = "$row->name";
$currenturl = "$row->url";
$currentimage = "$row->image";
$array[]= array('id'=>$currentid,'url'=>$currenturl, 'name'=>$currentname,'image'=>$currentimage);
}
echo json_encode($array);
}else{
echo json_encode(Array("error": "No POST values"));
}
?>
So this way, if the query has not executed properly, then you will know what exactly the error is.
Without any error checking, just the important part:
$myquery = "SELECT * FROM mytable WHERE id=" . $_POST['v'];

Load data from database + ajax + php

I have a question about loading multiple fields from the database and use them in javascript.
This is my table "deaths" with fields:
- district
- year_1999
- year_2000
- year_2001
- year_2002
- year_2003
- year_2004
- year_2005
- year_2006
- year_2007
- year_2008
- year_2009
Now I want to load the fields year_.... when district = 'districtname'
This is what I have: (PHP)
$host = "localhost";
$user = "root";
$pass = "root";
$databaseName = "testdatabase";
$tableName = "deaths";
//--------------------------------------------------------------------------
// 1) Connect to mysql database
//--------------------------------------------------------------------------
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
//--------------------------------------------------------------------------
// 2) Query database for data
//--------------------------------------------------------------------------
$result = mysql_query("SELECT year_1999,year_2000,year_2001,year_2002,year_2003,year_2004,year_2005,year_2006,year_2007,year_2008,year_2009 FROM $tableName WHERE district = 'Binnenstad'"); //query
$data = array();
while ( $row = mysql_fetch_row($result) )
{
$data[] = $row;
}
echo json_encode( $data );
Javascript:
$(function ()
{
//-----------------------------------------------------------------------
// 2) Send a http request with AJAX http://api.jquery.com/jQuery.ajax/
//-----------------------------------------------------------------------
$.ajax({
url: './api4.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
//--------------------------------------------------------------------
// 3) Update html content
//--------------------------------------------------------------------
for (var i in rows)
{
var row = rows[i];
var data = row[0];
$('#districts ul').append("<li>" + data + "</li>")
.append();
}
}
});
});
But this only shows the first column data (year_1999).
How can I fix this?
Instead for (var i in rows) ... try :
UPDATE. Looking your php closer try something like this to draw each year:
$.each(rows, function(i, data) {
$.each(data, function(j, year) {
$('#districts ul').append("<li>" + year + "</li>")
});
});

Categories