Undefined Index Issue and Error return - javascript

Marked as fixed!!!
I was missing vat_rate in my MySQL business database. This was causing both issues. Thanks Nytrix and Grimbode both for the swift and walk through support, much appreciated! :)
I'm getting an undefined index issue on line 16...
<?php
class Business extends Application {
private $_table = 'business';
public function getBusiness() {
$sql = "SELECT * FROM `{$this->_table}`
WHERE `id` = 1";
return $this->db->fetchOne($sql);
}
public function getVatRate() {
$business = $this->getBusiness();
return $business['vat_rate'];
}
}
How can I fix it? Thanks.
Also, I'm getting an error pop-up when I click my add to basket and remove from basket links, which is called from basket.js on line 13 and 14. I don't know how to fix that either, but think it may have something to do with the above?
Regards
Edit; Thinking I've done a var_dump correctly(?), this is what is shown for $business when I wrote
<?php var_dump($business); ?>
in my _header.php file to echo the array (I say that though with no knowledge!).
Notice: Undefined variable: business in /Users/ashleysmith/Documents/Website Tests/Z - Work from this/ecommerce/template/_header.php on line 68
NULL
Here's all the relevant code as far as I know...
Business.php
<?php
class Business extends Application {
private $_table = 'business';
public function getBusiness() {
$sql = "SELECT * FROM `{$this->_table}`
WHERE `id` = 1";
return $this->db->fetchOne($sql);
}
public function getVatRate() {
$business = $this->getBusiness();
return $business['vat_rate'];
}
}
basket_small_refresh.php
<?php
require_once("../inc/autoload.php");
$objBasket = new Basket();
$out = array();
$out['bl_ti'] = $objBasket->_number_of_items;
$out['bl_st'] = number_format($objBasket->_sub_total, 2);
$out['bl_vat'] = number_format($objBasket->_vat, 2);
$out['bl_total'] = number_format($objBasket->_total, 2);
echo json_encode($out);
basket_left.php
<div id="small_basket">
<?php $objBasket = new Basket(); ?>
<p class="your_bas">Your Basket</p>
<dl id="basket_left">
<dt>No. of items:</dt>
<dd class="bl_ti"><span><?php echo $objBasket->_number_of_items; ?></span></dd>
<dt>Sub-total:</dt>
<dd class="bl_st">£<span><?php echo number_format($objBasket->_sub_total, 2); ?></span></dd>
<dt>VAT (<span><?php echo $objBasket->_vat_rate; ?></span>%):</dt>
<dd class="bl_vat">£<span><?php echo number_format($objBasket->_vat, 2); ?></span></dd>
<dt>Total (inc):</dt>
<dd class="bl_total">£<span><?php echo number_format($objBasket->_total, 2); ?></span></dd>
</dl>
<p class="check_button">
View Basket |
Checkout
</p>
</div>
basket.php
<?php
require_once('../inc/autoload.php');
if (isset($_POST['job']) && isset($_POST['id'])) {
$out = array();
$job = $_POST['job'];
$id = $_POST['id'];
$objCatalogue = new Catalogue();
$product = $objCatalogue->getProduct($id);
if (!empty($product)) {
switch($job) {
case 0:
Session::removeItem($id);
$out['job'] = 1;
break;
case 1:
Session::setItem($id);
$out['job'] = 0;
break;
}
echo json_encode($out);
}
}
Basket.php
<?php
class Basket {
public $_inst_catalogue;
public $_empty_basket;
public $_vat_rate;
public $_number_of_items;
public $_sub_total;
public $_vat;
public $_total;
public function __construct() {
$this->_inst_catalogue = new Catalogue();
$this->_empty_basket = empty($_SESSION['basket']) ? true : false;
$objBusiness = new Business();
$this->_vat_rate = $objBusiness->getVatRate();
$this->noItems();
$this->subtotal();
$this->vat();
$this->total();
}
public function noItems() {
$value = 0;
if (!$this->_empty_basket) {
foreach($_SESSION['basket'] as $key => $basket) {
$value += $basket['qty'];
}
}
$this->_number_of_items = $value;
}
public function subtotal() {
$value = 0;
if (!$this->_empty_basket) {
foreach($_SESSION['basket'] as $key => $basket) {
$product = $this->_inst_catalogue->getProduct($key);
$value += ($basket['qty'] * $product['price']);
}
}
$this->_sub_total = round($value, 2);
}
public function vat() {
$value = 0;
if (!$this->_empty_basket) {
$value = ($this->_vat_rate * ($this->_sub_total / 100));
}
$this->_vat = round($value, 2);
}
public function total() {
$this->_total = round(($this->_sub_total + $this->_vat), 2);
}
public static function activeButton($sess_id) {
if(isset($_SESSION['basket'][$sess_id])) {
$id = 0;
$label = "Remove From Basket";
} else {
$id = 1;
$label = "Add To Basket";
}
$out = "<a href=\"#\" class=\"add_to_basket";
$out .= $id == 0 ? " red" : null;
$out .= "\" rel=\"";
$out .= $sess_id."_".$id;
$out .= "\">{$label}</a>";
return $out;
}
}
basket.js
$(document).ready(function() {
function refreshSmallBasket() {
$.ajax({
url: '/mod/basket_small_refresh.php',
dataType: 'json',
success: function(data) {
$.each(data, function(k, v) {
$("#basket_left ." + k + " span").text(v);
});
},
error: function(data) {
alert("Error occured");
}
});
}
if ($(".add_to_basket").length > 0) {
$(".add_to_basket").click(function() {
var trigger = $(this);
var param = trigger.attr("rel");
var item = param.split("_");
$.ajax({
type: 'POST',
url: '/mod/basket.php',
dataType: 'json',
data: ({ id : item[0], job : item[1] }),
success: function(data) {
var new_id = item[0] + '_' + data.job;
if (data.job != item[1]) {
if (data.job == 0) {
trigger.attr("rel", new_id);
trigger.text("Remove From Basket");
trigger.addClass("red");
} else {
trigger.attr("rel", new_id);
trigger.text("Add To Basket");
trigger.removeClass("red");
}
refreshSmallBasket();
}
},
error: function(data) {
alert("Error occured");
}
});
return false;
});
}
});

Ok, so you are selecting everything * from you're table defined as $_table = "business". You want to select the 'vat_rate' column that may not exists in the returnd array. Here for you checked with var_dump how you're array looks. If you want to know how to select a value from that array please look on the documentation: http://php.net/manual/en/language.types.array.php OR http://www.w3schools.com/php/php_arrays.asp (mabey a bit simpler explained)

Marked as fixed!!!
I was missing vat_rate in my MySQL business database. This was causing both issues. Thanks Nytrix and Grimbode both for the swift and walk through support, much appreciated! :)

Related

How do I submit form without page reload taking into consideration the php script?

So basically I have to work on this loan calculator loancalc.000webhostapp.com
I have looked at other pages on this site "how to submit form without page reload?" but this isn't completely relevant to what i'm working on. So far i've added this into the jquery part of the page...
jQuery('qis-register').on('submit', 'input', function(){
event.preventDefault();
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
return false;
}
else{
}
if (email == ""){
$("input#youremail").focus;
return false;
}
});
But i'm told there is also two other scripts that I need to work with, I'm not really too experienced with php so not sure what's going on, the two php scripts I have to work with are called quick-interest-slider.php and register.php,
//qis_verify_application in register.php
function qis_verify_application(&$values, &$errors) {
$application = qis_get_stored_application();
$register = qis_get_stored_application_messages();
$arr = array_map('array_shift', $application);
foreach ($arr as $key => $value) {
if ($application[$key]['type'] == 'multi') {
$d = explode(",",$application[$key]['options']);
foreach ($d as $item) {
$values[$key] .= $values[$key.$item];
}
}
if ($application[$key]['required'] == 'checked' && $register['use'.$application[$key]['section']] && (empty($values[$key]) || $values[$key] == 'Select...'))
$errors[$key] = 'error';
}
$filenames = array('identityproof','addressproof');
foreach($filenames as $item) {
$tmp_name = $_FILES[$item]['tmp_name'];
$name = $_FILES[$item]['name'];
$size = $_FILES[$item]['size'];
if (file_exists($tmp_name)) {
if ($size > $register['attach_size']) $errors['attach'.$item] = $register['attach_error_size'];
$ext = strtolower(substr(strrchr($name,'.'),1));
if (strpos($register['attach_type'],$ext) === false) $errors['attach'.$item] = $register['attach_error_type'];
}
}
return (count($errors) == 0);
}
//qis_process_application in register.php
function qis_process_application($values) {
global $post;
$content='';
$register = qis_get_stored_register ('default');
$applicationmessages = qis_get_stored_application_messages();
$settings = qis_get_stored_settings();
$auto = qis_get_stored_autoresponder();
$application = qis_get_stored_application();
$message = get_option('qis_messages');
$arr = array_map('array_shift', $application);
if ($message) {
$count = count($message);
for($i = 0; $i <= $count; $i++) {
if ($message[$i]['reference'] == $values['reference']) {
$values['complete'] = 'Completed';
$message[$i] = $values;
update_option('qis_messages',$message);
}
}
}
$filenames = array('identityproof','addressproof');
$attachments = array();
if ( ! function_exists( 'wp_handle_upload' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
add_filter( 'upload_dir', 'qis_upload_dir' );
$dir = (realpath(WP_CONTENT_DIR . '/uploads/qis/') ? '/uploads/qis/' : '/uploads/');
foreach($filenames as $item) {
$filename = $_FILES[$item]['tmp_name'];
if (file_exists($filename)) {
$name = $values['reference'].'-'.$_FILES[$item]['name'];
$name = trim(preg_replace('/[^A-Za-z0-9. ]/', '', $name));
$name = str_replace(' ','-',$name);
$_FILES[$item]['name'] = $name;
$uploadedfile = $_FILES[$item];
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
array_push($attachments , WP_CONTENT_DIR .$dir.$name);
}
}
remove_filter( 'upload_dir', 'qis_upload_dir' );
$content = qis_build_complete_message($values,$application,$arr,$register);
qis_send_full_notification ($register,$values,$content,true,$attachments);
qis_send_full_confirmation ($auto,$values,$content,$register);
}
function qis_loop in quick-interest-slider.php
function qis_loop($atts) {
$qppkey = get_option('qpp_key');
if (!$qppkey['authorised']) {
$atts['formheader'] = $atts['loanlabel'] = $atts['termlabel'] = $atts['application'] = $atts['applynow'] = $atts['interestslider'] = $atts['intereselector']= $atts['usecurrencies'] = $atts['usefx'] = $atts['usedownpayment'] = false;
if ($atts['interesttype'] == 'amortization' || $atts['interesttype'] == 'amortisation') $atts['interesttype'] = 'compound';
}
global $post;
// Apply Now Button
if (!empty($_POST['qisapply'])) {
$settings = qis_get_stored_settings();
$formvalues = $_POST;
$url = $settings['applynowaction'];
if ($settings['applynowquery']) $url = $url.'?amount='.$_POST['loan-amount'].'&period='.$_POST['loan-period'];
echo "<p>".__('Redirecting....','quick-interest-slider')."</p><meta http-equiv='refresh' content='0;url=$url' />";
die();
// Application Form
} elseif (!empty($_POST['qissubmit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_form($formvalues, $formerrors)) {
return qis_display($atts,$formvalues, $formerrors,null);
} else {
qis_process_form($formvalues);
$apply = qis_get_stored_application_messages();
if ($apply['enable'] || $atts['parttwo']) return qis_display_application($formvalues,array(),'checked');
else return qis_display($atts,$formvalues, array(),'checked');
}
// Part 2 Application
} elseif (!empty($_POST['part2submit'])) {
$formvalues = $_POST;
$formerrors = array();
if (!qis_verify_application($formvalues, $formerrors)) {
return qis_display_application($formvalues, $formerrors,null);
} else {
qis_process_application($formvalues);
return qis_display_result($formvalues);
}
// Default Display
} else {
$formname = $atts['formname'] == 'alternate' ? 'alternate' : '';
$settings = qis_get_stored_settings();
$values = qis_get_stored_register($formname);
$values['formname'] = $formname;
$arr = explode(",",$settings['interestdropdownvalues']);
$values['interestdropdown'] = $arr[0];
$digit1 = mt_rand(1,10);
$digit2 = mt_rand(1,10);
if( $digit2 >= $digit1 ) {
$values['thesum'] = "$digit1 + $digit2";
$values['answer'] = $digit1 + $digit2;
} else {
$values['thesum'] = "$digit1 - $digit2";
$values['answer'] = $digit1 - $digit2;
}
return qis_display($atts,$values ,array(),null);
}
}
Do I have to edit any of the php and I also don't know what I have to write considering the php.
You can use what is called Ajax to submit the data to the server via POST.
Create a button and give it a class of qis-register, then give each of your input fields a class that matches it's name. Then just add that field to the data object that I have following the format within it.
jQuery(document).on('click', '.qis-register', function(){
var name = $("input#yourname").val();
var email = $("input#youremail").val();
if (name == ""){
$("input#yourname").focus;
}
else if (email == ""){
$("input#youremail").focus;
}
else{
jQuery.ajax({
type: "POST",
url: "your_php_here.php",
data: {
name:name,
email:email,
qissubmit:$(".qissubmit").val(),
qisapply:$(".qisapply").val(),
part2submit:$(".part2submit").val(),
},
done: function(msg){
console.log(msg);
}
});
}
});

XMLHttpRequest - append php function to .json?add_fields ajax request

I am trying to update someone else's code, which uses a XMLHttpRequest setup to get product information from the server for use on some SilverStripe templates. I want to grab the url() function from Product.php so I can use it to get the url for the Product data object and send it to Google Analytics. However, simply appending it to the existing add_fields data does not work--the url function does not get retrieved.
I'm not very familiar with XMLHttpRequests so I'm kind of clueless as to what to do here.
Here is the JavaScript code that is getting the product data:
document.addEventListener("DOMContentLoaded", function(event) {
var productCatalogService = (function() {
var endpoint = "/api/v1/Product/";
return {
'getProductById': function(id, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', endpoint + id + ".json?add_fields=NutritionalInformationLabelURL,SortOrder,BeautyShotURL,url,Recipe"); //url function is not grabbed
xhr.onload = function() {
if (xhr.status === 200) {
callback && callback(JSON.parse(xhr.responseText));
}
else {
console.error('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send();
}
};
})();
var utils = (function() {
return {
'removeClass': function(node, className) {
node.className = node.className.replace(className, '');
return node;
},
'addClass': function(node, className) {
node.className = node.className.replace(className, '');
node.className += " " + className;
},
'hasClass': function(node, className) {
return node.className.indexOf(className) >= 0;
}
}
})();
var changeProduct = function(product) {
var name = document.querySelector('.product-name'),
subname = document.querySelector('.product-subname'),
tagline = document.querySelector('.product-tagline'),
description = document.querySelector('.product-description'),
beautyShot = document.querySelector('.beauty-shot'),
nutritionFacts = document.querySelector('.ingredients-list'),
mobileNutritionLabel = document.querySelector('.mobile-nutrition-label img'),
nutritionLabel = document.querySelector('.nutritional-label img'),
recipeName = document.querySelector('.recipe-name'),
recipeDescription = document.querySelector('.recipe-description'),
recipeContainer = document.querySelector('.recipe-container');
name.innerHTML = product.Name;
subname.innerHTML = product.SubName;
description.innerHTML = product.Description;
tagline.innerHTML = product.Tagline;
beautyShot.src = product.BeautyShotURL;
if(product.NutritionalInformationLabelURL){
nutritionLabel.src = product.NutritionalInformationLabelURL;
mobileNutritionLabel.src = product.NutritionalInformationLabelURL;
}
if(product.NutritionFacts){
nutritionFacts.innerHTML = product.NutritionFacts;
if(utils.hasClass(nutritionFacts, 'hidden')) {
utils.removeClass(nutritionFacts, 'hidden');
}
} else {
utils.addClass(nutritionFacts, 'hidden');
}
// var pagePath = product.url();
console.log(product.url); //returns undefined
typeof(ga) !== "undefined" && ga('send', 'pageview', {
'page': location.pathname, //want to use the url() function in Product.php here
'title': product.PageTitle
});
};
NodeList.prototype.forEach = Array.prototype.forEach;
var products = document.querySelectorAll('.carousel-products .product');
products.forEach(function(product) {
product.onclick = function() {
var productId = product.getAttribute('data-product-id');
productCatalogService.getProductById(productId, function(product) {
console.log(product);
changeProduct(product); //add recipe data to be pulled in here (fields are above)
});
};
});
});
Product.php
<?php
class Product extends DataObject implements Pageable, Searchable {
private static $api_access = true;
private static $db = [
'Name' => 'varchar(255)',
'SubName' => 'varchar(255)',
'Tagline' => 'varchar(255)',
'Description' => 'HTMLText',
'WhereToBuy' => 'varchar(500)', // external link
'NutritionFacts' => 'HTMLText',
'PageTitle' => 'varchar(250)',
'MetaKeywords' => 'Text',
'MetaDescription' => 'Text',
'SortOrder' =>'Int'
];
private static $has_one = [
'BeautyShot' => 'Image',
'ThumbImage' => 'Image',
'NutritionalInformationLabel' => 'Image',
'Category' => 'Category',
];
private static $summary_fields = [
'GridThumbnail' => 'Photo',
'Name' => 'Name'
];
public function getCMSFields() {
$fields = parent::getCMSFields();
$fields->addFieldToTab('Root.Main', new TextField("Name", "Name"));
$fields->addFieldToTab('Root.Main', new TextField("SubName", "SubName"));
$fields->addFieldToTab('Root.Main', new TextField("Tagline", "Tagline"));
$fields->addFieldToTab("Root.Main", new HtmlEditorField("Description", "Description"));
$fields->addFieldToTab('Root.Main', new TextField("WhereToBuy", "WhereToBuy"));
$fields->addFieldToTab("Root.Main", new HtmlEditorField("NutritionFacts", "NutritionFacts"));
$fields->addFieldToTab("Root.Main", new UploadField("BeautyShot", "BeautyShot"));
$fields->addFieldToTab("Root.Main", new UploadField("ThumbImage", "ThumbImage"));
$fields->addFieldToTab("Root.Main", new UploadField("NutritionalInformationLabel", "NutritionalInformationLabel"));
$fields->addFieldToTab('Root.SEO', new TextField("PageTitle", "PageTitle"));
$fields->addFieldToTab('Root.SEO', new TextareaField("MetaKeywords", "MetaKeywords"));
$fields->addFieldToTab('Root.SEO', new TextareaField("MetaDescription", "MetaDescription"));
$fields->removeByName('SortOrder');
return $fields;
}
public function getGridThumbNail() {
if ($this->BeautyShot()->exists()) {
return $this->BeautyShot()->SetWidth(100);
}
return '(no image)';
}
public function getBeautyShotURL() {
return $this->BeautyShot()->URL;
}
public function getNutritionalInformationLabelURL() {
if ($this->NutritionalInformationLabel()->Exists()) {
return $this->NutritionalInformationLabel()->URL;
} else {
return "";
}
}
public function getCouponImageURL() {
if ($this->CouponImage()->Exists()) {
return $this->CouponImage()->URL;
} else {
return "";
}
}
public function getProductFullName(){
return $this->Name." ".$this->SubName;
}
public function AbsoluteLink() {
return Director::absoluteURL($this->url());
}
private function url() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
// lifted from Artisa
public function MetaTags() {
$tags = "";
$generator = trim(Config::inst()->get('SiteTree', 'meta_generator'));
if (!empty($generator)) {
$tags .= "<meta name=\"generator\" content=\"" . Convert::raw2att($generator) . "\" />\n";
}
$charset = Config::inst()->get('ContentNegotiator', 'encoding');
$tags .= "<meta http-equiv=\"Content-type\" content=\"text/html; charset=$charset\" />\n";
if($this->MetaDescription) {
$tags .= "<meta name=\"description\" content=\"" . Convert::raw2att($this->MetaDescription) . "\" />\n";
}
if($this->MetaKeywords) {
$tags .= "<meta name=\"keywords\" content=\"" . Convert::raw2att($this->MetaKeywords) . "\" />\n";
}
if(Permission::check('CMS_ACCESS_CMSMain')
&& in_array('CMSPreviewable', class_implements($this))
&& !$this instanceof ErrorPage
&& $this->ID > 0
) {
$tags .= "<meta name=\"x-page-id\" content=\"{$this->ID}\" />\n";
$tags .= "<meta name=\"x-cms-edit-link\" content=\"" . $this->CMSEditLink() . "\" />\n";
}
$this->extend('MetaTags', $tags);
return $tags;
}
public function canView($member = null){
return true;
}
public function canEdit($member = null) {
return true;
}
public function canCreate($member = null) {
return true;
}
public function slug()
{
return Utilities::friendlyName($this->Name);
}
public function Link()
{
return $this->url();
}
public function getTitleFields() {
return ['Name', 'SubName'];
}
public function getContentFields() {
return ['Description'];
}
public static function getSearchFilter() {
return [];
}
}
// Handles Products and categories
class ProductCsvBulkImporter extends CsvBulkLoader {
protected function processRecord($record, $columnMap, &$results, $preview = false) {
$categoryName = $record['Main Category'];
$productName = $record['Product ID'];
$productSubName = $record['Product Type'];
$productTagline = $record['Product Label'];
$productDescription = $record['Product Description'];
$productKeywords = $record['Keyphrase'];
$category = Category::get()
->filter(['Name' => $categoryName])
->first();
if (!$category) {
$category = new Category();
$category->Name = $categoryName;
$category->write();
}
$product = Product::get()
->filter(['Name' => $productName])
->first();
if (!$product) {
$product = new Product();
}
$product->PageTitle = sprintf("%s %s", $productName, $productSubName);
$product->Name = $productName;
$product->SubName = $productSubName;
$product->Tagline = $productTagline;
$product->Description = $productDescription;
$product->MetaKeywords = $productKeywords;
$product->CategoryID = $category->ID;
$product->write();
return $product->ID;
}
}
I don't know if the code, as it's setup now, is best practice or not as I didn't make it, so if there are mistakes, I can't tell for sure.
Is there some way to append the url() function from Product.php to the .json?add_fields ajax response?
As you can see in the Product class, the url() method it's private, so you don't have access to it outside that class:
private function url() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
If you change that to:
public function url() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
it'll probably work... That's all I can say based on the code you submitted. You should know, there's probably a reason why that url() method is private - most probably it's only used internally in the Product class.
If it's still not working, try to duplicate that function like this:
public function getUrl() {
return sprintf("/home/products/%s/%s", $this->Category()->slug(), $this->slug());
}
...and then in the JS code you can use it like this:
console.log(product.Url);
As you can see, you have calls like this in the JS code: product.BeautyShotURL, but the actual method in the Product class it's called getBeautyShotURL(), so it should work with product.Url (this might also work tough: product.getUrl)

How to refresh a page section using ajax/json?

i am building a chat website, now i working on ONLINE USER.
I use AJAX to refresh but i meet some problems with Append.();.
When refreshing section the same data appear again and again...That is the PHP file.
<?php
public function online(){
$database = new DB();
$db = $database->database();
$array = array();
$ref = $_SESSION['oc_users_ref'];
$time_out = time()-5;
$time = time();
$query = $db->query("SELECT * FROM oc_users WHERE users_online = 0");
$updateOnline = $db->query("UPDATE oc_users SET users_online = 1 WHERE users_lastcome < '$time_out'");
$q = $db->query("SELECT * FROM oc_users WHERE users_ref <> '$ref' AND users_online = 0 ORDER BY users_lastcome DESC");
while($data = $q->fetch()) {
if($data['users_online'] == 1){
$class = "opacity30";
}else{
$class = '';
}
$array[] = $data;
}
print json_encode($array);
} ?>
Now the Javascript
function getOnline(){
$.ajax({
url: "conf/users.php?act=online",
dataType: "text",
success: function(data) {
var json = $.parseJSON(data);
for (var i=0;i<json.length;++i)
{
$('#printOnline').append('<li><a href="javascript:void(0);" onclick=javascript:chatWith("'+json[i].users_nickname+'")><i></i>'+json[i].users_nickname+'</a></li>');
}
}
});
}
setInterval('getOnline()',10000);
And the result*
User001
User001
User001
User001
User001
User001
User001
User001
Please help me...Great Thanks
Reset the user list before updating:
function getOnline(){
$.ajax({
url: "conf/users.php?act=online",
dataType: "text",
success: function(data) {
$('#printOnline').html("");
var json = $.parseJSON(data);
for (var i=0;i<json.length;++i)
{
$('#printOnline').append('<li><a href="javascript:void(0);" onclick=javascript:chatWith("'+json[i].users_nickname+'")><i></i>'+json[i].users_nickname+'</a></li>');
}
}
});
}
setInterval('getOnline()',10000);

Same type of data once called is a JSON Object but when called 2nd time it turns out to be a string

Following is my JS Code.
function showresult(data){
jQuery.each(data, function(key, value) {
var count = 1;
if(key == 0){
jQuery.each(value, function(key, value) {
var str = value.split(',');
jQuery.each(str, function(key, value1) {
eval("document.getElementById('image"+count+"').src = '"+value1+"';");
count++;
});
});
}
if(key == 1){
var count = 1;
jQuery.each(value, function(key, value) {
jQuery.each(value, function(key, value1) {
jQuery('#image'+count).after(value1+'%');
count++;
});
});
}
});
}
When I doalert(data), I get [object Object], following is the data I am passing to the function.
[{"path":"patternimages/041929_d.jpg,patternimages/016630_d.jpg,patternimages/039462_d.jpg,patternimages/065862_d.jpg,patternimages/041984_d.jpg,patternimages/041931_d.jpg,patternimages/041939_d.jpg,patternimages/075066_d.jpg"},{"percentage":["100","100","99","98","98","97"]}]
When another call made to the same function but with different data, after alert(data) gives me following result. I was expecting [object Object] after alert but I didn't got that type of result after alert.
[{"path":"patternimages/051696_d.jpg,patternimages/026965_d.jpg,patternimages/047889_d.jpg,patternimages/050544_d.jpg,patternimages/019186_d.jpg,patternimages/005978_d.jpg,patternimages/044707_d.jpg,patternimages/045949_d.jpg,patternimages/104967_d.jpg,patternimages/006135_d.jpg,patternimages/006897_d.jpg,patternimages/017471_d.jpg"},{"percentage":["83","83","80","80","65","63","63","63","62","59","59","51"]}].
Following is my PHP Code
public function result($result) {
$results = array();
while ($row = mysql_fetch_array($result)) {
$id[] = $row['image_id'];
$percentage[] = $row['percentage'];
}
if (#count($id) > 1) {
$id = array_unique($id);
} else {
#$id = $id;
}
$fresult = $this->GetResult($id);
$count = mysql_num_rows($fresult);
if ($count > 1) {
while ($row = mysql_fetch_array($fresult)) {
$ids[] = $row['id'];
$names[] = $row['name'];
$percentages[] = $row['percentage'];
}
$percent_val = array();
$res = implode(',patternimages/', $names);
$path['path'] = 'patternimages/' . $res;
$percent_val['percentage'] = $percentages;
array_push($results, $path);
array_push($results, $percent_val);
} else {
$results = 'No Data Found';
}
return $results;
}
the result is encoded to JSON response like this echo json_encode($results, JSON_UNESCAPED_SLASHES);
EDIT JS code
$.ajax({
type: 'post',
dataType: "json",
url: url,
data: {color1: color1},
success: function(data) {
showresult(data);
}
});

SyntaxError: Unexpected token l in ajax call

I am trying to fetch a data from the server data base and pass it to the ajax to create a database table and its data in the local android database. But when an ajax call is make it give following error.
LogCat:
01-30 10:58:45.888: D/CordovaLog(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l
01-30 10:58:45.888: I/Web Console(31914): Server is not responding... Please try again: SyntaxError: Unexpected token l at file:///android_asset/www/home.html:513
here is the ajax code:
$.ajax({
url : urlServer + 'getTableData.php',
// type: 'POST',
contentType : 'application/json',
beforeSend : function() {
$.mobile.loading('show')
},
complete : function() {
console.log("ajax complete");
createTable();
},
dataType : 'json',
data : {userId: user_id},
success : function(data) {
if (data != null)
{
dynamic_tabledetails = data.Table_details;
dynamic_selectQuery = data.SelectTableQuery;
table_data = data;
getTabledetails(dynamic_tabledetails);
}
else
{
alert("Error Message");
}
},
error : function(xhr, ajaxOptions, thrownError) {
console.log("Server is not responding... Please try again: "+thrownError);
}
});
Here is the php code:
<?php
require_once ('connect.php');
$userID= $_REQUEST['userId'];
$data = array ();
$listtables = array();
$Tabledetails = array();
$select_table = '';
$tab_name = array();
$getlistTables = 'SHOW TABLES FROM sacpl_crm_dev ';
$resultsListTables = mysql_query($getlistTables);
echo 'length of the tables name: '.$resultsListTables.' ';
while ($row = mysql_fetch_array($resultsListTables))
{
if(strpos($row[0],'_trail') == false)
{
$temporarydata = array();
$TableName = new ArrayObject();
$getTabledetails = 'show columns from '.$row[0].'';
$resultdetails = mysql_query($getTabledetails);
$TableName['tablename'] = $row[0];
$tab_name[] =$row[0];
$column = array();
$delete_field = '';
$comp_codeField = '';
while($rows = mysql_fetch_array($resultdetails))
{
$column_list =new ArrayObject();
$column_list['FieldName'] = $rows['Field'];
$column_list['Default'] = $rows['Default'];
if(strpos($rows['Type'],'(') == false)
{
$column_list['dataType'] = $rows['Type'];
$column_list['dataType_limit'] ='';
}
else
{
$type = explode('(',$rows['Type']);
$column_list['dataType'] = $type[0];
$column_list['dataType_limit'] = '('.$type[1];
}
if($rows['Field'] == 'deleted')
{
$delete_field = 'deleted = 0';
}
if($rows['Field'] == 'userId')
{
$userIdField = $rows['Field'].'="'.$userId.'"';
}
$column_list['Extra'] = $rows['Extra'];
$column_list['Null_value'] = $rows['Null'];
$column_list['Key_value'] = $rows['Key'];
$column[] = $column_list;
}
$TableName['column_details'] = $column;
$Tabledetails[]=$TableName;
if($userIdField == '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$delete_field.'';
}
else if($userIdField != '' && $delete_field =='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.'';
}
else if($userIdField != '' && $delete_field !='')
{
$select_table = 'select * from '.$row[0].' where '.$userIdField.' and '.$delete_field.'';
}
else{
$select_table = 'select * from '.$row[0].'';
}
$select_query[] = $select_table;
$resultTableData = mysql_query($select_table);
while ($row1 = mysql_fetch_array($resultTableData))
{
$temporarydata[] = $row1;
}
$data[$row[0]] = $temporarydata;
}
}
$data['Table_details'] = $Tabledetails;
$data['SelectTableQuery'] = $select_query;
mysql_close($con);
require_once('JSON.php');
$json = new Services_JSON();
echo ($json->encode($data));
?>
Comment out the line:
echo 'length of the tables name: '.$resultsListTables.' ';
Also, when outputting JSON for an AJAX call, it's important to set the Content-type header using:
header('Content-type: application/json; charset=utf-8',true);
This php code doesn't seem to have syntax error. the problem probably lies on the included php's: "connect.php" and "JSON.php". could you please post them too so we can find the error.
Link this into the beginning of your PHP-file:
header("Content-Type: text/javascript; charset=utf-8");

Categories

Resources