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
}
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 trying to subtract 0.05 from the cash amount of a player in my database once they push a button. Here is what I got so far.
My database:
Database name: accounts
Table: users
The Column I want to affect: cash_amount
Html:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'subtract5.php', // <=== CALL THE PHP FUNCTION HERE.
success: function ( data ) {
alert( data ); // <=== VALUE RETURNED FROM FUNCTION.
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<button id="playbutton" onclick="myAjax();location.href='5game.html'">Play (-5¢)</button>
Php file: (subtract5.php)
<?php
UPDATE `accounts`.`users` SET `cash_amount` = '`cash_amount` - 0.05'
Thanks for helping, I am kind of a noob :)
This the following code, however dont exactly copy paste it, read the comments there are a few variables you might have to change and get from the database.
<?php
$servername = "servarname";
$username = "username";
$password = "password";
$dbname = "dbName";
// Create connection
$userid = // You must enter the user's id here.
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch the existing value of the cash_amount against that particular user here. You can use the SELECT cash_amount from users where userid = $userid
$newAmount = $previousAmount - 0.05;
$sql = "UPDATE users SET cash_amount = '$newAmount'";
$result = $conn->query($sql);
if($result)
{
echo "Query Executed Successfully!";
}
else
{
echo mysqli_error($conn);
}
$conn->close();
?>
Try executing that request. That's nothing more than a string without quotes around it. I'm sure that PHP considers it as an error.
You should consider learning PHP and MySQL before attempting to code a project.
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 created a form with two selects and my idea was when the first select is changed, a query is made to the database and the second select is updated with new information.
Since is the first time I'm doing this kind of things, I tried insert some data from that query in a H3 tag instead of using a select tag, but something is not working... The H3 tag starts empty and after changing the select box, the H3 tag remains empty.
This is my code:
<script>
$(document).ready(function(){
$("#show-form-button").click(function(){
$("#show-form-button").hide();
$("#bot-form").show();
});
$("#distrito").on('change', function() {
var selected = $(this).val();
makeAjaxRequest(selected);
});
});
function insertResults(json){
alert("cenas");
$("#teste").val(json["nome"]);
}
function makeAjaxRequest(placeID){
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
}
});
}
</script>
And this is my PHP script:
<?php
$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "paulocristo";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$placeId = $_GET["placeId"];
$query = "SELECT nome from local WHERE id =".$placeId ." AND tipo=0";
$result = $conn -> query($query) or die("Query failed");
if($result -> num_rows > 0)
{
while ($row = $result -> fetch_assoc())
{
echo $row['nome'];
echo json_encode($row);
}
}
?>
Any idea what can be wrong?
I think the problem must be with AJAX because when I run this code, the right information is being displayed in the browser.
Thanks for your patience and sorry for my bad english.
1) Remove echo $row['nome']; if you echo ANYTHING along with the JSON response, the full response will not be valid JSON and the success function will not be called
2) dont echo your JSON for each row like that, that's not valid either. –
Instead do this:
$response = [];
while ( $row = $result->fetch_assoc() ){
$response[] = $row;
}
echo json_encode($response);
3) you're checking $_GET['placeId'] but your ajax is using type: "POST". Change your php to $placeId = $_POST["placeId"];
Additionally, and an error function after your success function in your AJAX like the following to better see what is going wrong:
$.ajax({
type: "POST",
data: {placeId: placeID},
dataType: "json",
url: "http://localhost/Paulo%20Cristo%20LDA/insert.php",
success: function(json) {
insertResults(json);
},
error: function(xhr, status, error){
console.log(xhr);
}
});
4) Remember also that the response will be an array of rows not a single row so you'll need to update your function like so:
function insertResults(json){
alert("cenas");
$("#teste").val(json[0]["nome"]); // grab the 'nome' property from the first row in the response
}
In your PHP do this:
while($row = $result->fetch_assoc()){
$arr[] = $row;
}
echo json_encode($arr);
mysql_close($con);
Also don't forget to do mysql_close($con) at the end. Hope this helps you!
From what I see you are using val() on h3 change your function to the following and use html(), The .val() method is primarily used to get the values of form elements such as input
function insertResults(json){
alert("cenas");
$("#teste").html(json["nome"]);
}
at first I apologise for creating this topic. I did try to search the answer but I couldnt find the right solution.
I am reading data from mysql with ajax and everything is working with one div. The thing I can't get working is to load each variable into separate div.
I use this api.php for fetching the data from mysql.
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "skuska";
$tableName = "hodnoty";
//--------------------------------------------------------------------------
// 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 t.hodnota FROM hodnoty t ORDER BY t.id DESC LIMIT 1') or die('Invalid query: ' . mysql_error()); //query
while ($row = mysql_fetch_assoc($result)) {
echo $row['hodnota'];
}
?>
This is the ajax script for updating the data.
$(document).ready(function() {
$("#gettable").load("api.php");
var refreshId = setInterval(function() {
$("#gettable").load('api.php?randval='+ Math.random());
}, 9000);
$.ajaxSetup({ cache: false });
});
Then in html I am using div for showing the data
<div id="gettable"></div>
I would like to use this but with more variables like data1, data2, data3
and then used div for each data so I could use more divs.
For example:
<div id="data1"></div>
<div id="data2"></div>
I understand html, a little bit of php but I am totally new in java.
Thank you for your help.
do this
take as many variables as you have div and store content in variables inside loops
/******* a short example **************/
$div1cnt="";
$div2cnt="";
while($SRC=mysqlii_fetch_object($link)){
$divid=$SRC->id;
if($divid==1){
$div1cnt.="add more stuff that you want here";
}
else if($divid==2){
$div2cnt.="add stuff to second div";
}
echo "<div id=\"div1\">{$div1cnt}</div>";
/************and so on ******************/
There is no JS requirement means it is mobile friendly and no double connection required to load second page.
Here is how you can solve the problem in Javascript ( watch out, not JAVA :) )
$(document).ready(function() {
var i = 1;
$.get("api.php", function(result) {
$("#gettable").append("<div id='data"+i+"'>"+result+"</div>");
i++;
});
var refreshId = setInterval(function() {
$.get("api.php?randval="+ Math.random(), function(result) {
$("#gettable").append("<div id='data"+i+"'>"+result+"</div>");
i++;
});
}, 9000);
$.ajaxSetup({ cache: false });
});