Insert Large html markups inside jquery variable error - php

im builng a web game and im stuck tryning to append the html-markup for a jquery-ui dailog box.I am currently getting the Uncaught SyntaxError: Unexpected number error in chrome. I have tryed the appendTo method for large blocks of data before,but i was wondering is the a limit on the amount of html-elements you can place inside a jquery varable? because i find myself having to work around this every day ant tips?
note: please read the question carefully before you answer . Is there a way to store large blocks of (html code/ text) static or dynamic, inside a jquery variable?
jquery code :
<script>
var vari = "<?= $UserSpacesAvA ; ?>";
var btn = "<button id='d_pis_btn'>Place in shop</button>";
$(vari).appendTo(document).dialog({
closeOnEscape: false,
modal : true,
draggable : false,
height : 400,
width : 500,
resizable : false,
title : 'Give Your new <?=ucfirst($morph); ?> A Home!',
buttons : [
{
text: 'Done!',
click: function() {
$(this).dialog("destroy").remove();
}
},
],
open: function(event, ui) { $(".ui-dialog-titlebar-close").remove(); },
});
$('.popi select').chosen({});
$(btn).appendTo('.set').on("click",function(){
});
</script>
Php code :
function UserPlaces($userData,$dataExpected,$type){
$dat = "<div class='popi' id='pop'><fieldset class='set'><legend>Location:</legend>";
$x = explode(",",$type);
foreach($x as $s){
switch($s){
case 'rooms':
// bring out rooms
$dat .= "<label>Room:</label><select id='d_room_select'>";
if(count($userData["locations"]['r']) < 1){
$dat .= "Insufficient Space";
}else{
$int = 1;
foreach($userData["locations"]['r'] as $x){
$dat .= "<option value=\"$x\">Room Number $int</option>";
$int++;
}
}
$dat .= "</select><br><br>";
break;
case 'shops':
// bring out shops
$dat .= "<h4>Is this snake for sale ?</h4><br><label>Shop:</label><select id='d_shop_select'>";
if(count($userData["locations"]['r']) < 1){
$data .= "No Shops";
}else{
$int = 1;
foreach($userData["locations"]['s'] as $x){
$dat .= "<option value=\"$x\">Shop Number $int</option>";
$int++;
}
}
$dat .= "</select><br><br><label>Price:</label>
<input id='d_shop_price_snake' name='d_shop_price_snake'><br><br>
";
break;
case 'shows':
// bring out shows
break;
}
}
$dat .= "</fieldset></div>";
return $dat;
}

This doesn't answer your question on limits, but try using jQuery Templates:
http://api.jquery.com/category/plugins/templates/

Related

Unable to use jquery.html() with ajax response

I have a problem when trying to select the <li> inside a <ul> list from an ajax response using jQuery.html();
This is my AJAX request:
if (searchid != '') {
$.ajax({
type: "POST",
url: "/service/search.php",
data: dataString,
cache: false
}).done(function (html) {
$("#result").html(html).show();
var images = $("#result").find(".dbRows.sixth").html();
console.debug(images);
})
.fail(function (jqXHR, textStatus) {
$("#explainMessage").html('Unable to check at the moment. Please retry later').show();
})
}
return false;
and in php I have this code:
if ( mysqli_num_rows($result)==0)
{
$display = '<div id="explainMessage" class="explainMessage">Sorry, this was not found.</div>';
echo $display;
} else {
$counter = 0;
while ($row = $result->fetch_assoc()) {
++$counter;
$image_filename = $row['image_filename'];
$imageFolder = $_SERVER['DOCUMENT_ROOT'] . '/service/img/';
$imageList = scandir($imageFolder, 1);
$imageLink = '/service/img/' . $image_filename;
$withoutExt = preg_replace('/\\.[^.\\s]{3,4}$/', '', $image_filename);
$pattern = '/^(' . quotemeta($withoutExt) . ').*$/';
$display = '<div class="dbRows sixth" style="display:none"><ul>';
foreach ($imageList as $image) {
if (preg_match($pattern, $image)) {
if (in_array($image, $imageList)) {
$display .= '<li><img src="' . $imageLink . '" /></li>';
}
}
};
$display .= '</ul></div>';
echo $display;
the problem is that when I try to use the AJAX.done(); function, in my console I have just <ul></ul> without the list of images.My question is, why i can't select the code inside the <ul> tags even if the list of images is actually in the code? I'm pretty new with PHP, any help will be really appreciated. Thanks in advance.
You are doing it wrong. As I doubt before asking you for response HTML, you have blank `'.
$("#result").find(".dbRows.sixth").html() will print html for first matched element only.
Try this, if you want to fetch html for all matched element:
$("#result").find(".dbRows.sixth").each(function(){
console.log($(this).html());
});
From a quick look I can see a few problems. In your php change your first line of code from <div class="dbRows sixth" style="display:none"><ul>'; to $display = '<div class="dbRows sixth" style="display:none"><ul>';
I'd probably change this: var images = $("#result").find(".dbRows.sixth").html(); to this: var images = $("#result > .dbRows.sixth");.
Then add images.show(); and console.log(images.html());. Not tested but might get you on the right track.

Having trouble passing data to Highcharts

I am trying to pull financial stock data of multiple companies from CSVs and display the data as separate series in a Highcharts/Highstocks line chart. I have the sources setup and I am able to pull data + convert to JSON, but I am having trouble passing the data off to Highcharts. I believe I am not using the most efficient method of preparing the data for Highcharts use, and I am hoping someone can give me direction on what I've done incorrectly. Please take a look at my code and make me aware of any inefficiencies or glaring errors you see.
PHP code:
date_default_timezone_set('America/Los_Angeles');
$stocks = array('MSFT' => 'http://ichart.finance.yahoo.com/table.csv?s=MSFT', 'AAPL' => 'http://ichart.finance.yahoo.com/table.csv?s=AAPL', 'FB' => 'http://ichart.finance.yahoo.com/table.csv?s=FB');
$stocks_data = array();
foreach ($stocks as $key=>$stock) {
$fh = fopen($stock, 'r');
$header = fgetcsv($fh);
$varname = $key . '_data';
$$varname = array();
while ($line = fgetcsv($fh)) {
${$varname}[count($$varname)] = array_combine($header, $line);
}
fclose($fh);
}
foreach($MSFT_data as $val){
$MSFT[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$MSFT = json_encode($MSFT);
foreach($AAPL_data as $val){
$AAPL[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$AAPL = json_encode($AAPL);
foreach($FB_data as $val){
$FB[] = strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close']; //sets the date as a javascript timestamp
}
$FB = json_encode($FB);
JS code:
$(function () {
var seriesOptions = [],
yAxisOptions = [],
colors = Highcharts.getOptions().colors;
seriesOptions[0] = {
name: 'MSFT',
data: <? php echo $MSFT; ?>
};
seriesOptions[1] = {
name: 'AAPL',
data: <? php echo $AAPL; ?>
};
seriesOptions[2] = {
name: 'FB',
data: <? php echo $FB; ?>
};
function createChart() {
chart = new Highcharts.StockChart({
chart: {
renderTo: 'container'
},
rangeSelector: {
selected: 4
},
yAxis: {
labels: {
formatter: function () {
return (this.value > 0 ? '+' : '') + this.value + '%';
}
},
plotLines: [{
value: 0,
width: 2,
color: 'silver'
}]
},
plotOptions: {
series: {
compare: 'percent'
}
},
tooltip: {
pointFormat: '<span style="color:{series.color}">{series.name}</span>: <b>{point.y}</b> ({point.change}%)<br/>',
valueDecimals: 2
},
series: seriesOptions
});
}
});
If you have any questions or need further information, please let me know with a comment.
Thanks
BTW: I have all necessary assets included for Highcharts to work; when I replace my JS + PHP with example code from the Highcharts site, it works beautifully. So the problem clearly lies in my JS + PHP code.
Alright, I believe I found the problem, it lies in the way that you are storing each individual point in the array.
Instead of this (which is passing a string x,y separated by a comma):
strtotime($val['Date']) * 1000 . ', ' . (float)$val['Close'];
You are going to want to use something like this (Highcharts accepts arrays or associative arrays):
array((strtotime($val['Date']) * 1000), ((float)$val['Close']));
That will store the X and Y variables as an array instead of comma separated string for the javascript to pass as data.

Return Multiple Values on Passing Arguments via AJAX, PHP and MYSQL

I am developing ajax Based Search , This is demo of how it will be. I am faceing Problem in returning result. I need to show the Result 2 times. But its only showing once. Below is my HTML code
<form action="" method="post" id="demoform">
<select style="width:250px;padding:5px 0px;color:#f1eedb;" name="product" class="product">
<option>TENNIS</option>
<option>FOOTBALL</option>
<option>SWIMMING</option>
</select>
</form>
<div id="result">Display Result Here</div>
I Using The Below Ajax Script to Retrieve Data :-
$(".product").change(function(){
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
product : $(".product option:selected").text(),
},
success : function(data){
$('#result').removeClass().addClass((data.error === true) ? 'error' : 'success')
.html(data.msg).show();
if (data.error === true)
$('#demoForm').show();
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#result').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show();
}
});
});
The post.php file has the following code :-
<?php
require('connect.php');
$get_select = $_POST[product];
if($get_product!='FOOTBALL'){
$return['error'] = true;
return['msg'] = 'Incorrect Selection';
echo json_encode(return);
}
else {
$return['error'] = false;
$i=0;
while($i<2) {
return['msg'] = $get_product;
}
echo json_encode(return);//Returns only one result.
}
?>
I need to show the result Two times as "CRICKET CRICKET", but its only showing once.
What should i do to get both the result.
Is it possible that this line is confusing php:
while($i<2) {
return['msg'] = $get_product;
}
Should it be $return? Using a reserved word like 'return' is a tad iffy too.
Please change the following code:
else {
$i=0;
$messageToReturn = "";
while($i<2) {
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn); //Returns the result
}
I would suggest to change the while to a for loop.
In that case you will get this:
else {
$messageToReturn = "";
for($i = 0; $i < 2; $i++)
{
$messageToReturn .= $get_product; //Append to your variable
}
return json_encode($messageToReturn);
If you know the times you need to repeat, use a for loop. The while is never ending. So you can get a possible stack overflow...

php with jquery html pop up

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.

Jquery autocomplete - strip tags to enter into input

I have the following jquery autocomplete code which works perfectly:
$("#autoc1").autocomplete("/autoc2.php?arg=1&category=<? echo $category_id; ?>", {
width: 400,
matchContains: true,
minChars: 3,
selectFirst: false
});
I format the data using PHP to show an image in the automplete, for a better more informative UI for the user, the PHP code is:
$query = "SELECT $title, imageURL FROM PRprodINFO2 WHERE ((prodcatID = '$cat_id')
AND ($title LIKE \"%" . $_GET["q"] . "%\")) group by $title LIMIT 8"; }
$result = mysql_query($query);
$output_items = array();
while($row = mysql_fetch_array($result)) {
$row[$title] = preg_replace('/[^\w\s].*$/', "", $row[$title]);
$row[$title] = trim($row[$title]);
$output_items[$row['title']] = $row['imageURL'];
} // while
$output_items = array_unique($output_items);
$output = '';
foreach ($output_items as $title => $image) {
$output .= '<img src='.$image.' style=max-width:50px;>'.$title."\n";
}
echo $output;
The problem is that the JQuery autocomplete code is pushing the <img> tag data into the input as well.
Is there a way to format like this but have only the item title in the input box without the <img src=/....>?
You can achieve that by extending the Autocomplete plugin by overwriting certain core functions, mainly "parse". The internal version of this function simply loops over each line of the returned data and “parses” it into an array of objects, each containing the following attributes:
data – the entire entry
value – the default display value
result – the data to populate the input element on selection
You can overwrite this by passing your own parse function as part of the options object to autocomplete.
you will also need to provide a "formatItem" function that will give you a chance to format the data shown in the autocomplete dropdown!
var acOptions = {
minChars: 3,
max: 100,
dataType: 'json', // this parameter is currently unused
extraParams: {
format: 'json' // pass the required context to the Zend Controller
},
parse: function(data) {
var parsed = [];
data = data.users;
for (var i = 0; i < data.length; i++) {
parsed[parsed.length] = {
data: data[i],
value: data[i].displayName,
result: data[i].displayName
};
}
return parsed;
},
formatItem: function(item) {
return item.displayName + ' (' + item.mail + ')';
}
};
Then you can call and also provide a function that can remove the image as required by you in the .result call as follows:
jQuery(document).ready(function($) {
$('#user_id')
.autocomplete('/path/to/ajax/data/source', acOptions)
.attr('name', 'display_name')
.after('<input type="hidden" name="user_id" id="ac_result">')
.result(function(e, data) {
$('#ac_result').val(data.uid); // remove the img here for your text field!
});
});
Hope this helps!
try this :
$img = $('img');
$img.replaceWith($img.html());
read here Jquery remove form tag, not content

Categories