How to display json data in a smarty template? - php

I'm using smarty and php for my website. There is some code which converts the data into json. I want to use that data in a smarty template. That data is a set of error messages and I want to display those messages in a assigned smarty template at desired ID. I'm not able to get that in smarty template. Actually what is happening is the error messages are displayed on a plain page instead in the desired tag.
Following is my smarty and PHP code:
Following is the smarty code where I want to display the error messages:
if $error_msg}<div class="error-info">{$error_msg.error_msgs}</div>{/if}
Now following is my PHP code:
<?php
if($request['form_submitted']=='yes') {
$ret = $objPracticeSheet->InsertPracticeSheet($request, $practice_sheet_error_messages);
if(!$ret) {
$error_msg = $objPracticeSheet->GetAllErrors();
$data = array();
$data['error_message'] = $error_msg['error_msgs'];
$data = json_encode($data);
echo $data;
die;
} else {
$data = array();
$data['success_message'] = "success";
$data = json_encode($data);
echo $data;
die;
}
} else {
$all_subjects = $objSubjectsTopicsQues->GetAllSubjectsHavingTopics();
$smarty->assign('all_subjects', $all_subjects);
$smarty->assign('sheet_type', 'practice');
$bread_crumbs_text = 'Add Practice Sheet';
$submit_value = 'Submit';
$cancel_value = 'Cancel';
$file_to_show = 'manage-practice-sheet.tpl';
}
$smarty->assign("op", $op);
$smarty->assign("query_string", $query_string);
$smarty->assign("bread_crumbs_text", $bread_crumbs_text);
$smarty->assign("submit_value", $submit_value);
$smarty->assign("cancel_value", $cancel_value);
$smarty->assign("error_msg", $error_msg);
$smarty->assign("file_to_show", $file_to_show);
/*$smarty->assign('create', '-active');
$smarty->assign("sub_menu_file", "epn-create-sub-menu.tpl");
$smarty->assign('practice_sheet', '-active');*/
$smarty->assign('practice_sheet', 'active');
$smarty->assign('prepare', 'selected');
$smarty->display("index.tpl");
?>
Can you help me in displaying the error messages json data in the above div? Thanks in advance. I'm also attaching the screenshot of the current output.

Use JavaScript to parse the JSON, then put the errors in the div.
To make this easier, let's give your div an id:
<div id="error-info-main" class="error-info"></div>
Then
<script>
{literal}
(function() {
var error_json = {/literal}{$error_msg.error_msgs}{literal};
var errors = JSON.parse(error_json);
document.getElementById('error-info-main').innerHTML = errors.error_message;
}());
{/literal}
</script>
Alternatively, you could just the pass the message itself from PHP:
$smarty->assign("error_msg", $error_msg->error_message);
This may not be 100% correct, as I don't have your data to test with, but I believe that's right. You get the idea at any rate.

Related

Want to perform php using OnClick function without clearing the current web page

This is the js script at the bottom of my wp post.
<script type="text/javascript" src="jquery-1.10.2.min.js">
</script>
<script type="text/javascript">
var id = 'downloadid';
var data_from_ajax;
$.post('download.php', {id : id}) .done(function(data) {
data_from_ajax = data;
});
function hey() {
document.write(data_from_ajax);
}
</script>
Function hey was being called from a link OnClick function. When using this, the page would successfully perform the php code on download php (update a db then download a file) although it would clear the current page I was on. What I wanted to do was perform the php and keep the current page template. So next I tried using
document.getElementById("download").innerHTML = data_from_ajax;
instead of document.write. I made a div with the id download. Now when I click it, it simply won't perform the php. when I replace the data_from_ajax with a string, it gladly puts it in the div though.
Any help would be great.
EDIT:
my html is
download
<div id='download'>&nbsp</div>
http://jsfiddle.net/7smJE/
From PHP code which you've provided, I think you should replace document.write() in your code with $('#download').html(). This way you don't need to put the returned result in your download div anymore because when PHP page gets loaded it'll do this for you and you have to put your $.post in hey() function too because you need this to perform when your link gets clicked.
PHP:
<?php
$fileid = $id;
if (is_file('d84ue9d/' . $fileid . '.apk'))
{
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("localhost","docvet95_check","%tothemax%","docvet95_downcheck");
$result = mysqli_query($con,"SELECT * FROM `download-check` where ip = '$ip'");
while ($row = mysqli_fetch_array($result))
{
$files = $row['files'];
$downloads = $row['downloads'];
}
if ($downloads > 4)
{
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%61%6C%65%72%74%28%27%59%6F%75%5C%27%76%65%20%64%6F%77%6E%6C%6F%61%64%65%64%20%66%69%76%65%20%6F%72%20%6D%6F%72%65%20%66%69%6C%65%73%2E%20%46%6F%72%20%72%69%67%68%74%20%6E%6F%77%2C%20%74%68%69%73%20%69%73%20%6F%6B%61%79%2E%20%49%6E%20%74%68%65%20%66%75%74%75%72%65%2C%20%79%6F%75%20%77%69%6C%6C%20%6E%65%65%64%20%74%6F%20%63%6F%6D%70%6C%65%74%65%20%61%20%73%75%72%76%65%79%20%69%6E%20%6F%72%64%65%72%20%74%6F%20%63%6F%6E%74%69%6E%75%65%20%64%6F%77%6E%6C%6F%61%64%69%6E%67%2E%20%54%68%61%6E%6B%20%79%6F%75%20%66%6F%72%20%75%73%69%6E%67%20%6F%75%72%20%77%65%62%73%69%74%65%27%29%3B%20%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%2F%61%70%6B%73%2F%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
}
else
{
$downloadq = $downloads + 1;
$there = $result->num_rows;
if ($there <1)
{
$addidnip = mysqli_query($con,"INSERT INTO `download-check` (ip, files, downloads) VALUES ('$ip', '$fileid', 1)");
}
else
{
$idtoarray = explode(",", $files);
if (!in_array($fileid, $idtoarray))
{
array_push($idtoarray, $fileid);
$newfile = implode(",", $idtoarray);
$adddw = mysqli_query($con,"UPDATE `download-check` SET downloads=$downloadq, files='$newfile' where ip = '$ip'");
}
}
print "<script type=\"text/javascript\">";
print "$('#download').html(unescape('%3C%73%63%72%69%70%74%20%74%79%70%65%3D%22%74%65%78%74%2F%6A%61%76%61%73%63%72%69%70%74%22%3E%0A%77%69%6E%64%6F%77%2E%6F%70%65%6E%28%27%64%38%34%75%65%39%64%2F". $fileid . "%2E%61%70%6B%27%2C%27%5F%73%65%6C%66%27%29%0A%3C%2F%73%63%72%69%70%74%3E'));";
print "</script>";
}
}
else
{ echo 'Whoops, looks like we couldn\'t find that file. You could try searching for it?'; }
?>
JavaScript:
var id = 'downloadid';
var data_from_ajax;
function hey() {
$.post('download.php', {id : id});
}
But I recommend you to return the exact data from your PHP without any extra tag and then use it this way:
var id = 'downloadid';
function hey() {
$.post('download.php', {id : id}).done(function(data) {
$("#download").html(unescape(data));
});
}
From what I can see without the fiddle:
The hey function is probably fired before the done function is ready. Why don't you call hey() from within done()?

How do I get data from requested server page?

I got two php pages:
client.php and server.php
server.php is on my web server and what it does is open my amazon product page and get price data and serialize it and return it to client.php.
Now the problem I have is that server.php is getting the data, but when I return it and do echo after using unserialize(), it shows nothing. But if I do echo in server.php, it shows me all the data.
Why is this happening? Can anyone help me please?
This the code I have used:
client.php
$url = "http://www.myurl.com/iec/Server.php?asin=$asin&platform=$platform_variant";
$azn_data = file_get_contents($url);
$azn_data = unserialize($azn_data);
echo "\nReturned Data = $azn_data\n";
server.php
if(isset($_GET["asin"]))
{
$asin = $_GET["asin"];
$platform = $_GET["platform"];
echo "\nASIN = $asin\nPlatform = $platform";
//Below line gets all serialize price data for my product
$serialized_data = amazon_data_chooser($asin, $platform);
return($serialized_data);
}
else
{
echo "Warning: No Data Found!";
}
On server.php , you need to replace your following line:
return($serialized_data);
for this one:
echo $serialized_data;
because client.php reads the output of server.php, return is used to pass information from functions to caller code.
UPDATE:
Apart from the fixes above, you're hitting a bug in unserialize() function that presents with some special combination of characters, which your data seems to have, the solution is to workaround the bug by base64() encoding the data prior to passing it to serialize() , like this:
In client.php:
$azn_data = unserialize(base64_decode($azn_data));
In server.php:
echo base64_encode($serialized_data);
Source for this fix here .
You are not serializing your data on server side so there is nothing to deserialize on client side.
return(serialize($serialized_data));
Edit:
if(isset($_GET["asin"]))
{
$asin = $_GET["asin"];
$platform = $_GET["platform"];
echo "\nASIN = $asin\nPlatform = $platform";
//Below line gets all serialize price data for my product
$serialized_data = amazon_data_chooser($asin, $platform);
die(serialize($serialized_data));
}
else
{
echo "Warning: No Data Found!";
}

How to receive data from a database using AJAX

I use a comment box in my web page and saved user input comments. Now what I want is to display them using AJAX. I set a javascript timer to get comments one by one. But I don't know how to use AJAX to retrieve data. This is the php file
<?php
$link = mysql_connect("localhost","root","");
mysql_select_db("continental_tourism");
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
$comment_number = rand(1,$counter);
$query_comment = mysql_query("SELECT * FROM comment WHERE comment_id = '$comment_number'");
if (!$query_comment) {
die('Invalid query: ' . mysql_error());
}
while($result_comment = mysql_fetch_array($query_comment)) {
echo $result_comment['comment'];
}
?>
following is the script part in the main file.
function timeMsg()
{
var t=setTimeout("show_comment()",3000);
}
function show_comment(){
}
How should i write the AJAX code to the?
function show_comment()
If someone can explain the AJAX code line by line, I'll be great full.
You have to move your all php script to another php file say getdata.php and use your ajax function in your file where you want to show the data say it is index.php. (this is for easy to use code). Now your index.php file should look like
<html>
<body>
<div id="comments"></div>
</body>
<script src="include/jquery.js" type="text/javascript"></script>
<script type="text/javascript>
function show_comments() {
$.ajax({
url:getdata.php
success:function(data){
$("#comments").append(data);
}
});
</script>
</html>
I am using jquery.ajax function of jquery. This is some hint how you can do this. I hope it will help you to accomplish your task.
Use jQuery's .get() method using the link to your PHP script as URL. That should call your PHP script and your script should echo the output.
You should consider json_encode-ing your output from php script before echoing it.
And I think, instead of doing this -
$query = "SELECT comment_id from comment";
$result = mysql_query($query);
$counter = 0;
while ($row = mysql_fetch_assoc($result))
{
$counter++;
}
you can query SELECT COUNT(comment_id) from comment and get the count.

Jquery Validation Remote Check Unique Not Working

I wanted to post this online because I have been searching for days on this JQuery Remote validation issue. I cannot get it to work. I think my PHP code is correct as I have test the URL with a query in the URL and it returns false and true depending on with the recordset count is one or more
This is my Jquery Validate Code:
// validate form and submit
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#myform").validate({
rules: {
ord_ref: {
required: true,
minlength: 12,
remote: "check_ord_ref.php"
},
messages: {
ord_ref: {
remote: "Order Number Does Not Exist"
}
}
}
});
});
This is my PHP code for the remote page "check_ord_ref.php"
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = 'false';
} else {
$valid = 'true';
}
echo $valid;
Please someone can you help solve the puzzle for myself and anyone else having issues
Using JQuery 1.5.2min
Validates OK without remote function
Ok, so I'm no PHP expert, but I do know that jQuery Validate expects the following result from a remote validation method:
The response is evaluated as JSON and must be true for valid elements,
and can be any false, undefined or null for invalid elements
Sending down "true" or "false" (note the quotation marks) is going to result in the value being parsed as the error message instead of being evaluated as a boolean primitive.
Back to the PHP part, I think you should probably use json_encode with a boolean primitive. I'm not quite sure the way to do this in PHP, but I believe it would be something like this:
$colname_rscheck_ord_ref = "-1";
if (isset($_GET['ord_ref'])) {
$colname_rscheck_ord_ref = (get_magic_quotes_gpc()) ? $_GET['ord_ref'] : addslashes($_GET['ord_ref']);
}
mysql_select_db($database_conn, $conn);
$query_rscheck_ord_ref = sprintf("SELECT ref_ord FROM orders WHERE ref_ord = '%s'", $colname_rscheck_ord_ref);
$rscheck_ord_ref = mysql_query($query_rscheck_ord_ref, $conn) or die(mysql_error());
$row_rscheck_ord_ref = mysql_fetch_assoc($rscheck_ord_ref);
$totalRows_rscheck_ord_ref = mysql_num_rows($rscheck_ord_ref);
if($totalRows_rscheck_ord_ref < 0){
$valid = false; // <-- Note the use of a boolean primitive.
} else {
$valid = true;
}
echo json_encode($valid);
This problem seems to be plaguing remote validation scripters and the jQuery documentation on the matter is clearly lacking.
I notice you are using jQuery 1.5.2: from what I understand (and found from experience) you must use the jQuery callback that is sent to the remote script with $_REQUEST with versions after 1.4, AND jQuery is expecting "true" or "false" as a STRING. Here is an example, confirmed working on multiple forms (I'm using jQuery 1.7.1):
if($totalRows_rscheck_ord_ref < 0){
header('Content-type: application/json');
$valid = 'false'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
} else {
header('Content-type: application/json');
$valid = 'true'; // <---yes, Validate is expecting a string
$result = $_REQUEST['callback'].'('.$check.')';
echo $result;
}
I found this answer here (in the answers section), randomly, and have since stopped pulling out my hair. Hope this helps someone.
To add to Andrew Whitaker's response above, I must stress that you are sure that the response is strictly JSON and that there are no other content types being returned. I was having the same issue with my script, and everything appeared to be set properly - including using json_encode(). After some troubleshooting with Firebug's NET tab, I was able to determine that PHP notices were being sent back to the browser converting the data from JSON to text/html. After I turned the errors off, all was well.
//check_validate.php
<?php
// some logic here
echo json_encode(true);
?>

Detect when Ajax request to search page returns 0 results before displaying HTML

I'm trying to get json code from page.I use this
private function __ajax_admin_search($username = '')
{
$result = $this->admin_login->Admin_Username_Ajax($username);
$count = count($result);
for ($i = 0;$i < $count;$i++)
$arr[$i] = $result[$i]->username;
echo (json_encode($arr));
}
And try to show it by jQuery and JavaScript
$("#AdminSearch").bind("change keyup", function() {
var url = "http://localhost/PmMusic/index.php/admin/ajax/admin_search/"+$("#AdminSearch").val();
$.getJSON(url,function(data){
if (data.length == 0) // or arr == null
{
$("#AutoSearch").hide(1000);
}
else
{
$("#AutoSearch").show(1000);
}
});
});
Now my problem is,I can't detect when __ajax_admin_search doesn't find any result and first if (in JavaScript) doesn't be TRUE(always it's FALSE).
how Can I detect in JavaScript when my php code doesn't find any result in database.
Make sure to initialise $arr = Array(); before your for loop.
Then, the PHP script will return [] as the JSON object, which you can detect in JavaScript without problems.
be aware that you have to set the correct mime type. your javascript is expecting json so you need to set the headers in php. The MIME media type for JSON text is application/json...
header("Content-type: application/json");

Categories