I'm currently doing a live search form based on Jquery/ajax/php, but it dosent seems to work.
Can you guys se a problem in my code? :)
function getStates(value) {
$.post("search.php",{ partialState: value }, function(data) {
$("#results").html(data);
});
}
<input type="text" onkeyup="getStates(this.value)" />
<div id="results"></div>
Search.php:
$partialStates = $_POST['partialState'];
$states = mysql_query("SELECT institution_name FROM sb_institutions WHERE institution_name LIKE '%$partialStates%'");
while($stateArray = mysql_fetch_array($states)) {
echo "<div>" . $state['institution_name'] . "</div>";
}
Thanks! :)
Your Code looks ok.
The best way to troubleshoot ajax is to use Firefox with Firebug extension.
That way you can see :
if the function is being fired
if the $_POST values are good : url + parameters
what the server sends as a response
if you have errors in your js
All this will be in the console tab of firebug.
after installing firebug right click on the page and choose debug with firebug.
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
})
;
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
}
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Function
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
Please also see this http://crewow.com/AutoSuggest_Search_Tutorial.php
Live Search Tutorial is a PHP Ajax Based Tutorial which containts following pages and Folders.
Related
I have a bit of a complex query. I'm looking to remove other options when the checkbox is checked on the selected item when the AJAX query results are returned. The reason for this is because currently I have to enter the entire matching result so the result is narrowed down to one item. Otherwise the user would have to put a check on the item they selected and then scroll down about half the page to click the submit button to add the item they selected on a different table.
Here is my code so far;
trigger.js
// SKU search AJAX START //
$(document).ready(function() {
$(".tablesearch").hide();
// Search
function search() {
var query_value = $('input#barcode').val();
if(query_value !== ''){
$.ajax({
type: "POST",
url: "ajax/inventory.php",
data: { query: query_value },
cache: false,
success: function(html){
$("table#resultTable tbody").html(html);
}
});
}return false;
}
$("input#barcode").on("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$(".tablesearch").fadeOut(300);
}else{
$(".tablesearch").fadeIn(300);
$(this).data('timer', setTimeout(search, 100));
};
});
});
// SKU search AJAX END //
db-ajax.php
<?php
// Credentials
$dbhost = "localhost";
$dbname = "cms";
$dbuser = "root";
$dbpass = "pass";
// Connection
global $test_db;
$ajax_db = new mysqli();
$ajax_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$ajax_db->set_charset("utf8");
// Check Connection
if ($ajax_db->connect_errno) {
printf("Connect failed: %s\n", $ajax_db->connect_error);
exit();
}
?>
inventory.php
<?php
require_once "db-ajax.php";
// Output HTML formats
$html = "<tr>";
$html .= "<td>skuString</td>";
$html .= "<td>catString</td>";
$html .= "<td>descString</td>";
$html .= "<td>stockString</td>";
$html .= "<td>priceString</td>";
$html .= "<td><input class='checkBoxes' type='checkbox' name='checkBoxArray[]' value='skuIdString'></td>";
$html .= "</tr>";
// Get the Search
$search_string = preg_replace("/[^,-\/\sA-Za-z0-9_]/", " ", $_POST['query']);
$search_string = $ajax_db->real_escape_string($search_string);
// Check if length is more than 1 character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
$query = 'SELECT s_id, sku_number, category, description, price, in_stock ';
$query .= 'FROM parts_stock AS a JOIN items AS b ON a.stock_id = b.s_id ';
$query .= 'WHERE sku_number LIKE "%'.$search_string.'%" OR category LIKE "%'.$search_string.'%"';
// Do the search
$result = $ajax_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check for results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Output strings and highlight the matches
$d_sku = preg_replace("/".$search_string."/i", "<b>".$search_string."</b>", $result['sku_number']);
$d_cat = $result['category'];
$d_desc = $result['description'];
$d_stock = $result['in_stock'];
$d_price = $result['price'];
$s_id = $result['s_id'];
// Replace the items into above HTML
$o = str_replace('skuString', $d_sku, $html);
$o = str_replace('catString', $d_cat, $o);
$o = str_replace('descString', $d_desc, $o);
$o = str_replace('stockString', $d_stock, $o);
$o = str_replace('priceString', $d_price, $o);
$o = str_replace('skuIdString', $s_id, $o);
// Output it
echo($o);
}
}else{
// Replace for no results
$o = str_replace('skuString', '<span class="label label-danger">No SKUs Found</span>', $html);
$o = str_replace('catString', '', $o);
$o = str_replace('descString', '', $o);
$o = str_replace('stockString', '', $o);
$o = str_replace('priceString', '', $o);
$o = str_replace('skuIdString', '', $o);
// Output
echo($o);
}
}
?>
I have a search function that calls a php file onkeyup. Now in JQuery i have a onClick function that when you click a div from that same JSON call it alerts something, maybe it will be easier to understand from my code below:
<?php
$Connect = new mysqli("localhost", "root", "", "Data");
$Val = $_POST['Val'];
if($Val)
{
$Search = 'SELECT * FROM Users WHERE ';
$Term = explode(" ", $Val);
foreach($Term as $Key)
{
$I = 0;
$I++;
if($I == 1)
{
$Search .= 'Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
else
{
$Search .= 'OR Username LIKE "'.$Key.'%" LIMIT 0, 10 ';
}
}
if($Result = $Connect->query($Search))
{
while($Row = $Result->fetch_assoc())
{
$User = $Row['Username'];
$USearch['S'][] = '<div class="Result"><label class="TText" style="cursor:pointer;">' . $User . '</label></div>';
}
}
}
echo json_encode($USearch);
?>
Now, as you can see, once the user types into a box a div shows up showing all LIKE records of Users, once the div is clicked on nothing happens.
$('.Result').click(function()
{
alert('Hi');
});
When the ajax call return a state of success you can use for example the jquery bind method. (see here for more info http://api.jquery.com/bind/ )
function myAjaxFunct(val){
$.ajax(
{
type: "POST",
url: myPhpFile.php,
datatype: "jsonp",
data: {val: val},
success: function (result) {
$("#jsonResultDisplay").text(result);
$('.Result').bind('click', function() {
alert('hi');
});
}
});
}
You are dynamically creating element that is why it doesn't work.
Use on()method.
Check an example:
http://jsfiddle.net/pZQ8T/
this is actually a part of huge project so i didnt include the css but im willing to post it here if actually necessary.
Ok i have this code
<html>
<head>
<script src="js/jquery.js"></script>
<script type="text/javascript">
var q = "0";
function rr()
{
var q = "1";
var ddxz = document.getElementById('inputbox').value;
if (ddxz === "")
{
alert ('Search box is empty, please fill before you hit the go button.');
}
else
{
$.post('search.php', { name : $('#inputbox').val()}, function(output) {
$('#searchpage').html(output).show();
});
var t=setTimeout("alertMsg()",500);
}
}
function alertMsg()
{
$('#de').hide();
$('#searchpage').show();
}
// searchbox functions ( clear & unclear )
function clickclear(thisfield, defaulttext) {
if (thisfield.value == defaulttext) {
thisfield.value = "";
}
}
function clickrecall(thisfield, defaulttext) {
if (q === "0"){
if (thisfield.value == "") {
thisfield.value = defaulttext;
}}
else
{
}
}
//When you click on a link with class of poplight and the href starts with a #
$('a.poplight[href^=#]').click(function() {
var q = "0";
$.post('tt.php', { name : $(this).attr('id') }, function(output) {
$('#pxpxx').html(output).show();
});
var popID = $(this).attr('rel'); //Get Popup Name
var popURL = $(this).attr('href'); //Get Popup href to define size
//Pull Query & Variables from href URL
var query= popURL.split('?');
var dim= query[1].split('&');
var popWidth = dim[0].split('=')[1]; //Gets the first query string value
//Fade in the Popup and add close button
$('#' + popID).fadeIn().css({ 'width': Number( popWidth ) }).prepend('<img src="images/close_pop.png" class="btn_close" title="Close Window" alt="Close" />');
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = ($('#' + popID).height() + 80) / 2;
var popMargLeft = ($('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
$('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft
});
//Fade in Background
$('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
$('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
return false;
});
//Close Popups and Fade Layer
$('a.close, #fade').live('click', function() { //When clicking on the close or fade layer...
$('#fade , .popup_block').fadeOut(function() {
$('#fade, a.close').remove();
}); //fade them both out
return false;
});
});
</script>
</head>
<body>
<input name="searchinput" value="search item here..." type="text" id="inputbox" onclick="clickclear(this, 'search item here...')" onblur="clickrecall(this,'search item here...')"/><button id="submit" onclick="rr()"></button>
<div id="searchpage"></div>
<div id="backgroundPopup"></div>
<div id="popup" class="popup_block">
<div id="pxpxx"></div>
</div>
</body>
</html>
Ok here is the php file(search.php) where the jquery function"function rr()" will pass the data from the input field(#inputbox) once the user click the button(#submit) and then the php file(search.php) will process the data and check if theres a record on the mysql that was match on the data that the jquery has pass and so if there is then the search.php will pass data back to the jquery function and then that jquery function will output the data into the specified div(#searchpage).
<?
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con=mysql_connect("localhost", "root", "");
if(!$con)
{
die ('could not connect' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE title='$name' OR description='$name' OR type='$name'");
$vv = "";
while($row = mysql_fetch_array($result))
{
$vv .= "<div id='itemdiv2' class='gradient'>";
$vv .= "<div id='imgc'>".'<img src="Images/media/'.$row['name'].'" />'."<br/>";
$vv .= "<a href='#?w=700' id='".$row['id']."' rel='popup' class='poplight'>View full</a>"."</div>";
$vv .= "<div id='pdiva'>"."<p id='ittitle'>".$row['title']."</p>";
$vv .= "<p id='itdes'>".$row['description']."</p>";
$vv .= "<a href='http://".$row['link']."'>".$row['link']."</a>";
$vv .= "</div>"."</div>";
}
echo $vv;
mysql_close($con);
}
else
{
echo "Yay! There's an error occured upon checking your request";
}
?>
and here is the php file(tt.php) where the jquery a.poplight click function will pass the data and then as like the function of the first php file(search.php) it will look for data's match on the mysql and then pass it back to the jquery and then the jquery will output the file to the specified div(#popup) and once it was outputted to the specified div(#popup), then the div(#popup) will show like a popup box (this is absolutely a popup box actually).
<?
//session_start(); start up your PHP session!//
if(isset($_POST['name']))
{
$name = mysql_real_escape_string($_POST['name']);
$con = mysql_connect("localhost","root","");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("juliver", $con);
$result = mysql_query("SELECT * FROM items WHERE id='$name'");
while($row = mysql_fetch_array($result))
{
$ss = "<table border='0' align='left' cellpadding='3' cellspacing='1'><tr><td>";
$ss .= '<img class="ddx" src="Images/media/'.$row['name'].'" />'."</td>";
$ss .= "<td>"."<table><tr><td style='color:#666; padding-right:15px;'>Name</td><td style='color:#0068AE'>".$row['title']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Description</td> <td>".$row['description']."</td></tr>";
$ss .= "<tr><td style='color:#666; padding-right:15px;'>Link</td><td><a href='".$row['link']."'>".$row['link']."</a></td></tr>";
$ss .= "</td></tr></table>";
}
echo $ss;
mysql_close($con);
}
?>
here is the problem, the popup box(.popup_block) is not showing and so the data from the php file(tt.php) that the jquery has been outputted to that div(.popup_block) (will if ever it was successfully pass from the php file into the jquery and outputted by the jquery).
Some of my codes that rely on this is actually working and that pop up box is actually showing, just this part, its not showing and theres no data from the php file which was the jquery function should output it to that div(.popup_block)
hope someone could help, thanks in advance, anyway im open for any suggestions and recommendation.
JULIVER
First thought, the script is being called before the page is loaded. To solve this, use:
$(document).ready(function()
{
$(window).load(function()
{
//type here your jQuery
});
});
This will cause the script to wait for the whole page to load, including all content and images
if you're using ajax to exchange data into a php file. then check your ajax function if its actually receive the return data from your php file.
I have a Ajax PHP MySQL live search that basically pulls out food items from a MySQL database and presents them in a drop-down list, as users enter they search term, one item per line, just like searching in Google.
What I need is a way to allow users to click on a particular result item, and for that to open up, just below the item clicked, a box with a few radio buttons listing options with various amounts of that particular food item. The user would then be able to select an amount option and click submit to save their selection.
I know PHP and MySQL and HTML quite well, but JS is a bit of a challenge, so I'd appreciate if you could be detailed in your answer.
Below are some code snippets with what I have at this point:
The HTML search form:
<input type="text" size="30" name="food_name" id="q" value="" onkeyup="sendRequest(this.value);" autocomplete="off"/>
The AJAX code on same page w/ search form:
function createRequestObject() {
var req;
if(window.XMLHttpRequest){
// Firefox, Safari, Opera...
req = new XMLHttpRequest();
} else if(window.ActiveXObject) {
// Internet Explorer 5+
req = new ActiveXObject("Microsoft.XMLHTTP");
} else {
alert('Problem creating the XMLHttpRequest object');
}
return req;
}
// Make the XMLHttpRequest object
var http = createRequestObject();
function sendRequest(q) {
// Open PHP script for requests
http.open('get', 'checkfoods.php?q='+q);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4 && http.status == 200){
// Text returned FROM the PHP script
var response = http.responseText;
if(response) {
// UPDATE ajaxTest content
document.getElementById("searchResults").innerHTML = response;
}
}
}
The PHP script that looks into a table called FOOD_DES into MySQL and brings back the results populating the drop-down list of foods:
include 'my-food-dtabase.php';
$searchQry = isset($_GET['q']) ? mysql_real_escape_string($_GET['q']) : false;
if ($searchQry) {
$searchString = $_GET['q'];
$sql = mysql_query("SELECT NDB_No, FdGrp_Cd, Long_Desc FROM FOOD_DES WHERE Long_Desc LIKE '%".$_GET['q']."%' ORDER BY Long_Desc ASC");
if($searchString != NULL) {
while($row = mysql_fetch_assoc($sql)) {
echo "<span id=foodlist>".$row['Long_Desc']."<br /></span>";
}
}
if(mysql_num_rows($sql) == 0) {
echo "<span class=medium_white>Food item not found. Try a different name or keyword.</span>";
}
}
This isn't necessarily a complete answer but a pointer in the right direction.
You will save yourself a tonne of time and effort by using jQuery over pure JavaScript. It will also reduce your step 2 down to a few lines of code as it comes with its own Ajax API. Here's a tutorial on its Ajax system - much easier!
jQuery UI is a great extension to jQuery which helps you to build user interfaces, part of this is the dialog widget. I think the 'Modal form' dialog example is very similar to what you are trying to achieve when you click the 'create new user' button. Click 'View Source' to see how they did it.
Also from what I can see in step 3 you aren't sanitising your query, $_GET['q'] is being thrown right into your query string. You should replace this with $searchQry which you already defined a few lines above.
Here is something you can do with Ajax, PHP and JQuery. Hope this helps or gives you a start.
See live demo and source code here.
http://purpledesign.in/blog/to-create-a-live-search-like-google/
Create a search box, may be an input field like this.
<input type="text" id="search" autocomplete="off">
Now we need listen to whatever the user types on the text area. For this we will use the jquery live() and the keyup event. On every keyup we have a jquery function “search” that will run a php script.
Suppose we have the html like this. We have an input field and a list to display the results.
<div class="icon"></div>
<input type="text" id="search" autocomplete="off">
<ul id="results"></ul>
We have a Jquery script that will listen to the keyup event on the input field and if it is not empty it will invoke the search() function. The search() function will run the php script and display the result on the same page using AJAX.
Here is the JQuery.
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#search').focus();
});
//Listen for the event
$("input#search").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#search').val();
$('b#search-string').html(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search_st.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
});
In the php, shoot a query to the mysql database. The php will return the results that will be put into the html using AJAX. Here the result is put into a html list.
Suppose there is a dummy database containing two tables animals and bird with two similar column names ‘type’ and ‘desc’.
//search.php
// Credentials
$dbhost = "localhost";
$dbname = "live";
$dbuser = "root";
$dbpass = "";
// Connection
global $tutorial_db;
$tutorial_db = new mysqli();
$tutorial_db->connect($dbhost, $dbuser, $dbpass, $dbname);
$tutorial_db->set_charset("utf8");
// Check Connection
if ($tutorial_db->connect_errno) {
printf("Connect failed: %s\n", $tutorial_db->connect_error);
exit();
$html = '';
$html .= '<li class="result">';
$html .= '<a target="_blank" href="urlString">';
$html .= '<h3>nameString</h3>';
$html .= '<h4>functionString</h4>';
$html .= '</a>';
$html .= '</li>';
$search_string = preg_replace("/[^A-Za-z0-9]/", " ", $_POST['query']);
$search_string = $tutorial_db->real_escape_string($search_string);
// Check Length More Than One Character
if (strlen($search_string) >= 1 && $search_string !== ' ') {
// Build Query
$query = "SELECT *
FROM animals
WHERE type LIKE '%".$search_string."%'
UNION ALL SELECT *
FROM birf
WHERE type LIKE '%".$search_string."%'"
;
$result = $tutorial_db->query($query);
while($results = $result->fetch_array()) {
$result_array[] = $results;
}
// Check If We Have Results
if (isset($result_array)) {
foreach ($result_array as $result) {
// Format Output Strings And Hightlight Matches
$display_function = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['desc']);
$display_name = preg_replace("/".$search_string."/i", "<b class='highlight'>".$search_string."</b>", $result['type']);
$display_url = 'https://www.google.com/search?q='.urlencode($result['type']).'&ie=utf-8&oe=utf-8';
// Insert Name
$output = str_replace('nameString', $display_name, $html);
// Insert Description
$output = str_replace('functionString', $display_function, $output);
// Insert URL
$output = str_replace('urlString', $display_url, $output);
// Output
echo($output);
}
}else{
// Format No Results Output
$output = str_replace('urlString', 'javascript:void(0);', $html);
$output = str_replace('nameString', '<b>No Results Found.</b>', $output);
$output = str_replace('functionString', 'Sorry :(', $output);
// Output
echo($output);
}
}
http://koding.info/2013/07/ajax-search-box-php-mysql-jquery/
I have implemented a demo Live search application which uses Wordpress database.
Take a look.
it may help you.
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?