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]);
}
});
Related
I'm using URL hashes to request data from my database, such as "url.com/content/book.html#132" in this format:
$(document).ready(function(){
var number = window.location.hash.substr(1);
$.ajax({
type:'POST',
url:'./db/db.php',
dataType: "json",
data:{number:number},
success:function(data){
if(data.status == 'ok'){
$('#title').text(data.result.title);
$('#author').text(data.result.author);
$('#genre').text(data.result.genre);
etc...
}
}
});
});
and in PHP:
<?php
if(!empty($_POST['number'])){
$data = array();
//database details
$dbHost = '******';
$dbUsername = '******';
$dbPassword = '******';
$dbName = '******';
$db = new mysqli($dbHost, $dbUsername, $dbPassword, $dbName);
if($db->connect_error){
die("Unable to connect database: " . $db->connect_error);
}
$query = $db->query("SELECT * FROM db WHERE id = {$_POST['number']}");
if($query->num_rows > 0){
$userData = $query->fetch_assoc();
$data['status'] = 'ok';
$data['result'] = $userData;
}else{
$data['status'] = 'err';
$data['result'] = '';
}
echo json_encode($data);
}
?>
This works perfectly. However, I'd also like to pull up data on another page based on genre, which I would also like to set with the URL, as in
"url.com/content/genre.html#history"
In my ajax, I simply changed the variable to 'genre' and data:{genre:genre}. In my PHP I'm selecting like this:
$query = $db->query("SELECT * FROM db WHERE genre = {$_POST['genre']}");
but it doesn't work and I even get a blank when testing with print_r ($_POST['genre']); and a console.log(gengre); shows the hash is being read correctly. What am I missing?
For those interested, I found the answer, and of course it was much simpler than I was expecting. JSON.stringify()
So:
var hash = window.location.hash.substr(1);
var genre = JSON.stringify(hash);
This turns the value into a json object.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
i am making a quiz webapp with php and ajax where on click of radio button it triggers a function to get the new row in a database using ajax and php however it outputs object object inside the specified div element whenever the ajax success is called.
here is the ajax side of the code:
<script>
$(document).ready(function(){
$('input[type="radio"]').click(function(){
var answer = $(this).val();
var question_id = $('#dataContainer').data('value');
$.ajax({
url:"quizengine.php",
method:"POST",
data:{
answer:answer,
question_id:question_id
},
dataType: 'json',
success:function(response){
console.info(response);
$('#question').text(response);
$('#answer_one').text(response);
$('#answer_two').text(response);
$('#answer_three').text(response);
}
});
});
});
</script>
and here is the php side of the code
<?php
session_start();
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "rubiqube";
$connection = new mysqli($servername, $username, $password, $dbname);
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
?>
<?php
if (isset($_POST['answer'])) {
global $connection;
$answer = $_POST['answer'];
$question_id = $_POST['question_id'];
$result = mysqli_query($connection, "SELECT is_right FROM answers WHERE question_id='$question_id'");
$row = mysqli_fetch_assoc($result);
if (isset($row)) {
$correct = $row['is_right'];
if ($answer === $correct) {
$next = mysqli_query($connection, "SELECT Questions.question_id,Questions.lesson,Questions.instruction,Questions.question,Questions.image,Questions.option_type,Questions.question_value,Answers.answer_one,Answers.answer_two,Answers.answer_three,Answers.is_right FROM Questions LEFT JOIN Answers ON Questions.question_id = Answers.question_id WHERE Questions.question_id>'$question_id' ORDER BY Questions.question_id ASC LIMIT 1");
$nextrow = mysqli_fetch_assoc($next);
echo json_encode($nextrow);
exit();
}else{
echo "error";
exit();
}
}
}
?>
here is an image of what i am talking about
enter image description here
When the response comes back in the success callback, dataType: 'json' will convert it from json to an object (thus why you're seeing [object object]). You can't use the .text() method on it directly as that requires it to be a string. You may be able to do $('#question').text(response.key) depending on the data structure.
You need to simply either loop through the object and use the data, or access the properties directly (i.e. console.log(response.key)).
Here is some documentation from MDN on what to do with an object. Working with objects
Create an object of the Question on the server'side, then in your ajax response do this:
success:function(response){
$('#question').text(response.propertyName);
//propertyNamerefers to the one you made on the serverside
}
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 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);
})
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