Unwanted JSON Response - javascript

I'm using this small JSON function with a database.
<script>
$(document).ready(function () {
var url = "Database.php";
$("#jsondata tbody").html("");
$.getJSON(url, function (data) {
$.each(data.users, function (i, user) {
var songdetails = "<p>"
+ "<p>" + user.Title + "</p>"
+ "<p>" + user.ArtistNumber + "</p>"
+ "<p>" + user.TrackTime + "</p>"
+ "<p>" + user.Composer + "</p>"
+ "<p>" + user.Lyricist + "</p>"
+ "</p>";
$(songdetails).appendTo("songlist");
});
});
});
</script>
This produces this in the browser, which I don't want/need.
{"users":[{"Title":"Anyway","ArtistNumber":"2","TrackTime":"167","Composer":"John
Glaze","Lyricist":"Kellee
Maize","FileLocation":"public/Anyway.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"One
Way Heartbeats","ArtistNumber":"4","TrackTime":"187","Composer":"Bill
Bobs","Lyricist":"Michael
McEachern","FileLocation":"public/OneWayHeartbeats.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Parallel
Me","ArtistNumber":"3","TrackTime":"192","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"private/ParallelMe.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"1"},{"Title":"Poisoned
Oxygen","ArtistNumber":"3","TrackTime":"177","Composer":"Quite
Revolution","Lyricist":"Quite
Revolution","FileLocation":"public/PoisonedOxygen.mp3","rated":"0","scores":"[0,0,0,0,0]","free":"0"},{"Title":"Xmas
Prison Blues","ArtistNumber":"1","TrackTime":"192","Composer":"Steve
Perry","Lyricist":"Steve
Perry","FileLocation":"private/XmasPrisonBlues.wma","rated":"0","scores":"[0,0,0,0,0]","free":"1"}]}
Any ideas on how to hide it or remove it from coming up?
Thanks
This is the Database.php:
<?php
$Hostserver = "localhost";
$databUser = "ee2800";
$databPass = "secret";
$databDatabase = "ee2800";
$database = new mysqli ($Hostserver, $databUser, $databPass, $databDatabase);
if ($database) {
mysqli_select_db($database, "ee2800");
//echo ("Successfully connected to database!");
} else {
die ("<strong>Error:</strong> Failed to connect to the database.");
}
$var = array();
$sql = "SELECT * FROM songs";
$result = mysqli_query($database, $sql);
while ($obj = mysqli_fetch_object($result)) {
$var[] = $obj;
}
echo '{"users":' . json_encode($var) . '}';
?>
Using jQuery 1.10.2
The songlist element is found here
<?php
// The system queries the database to obtain a result set containing no more than 10 artists //
if ($result = $database->query( "SELECT * FROM `artist` ORDER BY `artist`.`ArtistNumber` ASC LIMIT 10")) {
while ($row = $result->fetch_row()) {
echo "<div id='artist{$row[2]}'>";
echo "<p>Artist: {$row[0]} {$row[1]}</p>";
echo '<p><div id= songlist> </div> </p>';
//div tag 'songlist' adds all data from json and pastes into this div id //
// echo '<p>Songs</p>';
//onlick function echo'd anchor tag//
echo "</div>";
// Songs dont display onclick however retrieved data using jSON can't seem to target where to put the information //
}
}
$database->close();
?>
And basically whenever I run these files, I get that long string I stated at the beginning as a response in my browser everytime.

Well your PHP appears to be returning a valid json string, but it is not being coverted automatically to a json object so that it can be processed by javascript as an object.
You could try forcing the parse to a json object like this
$.getJSON(url, function (data) {
data = $.parseJSON(data);
$.each(data.users, function (i, user) {

Related

Retrieve image from database and display using ajax

I'm facing problem while retrieving image location from database and display it using ajax.
Below is the code.
I can retrieve all the data except image.
Needed help with that please.
<script type="text/javascript">
$(document).ready(function() {
var url = "http://localhost/project/app/read.php";
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id;
var bookname = field.bookname;
var publisher = field.publisher;
var author = field.author;
var location = field.location; //image location
$("#listview").append("<h2>" + bookname + " </h2><p>" + publisher + "</p><p>" + author + "</p>");
});
});
});
</script>
read.php
<?php
include "db.php";
$data=array();
$q=mysqli_query($con,"select * from `book`");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
echo json_encode($data);
?>
the below code is also not working
"<img src=" +location+ /">"

how to check whether request is made or not

i am using contenteditable property in p tag .. the code is
<p contenteditable="true" id="Option1_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'A.'.' &nbsp'.$question1['Option1'];?></p>
<p contenteditable="true" id="Option2_<?php echo $i ?>" style="width:98%;border:4px thin black; background-color:#D6D6D6;font-size:18px;color:black;padding:3px "><?php echo ' '.'B.'.' &nbsp'.$question1['Option2'];?></P>
and jquery to make a request to make request
document).ready(function(){
$("p[contenteditable=true]").blur(function(){
var msg = $(".alert");
var newvalue = $(this).text();
var field = $(this).attr("id");
$.post("ajax.php",field+"="+newvalue,function(d){
var data = JSON.parse(d);
msg.removeClass("hide");
if(data.status == '200'){
msg.addClass("alert-success").removeClass("alert-danger");
}else{
msg.addClass("alert-danger").removeClass("alert-success");
}
msg.text(data.response);
setTimeout(function(){msg.addClass("hide");},3000);//It will add hide class after 3 seconds
});
});
});
and then php to update my mysql database on receiving the request
<?php
$response = NULL;
$status = http_response_code(406);
if(!empty($_POST)){
session_start();
$mock_test_name=$_SESSION['mock_test_name'];
$num_of_sections = $_SESSION['num_of_sections'];
$school_name = $_SESSION['school_name'];
$class_name = $_SESSION['class_name'];
$section_name = $_SESSION['section_name'];
$con = mysqli_connect("localhost","root","","onlinetest");
if (!$con)
{
die('Could not connect: ' . mysqli_error());
}
$table_space = "$school_name $class_name $section_name $mock_test_name";
$table = str_replace(" ", "_", $table_space);
$table_space1 = "$school_name $class_name $section_name";
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = "$table1 $table";
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);
foreach($_POST as $key=>$value){
$key = strip_tags(trim($key));
$value = strip_tags(trim($value));
$explode = explode("_",$key);
$user_id = $explode[1];
$field_name = $explode[0];
if(isset($user_id)){
$update = false;
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'"); //Selecting data from MySql
$result = mysqli_fetch_assoc($selectData); //Fetching Data
if($result[$field_name]!==$value){ //Checking if the Value is modified
$update = mysqli_query($con,"UPDATE" + $table2+ "SET" + $field_name+"="+$value+ "WHERE question_id='"+$user_id+"'"); //Updating MySQL if value is Modifie
}
//Update the users Table
if($update){
$response = "User Details Updated";
http_response_code(200); //Setting HTTP Code to 200 i.e OK
}else{
$response = "Not Modified";
http_response_code(304); //Setting HTTP Code to 304 i.e Not Modified
}
}else{
$response = "Not Acceptable";
}
}
}
echo json_encode(array(
"status"=>$status,
"response"=>$response
));
?>
But i think the request is not made properly as the database is not getting updated.. Please tell me how to check if a request has been made... or am i making error somewhere in writing code ??
Your mysqli_query function is formed incorrectly. You have to escape out of the parentheses in order to drop in variables.
You need to do something like
mysqli_connect($con, "SELECT " + var1 + " FROM " + var2);
or you'll end up making a query for
EDIT:
For a more apt example, the line
$selectData = mysqli_query($con,"SELECT $field_name FROM $table2 WHERE question_id='$user_id'");
should be
$selectData = mysqli_query($con,"SELECT " + $field_name + " FROM " + $table2 + " WHERE question_id='" + $user_id + "'");
You'll notice the main difference, especially in coloring between the two, signifying that in the first one, the variables $field_name, $table2, and $user_id are all being interpreted as part of the query. You don't want the NAME of the variable, you want the VALUE of it instead, so you need to concatenate the strings together.
This is just one of the multiple similar fixes you'll need to do for your multiple queries. Every place the editor is marking the thing you're trying to use as a variable as part of the string, take the same steps to concat the strings.
You need to change your code like this,
ajax code
$.ajax({
type:"post",
url:"ajax.php",
data: "your data",
success:function(d){
console.log(d);
}
});
php code:
$table_space = $school_name." ".$class_name." ".$section_name." ".$mock_test_name;
$table = str_replace(" ", "_", $table_space);
$table_space1 = $school_name." ".$class_name." ".$section_name;
$table1 = str_replace(" ", "_", $table_space1);
$table_space2 = $table1." ".$table;
$table2 = str_replace(" ", "_", $table_space2);
$table2 = strtolower($table2);

How to use setInterval() when there's a param?

I'm trying to get a single div on a php page to refresh every 5 seconds.
In HTML I have: EDIT: NEW SCRIPT FUNCTION
<script>
$(document).ready(function(){
var callAjax = function(){
$.ajax({
method:'get',
url:'game.php',
success:function(data){
$("#read_chat").html(data);
}
});
}
setInterval(callAjax, 5000);
});
</script>
And the function (in a php block) I'm trying to refresh is:
echo" <div class='read_chat' >";
function get_messages($db){
//get messages
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
//display messages
foreach ($messages as $row) {
//display each message in row
if ( $row['character_name'] == NULL){
echo "<div class='left'>" . $row['user_name'] . ": </div>";
}
else {
echo "<div class='left'>" . $row['character_name'] . ": </div>";
}
echo "<div class='center'>" . $row['message'] . "</div>";
echo "<div class='right'>" . $row['time'] . "</div>";
}
}
echo "</div>";
The display of this is only the CSSed block without any content. If I just call get_messages($db) all the chat from the database loads. How do I make this div refresh automatically? Thanks!
EDIT:
The name of the file is "game.php" and the php function is "get_messages()".
For the record I looked at:
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
and
Pass parameters in setInterval function
Javascript
setTimeout(function(){
$.ajax({url: "get_message.php", success: function(result){
var num_records = result.length,
i,
content;
for(i=0;i<num_records;i++){
if (result[i]['character_name'] !== null){
content += "<div class='left'>" + result[i]['character_name'] +": </div>";
}
else{
content += "<div class='left'>" + result[i]['user_name'] +": </div>";
}
content += "<div class='center'>" + result[i]['message'] + "</div><div class='right'>" + result[i]['time'] + "</div>";
}
$('.read_chat').html(content);
}});
}, 5000);
get_message.php
$get_m = "select user_name, message, time, character_name from Chat NATURAL JOIN User LEFT OUTER NATURAL JOIN Character where Chat.game_id =".$_SESSION[game_id]." ORDER BY Chat.chat_id;";
$messages = $db->query($get_m);
$response = array();
foreach ($messages as $row) {
$response[] = $row;
}
echo json_encode($response);
I'd suggest using jQuery $.load, see the example below:
setTimeout(function(){
$('.read_chat').load('get_message.php');
}, 5000);
You'll need to return nice html from the PHP script instead, but it's cleaner.

Getting javascript response from a PHP login function

public function login($username,$password) {
$linkingcon = $this->getConnection();
$sqlquery = "SELECT ac.userID,ac.name,us.usertype FROM users us JOIN accounts ac ON us.userID = ac.userID WHERE us.username='$username' AND us.password='$password';";
$result = mysql_query($sqlquery , $linkingcon);
$this->throwMySQLExceptionOnError($linkingcon);
$row = mysql_fetch_array($result);
$survey = new stdClass();
if($row) {
$res->userID = (int)$row['userID'];
$res->name = $row['name'];
$res->usertype = (int)$row['usertype'];
$string = rand() . 'SurveyLand' . rand() . $username. $password;
$_SESSION['SURVEYLAND_KEY'] = md5($string);
} else {
$res = false;
}
return $res;
}
Hi everyone,
im in a spot of bother regarding a conversion, I need to get a Javascript response from the above php function by calling that php function from another script(HTML)...
P.S
i saw an example in the internet like the below, cant i use method like below get the call
client.sendRequest('hello', null, { 'async': false }, function(rtn) {
if (rtn.isError())
document.write('<li>Request hello error: ' + rtn.getErrorMessage() + "</li>");
else
document.write('<li>Request hello result: ' + rtn.getResult() + "</li>");
});
If you are using ajax return response in json format
return json_encode($res);
Or just print response in script tag
<script>
var res = <?php echo json_encode(login('username','password')); ?>
</script>

Jquery and get the eq value of my returned XML

Hi I have a simple ajax search that returns the results in a table. I can extract the XML and display it fine but what I cannot do is get the index number of the data (var Rows) .
When a user clicks the returned result I believe I would need this in order to retrieve all the data in order to use IE $("name:eq(1)",data).text();. Can anyone help me please and I hope this makes sense !!, thanks
My Jquery code is here
$(document).ready(function(){
$.ajax({
type: "GET",
url: "search_action.php?" + string ,
dataType: "xml",
success: disxml ,
});
})
}
function disxml(data){
dv = $('#crmbox')
$(data).find('list').each(function() {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
var rows = $(this).eq() ;
display = display + "(" + rows + ")" + " Name :" + name + " ID :" + cus_id + " <br>" ;
})
dv.html(r);
};
here is the php that generates my xml
echo '<results>' ;
while($row = mysql_fetch_array($result)) {
$name = $row['name'] ;
$major_id = $row['address1'] ;
echo '<list>' ;
echo '<name>';
echo $name;
echo '</name>';
echo '<mid>';
echo $major_id ;
echo '</mid>';
echo '</list>' ;
} ;
echo '</results>' ;
the extra tag is the close of an earlier function - no relevence to question
It sounds like you want the index you're currently at, in which case use the first parameter passed to the .each() callback, like this:
$(data).find('list').each(function(row) {
var name = $(this).find('name').text();
var cus_id = $(this).find('mid').text();
//row is the index, starting at 0

Categories