I create a huge JSON-Object and save it in my database. But when I load the "string" and echo it in PHP, I can't access the JSON Object in JQuery. Do I have to consider something if I want to save my JSON Object in a MySQL Database (when I just create the Array and then echo it with "echo json_encode($arr);" it works fine, but I need to save the Object for caching).
{"247":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]},{"248":{"0":"This is a
question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer
2","962","0"],["Answer
3","961","0"],["Answer
4","963","0"]]}}
just an excerpt
If I just echo this JSON-Object, everything works fine, but if I load the same string from the database and echo it, it doesn't work.
Update 1: forget to tell that I'm using a TEXT-Field with UTF8_general_ci collation
Update 2: Maybe a little bit more code:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data[247][0]);
}, "json");
return false;
});
}
this loads the script and should alert "This is a question"
<?php
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
echo $output;
?>
this is the script, where I load the database entry with the JSON-Object.
Update 3:
I think I solved the problem. Some break sneaked into my JSON-Object so I do this, before the output:
$output = str_replace("\n", "", $output);
$output = str_replace("\r", "", $output);
$output = str_replace("\r\n", "", $output);
I'd suggest looking at what your javascript is seeing. Instead of asking jQuery to interpret the json for you, have a look at the raw data:
function start() {
$(".start").click(function () {
$.post("load_script.php", { }, function(data){
alert(data);
}, "text");
return false;
});
}
For example, if part of the string gets oddly encoded because of the UTF-8, this might cause it to appear.
Once you've done that, if you still can't spot the problem, try this code:
var data1, data2;
function start() {
$(".start").click(function () {
$.post("load_script.php", {src: "db" }, function(data){
data1 = data;
}, "text");
$.post("load_script.php", {src: "echo" }, function(data){
data2 = data;
}, "text");
if (data1 == data2) {
alert("data1 == data2");
}
else {
var len = data1.length < data2.length ? data1.length : data2.length;
for(i=0; i<len; ++i) {
if (data1.charAt(i) != data2.charAt(i)) {
alert("data1 first differs from data2 at character index " + i);
break;
}
}
}
return false;
});
}
And then change the PHP code to either return the data from the database or simply echo it, depending on the post parameters:
<?php
if ($_POST['src'] == 'db')) {
require_once('connect.php');
$ergebnis = mysql_query("SELECT text FROM cache_table ORDER BY RAND() LIMIT 1");
while($row = mysql_fetch_object($ergebnis)) {
$output = $row->text;
}
}
else {
$output = '{"247":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]},{"248":{"0":"This is a question","1":"","2":"247","3":"0","answers":[["Answer1","960","1"],["Answer 2","962","0"],["Answer 3","961","0"],["Answer 4","963","0"]]}}';
}
echo $output;
?>
Hope that helps!
I got this to work in a slightly different manner. I've tried to illustrate how this was done.
In Plain English:
use urldecode()
In Commented Code Fragments
$json = $this->getContent($url); // CURL function to get JSON from service
$result = json_decode($json, true); // $result is now an associative array
...
$insert = "INSERT INTO mytable (url, data) ";
$insert .= "VALUES('" . $url . "', '" . urlencode(json_encode($result)) . "') ";
$insert .= "ON DUPLICATE KEY UPDATE url=url";
...
/*
** Figure out when you want to check cache, and then it goes something like this
*/
$sqlSelect = "SELECT * FROM mytable WHERE url='" . $url . "' LIMIT 0,1";
$result = mysql_query($sqlSelect) or die(mysql_error());
$num = mysql_numrows($result);
if ($num>0) {
$row = mysql_fetch_assoc($result);
$cache = json_decode(urldecode($row['data']), true);
}
Hope this is helpful
Maybe you use varchar field and your string just doesn't fit in 255 chars?
Related
I'm working on a php project and the search function from the database is not returning any results or any error. Below is the code for the search function:
function searchweb() {
console.log("click");
//e.preventDefault();
searchWebsite = $("#searchWebsite").val();
if (searchWebsite == "")
$("#searchWebsite").focus();
else {
console.log("else");
$("#search").html("Searching..");
$("#search").attr("disabled", true);
var excat = "like";
if ($('input[type=checkbox]').prop('checked'))
excat = "match";
$.post("userinput.php", {
searchWebsite: $("#searchWebsite").val(),
excat: excat
}, function (data) {
console.log("hey"+data);
populateSearch(data);
});
function populateSearch(data){
data = JSON.parse(data);
$('#result').empty();
$.each(data, function (key, value) {
//console.log(data);
$('#result').append("<tr>\
<td><a href='"+value.website_name+"' target='_blank'><i class='glyphicon glyphicon-search'></i></a></td>\
<td>"+value.website_name+"</td>\
<td>"+value.avg_score+"</td>\
<td><img class = 'imgs img-responsive center' src='../img/"+value.remark+".png' alt ='"+value.remark+"' />\
</td></tr>");
});
}
// console.log(searchWebsite);
$("#search").html("Search Website");
$("#search").attr("disabled", false);
}
}
The 'searchweb' function calls the post method to search in the mysql database. I'm using phpmyadmin for this project. The code for post function in userinput file:
if(isset($_POST['searchWebsite'])){
$searchWebsite = $_POST['searchWebsite'];
$type = $_POST['excat'];
$sql = "SELECT * from websites WHERE ";
//for excact match
if($type=="match")
$sql.= "MATCH(tags) Against('$searchWebsite') ORDER BY avg_score DESC";
//for tags contaionun gthose words
else
$sql.= "tags LIKE '%$searchWebsite%' ORDER BY avg_score DESC";
$result = mysqli_query($db, $sql);
if($result){
$rr = array();
$i=1;
while($row = mysqli_fetch_assoc($result))
{ $rr[] = $row;
$i=$i+1;}
echo json_encode($rr);
}
else
{
echo "<script type='text/javascript'>alert('Error: '".mysqli_error($db).");</script>";
}
}
No error will be spit back as this is a .post in javascript call / AJAX request. AJAX will not dynamically parse the javascript error code you're trying to trap within the AJAX request.
It's better to do something like this:
PHP side:
Replace:
echo "alert('Error: '".mysqli_error($db).");";
With:
echo json_encode( [ 'error' => mysqli_error($db) ] );
Javascript Side:
// Note you shouldn't have to parse JSON since on the PHP side the error array has been encoded as json
if( ! $.isEmptyObject(data.error) ) {
alert( data.error );
}
Im retrieving an array from php file called check_num.php :-
check_num.php
<?php
include 'config.php';
session_start();
$VALUE = $_SESSION["some_session_variable"];
if(isset($_POST['default'])){
$ert = "SELECT * FROM table_name WHERE something = '$VALUE' ORDER BY p_id ASC ";
$qty = mysql_query($ert);
$fgh = mysql_num_rows($qty);
$ertz = "SELECT something, COUNT(something) FROM table_name WHERE something = '$VALUE'
AND something >= 1 GROUP BY p_id ORDER BY p_id ASC";
$qtyz = mysql_query($ertz);
$tyui = mysql_num_rows($qtyz);
$data = array(
"post" => $fgh,
"likes" => $tyui
);
echo json_encode($data);
} else {
echo "0";
}
?>
Now comes the jquery part :-
<script>
$(document).ready(function(){
setInterval(function(){
var def = "one";
$.post("check_num.php", {'default': def }, function(response){
if(response != 0){
document.getElementById("total_array_count").innerHTML = response;
//document.getElementById("total_like_count").innerHTML = response.likes;
//document.getElementById("total_post_count").innerHTML = response.post;
------------------OR THIS Method-----------------
var my_array = response;
//var post_number = my_array["post"];
document.getElementById("total_array_count").innerHTML = my_array;
//document.getElementById("total_post_count").innerHTML = '<b>'+post_number+'</b>';
}
else {
document.getElementById("total_array_count").innerHTML='Error occured !';
}
});
},2500);
});
</script>
Now received output is {"post":10,"likes":1} , its an array . But when i access array values response.post or my_array["post"] the value returned is undefined.
I had gone through this :- http://www.w3schools.com/js/tryit.asp?filename=tryjs_array_object
And kind of this too:- jQuery .val() returns undefined for radio button
Followed it but no success !
Please correct my mistakes .
Run JSON.parse() on your result before trying to access the values. The result comes as a raw string and you have to convert it to an object first.
result = JSON.parse(result);
Alternatively, since you're already using jQuery, you can use jQuery's alias for the function.
result = $.parseJSON(result);
They are essentially the same thing.
I've read multiple similar posts on this, and my code seems to match the suggestions, but still no data returned.
Here's my JS:
$.post('php/get_last_word.php', { user_id : userID },
function( data ) {
currentLanguage = data.language_id;
currentWord = data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
},'json');
And the relevant php:
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$encoded = json_encode($row);
echo $encoded;
}
And the resulting log:
Connected successfully{"language_id":"1","word_id":"1"}
So the json array is being echoed, but it's not ending up in data, because currentLanguage and currentWord are not being populated. Is this a problem with asynchronicity? Or something else?
Make sure you have a valid json coming back to your variable from your PHP script
IF your json object is like this,
{"language_id":"1","word_id":"1"}
You can access the values like this
currentLanguage = data.language_id;
currentWord = data.word_id;
Example JsFiddle http://jsfiddle.net/NuS7Z/8/
You can use http://jsonlint.com/ to verify your jSon is in correct form or not.
Specifying json as the data type value in your post request will make sure the reponse is coming back as json format to the success callback.
$.post('php/get_last_word.php',{user_id:userID}, dataType:"json",function(data){
currentLanguage = data.language_id;
currentWord = data.word_id;
});
You can also use getJson to simply get json data. getJson is a shorthand of ajax Call with datatype as json
http://api.jquery.com/jQuery.getJSON/
Try changing your JS to:
$.getJSON('php/get_last_word.php', { user_id : userID },
function( response ) {
if (response.success) {
currentLanguage = response.data.language_id;
currentWord = response.data.word_id;
console.log("currentLanguage = " + currentLanguage)
console.log("currentWord = " + currentWord);
} else {
alert('Fail');
}
});
and your PHP to:
<?php
$success = false;
$data = null;
$user_id=$_POST['user_id'];
mysql_select_db(wordsicle_search);
$sql = "SELECT `language_id`, `word_id` FROM `save_state` WHERE `user_id`=$user_id";
$result = mysql_query($sql,$con);
while ($row = mysql_fetch_assoc($result)) {
$success = true;
$data = $row;
}
// I generally format my JSON output array like so:
// Response
header('Content-Type: application/json');
echo json_encode(array(
'success' => $success,
'data' => $data
));
?>
That way its more organized and don't forget to set the content type.
Hope that helps.
i am a noob to jquery and i want to know how to make use of if else for the following:
on the server side there is a if for number of rows is equal to 0 and else some JSON part.
$age= mysql_query("SELECT title FROM parent WHERE id ='$name'");
$age_num_rows = mysql_num_rows($age);
if ($age_num_rows==0)
{
echo "true";
}
else
{
$sql ="SELECT * FROM parentid WHERE id = '$name'"; //$name is value from html
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$abc_output = array('title' => $row['title'],'age' => $row['age']);
}
echo json_encode($abc_output);
}
Now coming to Jquery part :
If the above PHP code go to if part then i want to display an alert box or if it goes to else part it needs to insert some values into the forms.
Here is something i tried but it did not work.
$(document).ready(function(){
$("#button1").click(function(){
$.getJSON('script_1.php',function(data){
if (data=='true') {
alert ('hello')
}
else {
$.post('script_1.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
},
"json");
}
});
});
Edited:
$(document).ready(function(){
$("#button1").click(function(){
$.post(
'script.php',
{ id: $('input[name="id"]', '#myForm').val() },
function(json) {
var data = JSON.parse(json);
if (data.length === 0){
alert('no data');
}
else{
$("input[name='title']").val(json.title);
$("input[name='age']").val(json.age);
}},
"json"
);
});
});
PHP side
$name = mysql_real_escape_string($_POST['id']);
$sql ="SELECT * FROM parentid WHERE id = '$name'";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if ($row) {
$row= array('title' => $row['title'],'age' => $row['age']);
echo json_encode($row);
} else {
echo json_encode(array());
}
You need to parse the JSON before you can use it like that. Modern browsers will have built in support for JSON.parse(yourJSON), but to account for those that don't, you should use Douglas Crockford's JavaScript JSON library. Including it will provide JSON.parse() if the browser doesn't have it already.
For the if-else stuff you're doing in the PHP, the common practice is to echo out an empty JSON object or array, so you don't have to test for things like no rows on the server side. You could do something as simple as this, later accounting for your database column names:
$result = mysql_query($sql);
$row = mysql_fetch_assoc($result);
if ($row) {
echo json_encode($row);
} else {
echo json_encode(array());
}
Back in the JavaScript, you could then do something like this:
var data = JSON.parse(json);
if (data.length === 0) {
alert('no data');
} else {
$("input[name='title']").val(data.title);
$("input[name='age']").val(data.age);
}
jeroen is right though, you only need to use one AJAX call.
There seem to be a few problems:
You are treating the data returned from getJSON as if it is plain
text
The php that you are calling from javascript does not always
return json
You are doing 2 ajax requests; getJSON and post where you only need one: The first call to getJSON without any data will never reach the else condition
By the way, where does $name come from in your php script? For your second ajax call to work, it needs to be something like mysql_real_escape_string($_POST['id']) or (int) $_POST['id'] if it is an integer.
Edit: I think it would be easiest to get rid of the .post and just use the first ajax call. So you will need to change:
$.getJSON('script_1.php',function(data){
to something like:
$.getJSON('script_1.php?id=' + $('input[name="id"]').val(), function(data) {
and in your php you need to use something like:
$name = mysql_real_escape_string($_GET['id']);
My Jquery code
function nalozi() {
var id_skupine = $('#skupina option:selected').val();
$('#artikel option').remove();
//$('#artikel').append('<option value="'+id_skupine+'">'+id_skupine+'</option>');
$.getJSON('artikli.php', {id_skupine:$('#skupina').val()}, function(data) {
$.each(data, function(index,item) {
$("#artikel").append("<option value=" + item.id + ">" + item.ime_artikla + "</option>");
});
});
}
$(document).ready(function() {
nalozi();
$('#skupina').change(function() {
nalozi();
});
});
AND PHP CODE
<?php
if(isset($_GET['id_skupine']))
{
$id_skupine = $_GET['id_skupine'];
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
$velikost = mysql_num_rows($poizvedba);
for ($i=0;$i<$velikost;$i++)
{
$elements[]=mysql_fetch_assoc($poizvedba);
}
}
echo json_encode($elements);
?>
I don't get the values back.
Update:
You should never put variable before sanitalizing/validating/type-converting into your sql queries. If your the value you expect in query string is a number, you need to properly type-cast it like this:
$id_skupine = (int) $_GET['id_skupine'];
And if it is a string, the least you can do is to use mysql_real_escape_string function:
$str = mysql_real_escape_string($_GET['str']);
Shouldn't you be grabbing the records from db like this:
if(isset($_GET['id_skupine']))
{
$id_skupine = $_GET['id_skupine'];
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
$velikost = mysql_num_rows($poizvedba);
while($row = mysql_fetch_assoc($poizvedba)){
$elements[] = $row['ime_artikla'];
}
}
echo json_encode($elements);
Might be your query is not returning anything
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '$id_skupine'");
Remove single quote from '$id_skupine'
Try
$poizvedba = mysql_query("SELECT id,ime_artikla FROM artikli WHERE id_skupine = '".$id_skupine."'");