How to process the JSON data using .getJSON - getjson

My business functionality is to format JSON code returned from database and then use AJAX to process the JSON content and need to use only ".getJSON" instead of ".ajax"
The point where i was struck up is: how to sent the parameters using .getJSON to another page (customer.php) as i need to search for the customer data from database and return result in JSON formate.[The "data" parameter which holds key&value pair that needs to be sent to the server.]
Code from ajaxcall.php(where .getJSON is used)
<head>
<script>
$(document).ready(function(){
function search(){
var x=$("#srh").val();
if(x!=""){
$.getJSON({
url:'/customer.php',
data:{value:"x"},
success:function (data)
{
content= data;
$("#result").html(content[0].cust_id);
}
});
}
}
$("#button").click(function(){
search();
});
});
</script>
</head>
<body>
<input type="text" id="srh" placeholder="Enter the Name of the Customer"/>
<input type="button" id="button" value="search" />
<div id="result"></div>
</body>
Here, i need to pass the X parameter to customer.php using getJSON.The way i am passing is not working!
Code from customer.php(where i need to get search term (X parameter as input) $var=$_POST["value"]
and fetch the data from database using X parameter in where condition and return data in JSON content)
<?php
$conn = new mysqli("localhost", "xyz", "12345", "cust");
$var=$_GET['value'];
if (mysqli_connect_errno())
{ echo 'connect not possible to database: ' . mysqli_connect_error($conn); }
else
{
$query="SELECT cust_fname,cust_lname,cust_id,cust_addresa,cust_phone
from customer where UPPER(cust_lname) like UPPER('%" . $x. "%') ";
$result = mysqli_query($conn, $query);
if (!$result) { die("Not Found ! " . mysqli_error($conn)); }
else
{
$rows = mysqli_fetch_all($result, MYSQLI_ASSOC);
$json = json_encode($rows);
}
mysqli_free_result($result);
mysqli_close($conn);
print $json;
}
} ?>
Appreciate your pointer on this! Thanks in Advance.

Related

Zend : Error Occurs when create html file from zend phtml file for multiple employee

//controller function
function sendBulkMailAction(){
$template = "estimated-festival-bill-single.phtml";
foreach ($employeeArr as $profile_id => $employeeValue) {
$someData = array(); //here include some salary data
$model = new ViewModel($someData);
$model->setTemplate($template);
$htmlContent = "<!DOCTYPE html>\n\r<html xmlns=\"http://www.w3.org/1999/xhtml\">\n\r<head>
<meta charset=\"utf-8\">
</head>
<body>"
. $this->getServiceLocator()->get('viewrenderer')->render($model)
. "</body>
</html>";
//create html file
//create pdf link from html by wkhtmlToPdf
//send this link via email to employee
}
}
//estimated-festival-bill-single.phtml
//simple code
<div> Employee Name</div>
<br>
<div><?php echo _get_salary_html(); ?></div>
<?php
function _get_salary_html(){
return "Salary Data";
}
?>
error show
Fatal error: Cannot redeclare _get_salary_html() (previously declared in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml:9) in G:\xampp\htdocs\ums\module\Hrm\view\hrm\salary-reports\estimated-salary-bill-single.phtml on line 10
hints: when single employee its ok but for multiple employee show error
Because you are re-declaring function unknowingly. Add a condition around the function like below.
if (!function_exists('_get_salary_html')) {
function _get_salary_html() {
........
}
}

Full_picture Parameter for page

I am using graph API to get access tokken using a reference "pagename?fields=picture" for my facebook page to be used on my website.
This is the function that I am using;
function get_facebook_post_pic_full_url($feed_id)
{
echo "<script>console.log( 'Debug Objects: " . $feed_id . "' );</script>";
$ursls = 'https://graph.facebook.com/'.$feed_id.'/?fields=full_picture,picture&access_token="Access Tokken"';
$fb_act = json_decode(file_get_contents($ursls));
return $fb_act;
}
function get_facebook_page_feed($fts_limiter='')
{
if(!$fts_limiter)
{
$fts_limiter = 1;
}
$pageid = get_field('facebook_page_id','option');
//If there's no Access Token then use a default
$access_token_array = array(
'sampleaccess tokken'
'sampleaccess tokken'
'sampleaccess tokken'
);
$access_token = $access_token_array[rand(0, 11)];
$graph_data = 'https://graph.facebook.com/'.$pageid.'/posts?fields=id,from,message,story,story_tags,link,source,name,caption,description,type,status_type,object_id,attachments,created_time&access_token='.$access_token.'&limit=1&locale=en_US';
$fb_activity = json_decode(file_get_contents($graph_data));
return $fb_activity;
}
And this is used to fetch and display image and caption and date;
<div class="col-xs-12 col-sm-6 col-md-4 no-padding">
<div class="facebook_img">
<?php
$fb_feeds = get_facebook_page_feed();
if(!empty($fb_feeds)):
$feeds = $fb_feeds->data[0];
$created_time = $feeds->created_time;
$link = $feeds->link;
$feed_id = $feeds->id;
$full_arr = get_facebook_post_pic_full_url($feed_id);
$full_picture = $full_arr->full_picture;
$message = $feeds->message;
$submessage = substr($message,0,75);
?>
<!--<?php var_dump($full_arr);?> -->
<img style="width:405px;height:341px" src="<?php echo $full_picture; ?>" alt="facebook"/>
<div class="fb_content"> <a target="_blank" href="<?php echo $link; ?>"><?php echo $submessage; ?></a>
<dt><?php echo date('d/m/Y', strtotime($created_time)); ?></dt>
</div>
<?php endif; ?>
</div>
The issue is that I am getting this error when I run; $ursls = 'https://graph.facebook.com/'.$feed_id.'/?fields=full_picture,picture&access_token="Access Tokken"';
{
"error": {
"message": "(#100) Tried accessing nonexisting field (full_picture) on node type (Page)",
"type": "OAuthException",
"code": 100,
"fbtrace_id": "traceid"
}
}
The code and everything was working fine and it has stopped 2 months ago. Can anyone please tell me why full_picture is nonexisting field? Does that mean that we can not use full_picture parameter for page anymore? Any help is appreciated! :)
The code and everything is working fine and facebook has not changed any parameters that are used in the above post. My access tokken was having some issues, I generated a new one and it started to work now. Thank you!

How to filter New WP Query by Custom Field Value?

I am creating new pages for each of my categories in wordpress. The post editor has a custom field that allows the selection of a sector type, this gets applied to the post on update. The custom field key is: sector, for custom field meta value options lets use SectorA, SectorB and SectorC. I am using a custom post type called projects.
I followed the advice at this link http://weblogtoolscollection.com/archives/2008/04/13/how-to-only-retrieve-posts-with-custom-fields/
How can I change the query line in the code below so that it filters the loop by a Sector name, lets use SectorA. I'll then reuse the code on each template page changing the value to SectorB and SectorC on the other pages.
I think this needs changing somehow:
$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );
Currently it echos the sector value and description value successfully but is showing all the posts. So my attempt to limit it to sectorA using sector=sectorA doesn't seem to work?
This code is in functions.php:
function get_custom_field_posts_join($join) {
global $wpdb, $customFields;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key in ($customFields)) ";
}
function get_custom_field_posts_group($group) {
global $wpdb;
$group .= " $wpdb->posts.ID ";
return $group;
}
And this code is on the Template Page:
<?php /* Begin Custom Field Posts */ ?>
<h2>Custom Posts</h2>
<ul>
<?php
global $customFields;
$customFields = "'sector', 'description'";
$customPosts = new WP_Query();
add_filter('posts_join', 'get_custom_field_posts_join');
add_filter('posts_groupby', 'get_custom_field_posts_group');
$customPosts->query('showposts=5&sector=sectorA&post_type=projects' );//Uses same parameters as query_posts
remove_filter('posts_join', 'get_custom_field_posts_join');
remove_filter('posts_groupby', 'get_custom_field_posts_group');
while ($customPosts->have_posts()) : $customPosts->the_post();
$sector = get_post_custom_values("sector");
$description= get_post_custom_values("description");?>
<li><?php echo $sector[0]; ?></li>
<li><?php echo $description[0]; ?></li><br />
<?php endwhile; ?>
</ul>
<?php /* End Custom Field Posts */ ?>
Thanks for your help
May be this what you want
function get_custom_field_posts_join($join) {
global $wpdb, $customSector;
return $join . " JOIN $wpdb->postmeta postmeta ON (postmeta.post_id = $wpdb->posts.ID and postmeta.meta_key = 'sector' and postmeta.value = '$customSector') ";
}
and modification of page
$customSector='sectorA';//<--- insert this
add_filter('posts_join', 'get_custom_field_posts_join');
Try using this code.
<?php
$sector = get_post_meta($post->ID, "sector", false);
if ($sector[0]=="") { ?>
<!-- If there are no custom fields, show nothing -->
<?php } else { ?>
<div class="sector">
<h3>Title</h3>
<?php foreach($sector as $sector) {
echo '<blockquote><p>'.$sector.'</p></blockquote>';
} ?>
</div>
<?php } ?>

POST data not being set? Codeigniter solution

I think I have a simple bug somewhere but I can't see it!
In my view, I have the following javascript to create a form:
$.ajax({
url:"<?php echo site_url('mycontroller/methodX/'.$ip.'/'.$hardwaremodel);?>",
type:'POST',
dataType:'json',
success: function(returnDataFromController) {
var htmlstring;
var submitFormHTML;
htmlstring = "<br><br><B>To reassign the port to a new vlan, click on a VlanId below and then click on the OK button</B><br><table class='table table-bordered table-striped'>";
htmlstring = htmlstring + "<th>VlanId</th><th>Name</th>";
for(i = 0; i < returnDataFromController.length; i++) {
}
submitFormHTML = "<form method='post' accept-charset='utf-8' action='/myapp/index.php/controllerABC/methodABC/"+ $('#ip').val() +"/" + $('#hardwaremodel').val() +"/" + $('#port').val() + "'><input type='text' id='newVlanID' style='width:5em;height:1.5em'/> <button type='submit' class='btn' id='saveVlan' style='width:10em;height:2em'>Reassign Vlan</button></form>";
//alert(submitFormHTML);
$('#clientajaxcontainer').html(htmlstring);
$('#newvlanform').html(submitFormHTML);
It's the "submitFormHTML" string that builds the form.
And in my controller I have the following logic to check for the input:
public function methodABC()
{
if($_POST){
echo 'I am here';
$form = $this->input->post();
var_dump($form);
exit();
}
else {
echo "false";
}
It always print the "false". I've also tried using:
print_r($this->input->post());
and
echo $this->input->post('newID');
But I can't seem to get the data from my view into the controller.
Can you see where I'm going wrong? Thanks for the help.
Edit:
The page when rendered, creates the following HTML for the form:
<form method="post" action="/myapp/index.php/switches/changeportvlan/11.11.11.11 /">
<input type='text' id='newVlanID' style='width:5em;height:1.5em'/>
<button type="submit" class='btn' id='saveVlan' style='width:10em;height:2em'>Reassign Vlan</button>
</form>"
The problem was that the textbox is missing a "name" attribute. "id" is not enough!
You need
if ($this->input->post(Null, False)) {
echo "I am here";
$form = $this->input->post(Null, True); ## True for XSS-cleaning, which you probably want.
exit();
}
else {
echo "False";
}
You have to give $this->input->post() arguments. Moreover, never use $_POST in CodeIgniter.
Good luck

dojo file upload using zend framework problem

I am struggling with a bit of dojo that is needed to upload a file. Now the file upload form sits within a dojo dialog box, so is hidden until the user selects an 'upload file' button.
This button can be clicked on anywhere on the site, so I've created a controller to handle the upload.
At the moment I am just trying to get it to work, and in my head script I have the following:
<?php $this->headScript()->captureStart(); ?>
function sendForm(){
//Hide the file input field
dojo.style('inputField',"display","none");
//Show the progress bar
dojo.style('progressField',"display","inline");
dojo.byId('preamble').innerHTML = "Uploading ...";
dojo.io.iframe.send({
url: "<?php echo $this->baseUrl(); ?>/fileprocssing/loadfile/",
method: "post",
handleAs: "text",
form: dojo.byId('StartFrm'),
handle: function(data,ioArgs){
var fileData = dojo.fromJson(data);
if (fileData.status == "success"){
//Show the file input field
dojo.style(dojo.byId('inputField'),"display","inline");
dojo.byId('fileInput').value = '';
//Hide the progress bar
dojo.style(dojo.byId('progressField'),"display","none");
dojo.byId('uploadedFiles').innerHTML += "success: File: " + fileData.details.name
+ " size: " + fileData.details.size +"<br>";
dojo.byId('preamble').innerHTML = "File to Upload: ";
}else{
dojo.style(dojo.byId('inputField'),"display","inline");
dojo.style(dojo.byId('progressField'),"display","none");
dojo.byId('preamble').innerHTML = "Error, try again: ";
}
}
});
}
<?php $this->headScript()->captureEnd() ?>
With the the basic upload for like this
<form id="StartFrm" enctype="multipart/form-data"
name="cvupload"
action="<?php echo $this->baseUrl();?>/fileprocssing/loadfile/"
method="post">
<input type="hidden" name="MAX_FILE_SIZE" value="500000">
<!-- wrapping these in spans to be able to modify
parts of this form depending on what the
dojo.io.iframe.submit() does -->
<span id="preamble">File to Upload:</span><br>
<span id="inputField">
<input type="file" id="fileInput" name="uploadFile">
</span>
<span id="progressField" style="display:none;">
<div dojoType="dijit.ProgressBar" style="width:200px" indeterminate="true"></div>
</span>
<br/>
<button value="upload" dojoType="dijit.form.Button"
onclick="sendForm()">Upload</button>
</form>
What I would like to know is how I can get the JSON data object from /fileprocssing/loadfile/ that contains upload data information if the form is called from /somecontroller/someaction/ ?? and when the file has been processed automatically redirect to something like /fileprocesing/reviewdata/
At the moment the action that I have looks like this
public function loadfileAction() {
$log = Zend_Registry::getInstance()->get('log');
$log->log('in loadfileaction', Zend_Log::DEBUG);
$log->log($_FILES['uploadFile']['name'], Zend_Log::DEBUG);
$uploadedFile = array(
'details' => $_FILES['uploadFile'],
'status' => 'success'
);
$log->log($fileUploadData->toJson(), Zend_Log::DEBUG);
$foo = "{'status':'success',details: {name:'".
$_FILES['uploadFile']['name'].
"',size:".
$_FILES['uploadFile']['size'].
"}}";
$log->log($foo, Zend_Log::DEBUG);
$this->view->fileData = $foo;
}
I've handcrafted the JSON data for the time being but will use Zend_Dojo_Data but at the moment I am just trying to get this working.
I have to confess that I don't know dojo that well, but trying to get my head around it in the shortest possible time.
Thanks in advance.
dojo.io.iframe.send requires the response data to be wrapped in a TEXTAREA tag. This is the only/easiest cross browser way to successfully access and load the response data, and is a requirement. It looks like you are sending plain JSON back from the action.
You can also adjust your handleAs to be "json" and skip the intermediate dojo.fromJson(data) call, it will be passed to you as a JSON object (provided the response is wrapped in the aforementioned TEXTAREA)