I have code in javascript:
if (imageData[imageCount].comments.data != null)
{
text = 'Comments Data:<br />';
imageData[imageCount].comments.data.forEach(function(comment){
text += comment.from.username + ': ' + comment.text + '<br />';
});
}
Which imageData[imageCount] refers to $data in PHP.
i've trying to rewrite self in PHP but it doesn't worked.
foreach ($contents->data as $data) {
if ($data->comments->data != null)
{
foreach($data->comments->data as $comment)
{
$text = comment->from->username + ': ' + comment->text + '<br />';
});
}
I'm sure to have problem with the code structure. It returns Invalid argument supplied for foreach()
-- Edit --
I've successed to convert the snippet to PHP. But i faced a new problem since i'm trying to create XML File from API (in this case Instagram API).
Look at productName and productPrice attribute from product section:
http://pastebin.com/ubGGyp9b
Value productName="Sushi Homemade " and productPrice="50.000 " is just for productID="002". But why the value also filled to next productID >= 002.
Is there mistake from this code:
<products>
<category categoryName="Instagram">
<?php
foreach ($contents->data as $data) {
foreach($data->comments->data as $comment){
if(preg_match('/#title/', $comment->text)){
$komen = preg_replace('/#title/', '', $comment->text);
break;
} else { $komen = 'No Title'; }
}
foreach($data->comments->data as $comment){
if(preg_match('/#price/', $comment->text)){
$harga = preg_replace('/#price/', '', $comment->text);
break;
} else { $harga = '0'; }
}
echo '<product productName="'. $komen .'" productID="' . $data->id . '" thumbPath="' . $data->images->thumbnail->url . '" productPrice="'. $harga .'">
<details>
<![CDATA[
<img src="' . $data->images->low_resolution->url . '" width="100%"/>
' . $data->caption->text . '
]]>
</details>
</product>
You forgot an $ in the last line and some brackets were not correctly set. To concat strings in PHP use "." instead of "+"
foreach ($contents->data as $data) {
if ($data->comments->data != null) {
foreach ($data->comments->data as $comment) {
$text = $comment->from->username . ': ' . $comment->text . '<br />';
}
}
}
Related
I have been struggling with this for the last two hours and I can't get it to work. Take a look to the following piece of code:
$js = '$.extend($.fn.fmatter , {
userActions : function(cellvalue, options, rowData, addOrEdit) {
var data = cellvalue.split("|");
var id = options.rowId;
var actions = "";';
foreach ($editorActions as $linkType => $value) {
switch ($linkType) {
case 'view':
$js .= "if(data[1] == 1) {
actions += \"<a class='actionimage' href='" . $value . " + options.rowId' title='" . $this->translate->_e('View') . "' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>\";
}";
}
break;
}
As you can see id is a value coming from Javascript and $value is coming from PHP. The idea is to get an hyperlink as for example:
$value = "/route/to/function/";
id = 19009; // I've omitted the $ sign since this var is coming from JS
var href = "' . $value . '" + id;'
Then I need to use the href var as part of the <a> element shown right after the definition.
With my code above I am getting this error:
Uncaught SyntaxError: Invalid or unexpected token
Can I get some help to get this right?
UPDATE:
This is how the code looks like after I render the page:
$(function () {
$.extend($.fn.fmatter, {
userActions: function (cellvalue, options, rowdata) {
var data = cellvalue.split('|');
var id = options.rowId;
var actions = '';
console.log(id);
if (data[1] == 1) {
actions += "<a class='actionimage' href='/sf/distributor/show/ + options.rowId' title='View' onClick='load_start();'><img src='/images/icons/16x16/document_view.png' width='16' height='16' alt='' /></a>";
}
return actions;
}
});
});
Notice how the function $.extend close properly. console.log(id) did print the value of options.rowId however this value doesn't have any effect on the hyperlink as you may notice this is the value /sf/distributor/show/ + options.rowId.
What is coming in $value is a plain string in the case above /sf/distributor/show/.
You're missing double quotes and to end and reopen the string around options.rowId and a + in:
actions += \"<a class='actionimage' href='" . $value . " + options.rowId'
It should be:
actions += \"<a class='actionimage' href='" . $value . "\" + options.rowId + \"'
Here you are missing "" and that way you are adding options.rowId as a string text.
href='/sf/distributor/show/" + options.rowId + "'
Have been searching around for a while and can't find a proper answer to this problem. I have a "finance" tracker that has several hidden divs which using jQuery appear when the button to show that div is clicked. I have a Asset Tracker which queries a database and upon being checked updates the database with new values in adjacent input rows where the checkbox is located. I am trying to get the checkbox to submit the data without causing the page to reload and the div to "toggle" off again.
On the form section I attempted to remove the method='post' but instead when checking the box it reloaded the page and added all the post variables to the URL string. I removed the action='FBook.php' in an attempt to prevent the reloading, but that did not resolve the problem.
Here is the related code from the PHP file:
if(isset($_POST['AssetSetUpdate'])) { $AssetLastUpdate = $dtNowDate->format('Y-m-d');
foreach($_POST['AssetID'] as $key => $id) { if(isset($_POST['AssetSetUpdate'][$key])) {
$stmt_ATrackUp -> bindParam(':UpDate', $AssetLastUpdate, PDO::PARAM_STR, 10);
$stmt_ATrackUp -> bindParam(':UpNotes', $_POST['AssetNotes'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpThis', $_POST['AssetDescription'][$key], PDO::PARAM_STR, 50);
$stmt_ATrackUp -> bindParam(':UpVal', $_POST['AssetValue'][$key], PDO::PARAM_INT, 3);
$stmt_ATrackUp -> execute(); } else continue; }
echo "<div class='Notice'>" . $PageTitle . " / Assets updated!</div>"; }
(other code)
$(document).ready(function() {
$("#AssetUpdateForm").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'FBook.php',
data: $(this).serialize(),
success: function() { alert('form submitted'); },
});
return false;
});
$('#ShFBAsset').click(function() { $('#FBAsset').toggle('slow'); });
(other code)
});
(other code)
$AssetCounter = 1;
$stmt_ATrack -> execute(); while ($row_ATrack = $stmt_ATrack -> fetch(PDO::FETCH_ASSOC))
{
$ChAge = $row_ATrack['Checked']; $cChAge = ''; switch(true)
{
case (strtotime($ChAge) >= strtotime('-7 days')): $cChAge = 'FBCAN'; break;
case (strtotime($ChAge) >= strtotime('-30 days')): $cChAge = 'FBCA1'; break;
case (strtotime($ChAge) >= strtotime('-90 days')): $cChAge = 'FBCA3'; break;
default: $cChAge = 'FBCA6'; break;
}
if(isset($row_ATrack['Serial'])) { $IfDSerial = "<strong>Serial: </strong>" . $row_ATrack['Serial'] . "<br/>"; } else { $IfDSerial = ''; }
if(isset($row_ATrack['UPC'])) { $IfDUPC = "<strong>UPC: </strong>" . $row_ATrack['UPC'] . "<br/>"; } else { $IfDUPC = ''; }
if(isset($row_ATrack['Related'])) { $IfDRelated = "<strong>Related: </strong>" . $row_ATrack['Related'] . "<br/>"; } else { $IfDRelated = ''; }
if(isset($row_ATrack['Location'])) { $IfDLocation = "<strong>Location: </strong>" . $row_ATrack['Location'] . "<br/>"; } else { $IfDLocation = ''; }
if(isset($row_ATrack['TagPhoto'])) { $IfDTagPhoto = "<strong>Tag photo: </strong><a href='Images/INV/" . $row_ATrack['TagPhoto'] . ".JPG'>" . $row_ATrack['TagPhoto'] . "</a><br/>"; } else { $IfDTagPhoto = ''; }
$IfDetails = "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'>" . ($IfDSerial) . ($IfDUPC) . ($IfDRelated) . ($IfDLocation) . ($IfDTagPhoto) . "</div></div>";
if($IfDetails == "<div class='UPop'><img class='th_icon' src='Images/Icons/ic_lst.jpeg'><div class='UPopO'></div></div>") { $IfDetails = ''; }
echo "<form id='AssetUpdateForm[" . $AssetCounter . "]' method='post'>";
echo "<tr><input type='hidden' name='AssetID[" . $AssetCounter . "]' value='" . $AssetCounter . "' />";
echo "<td><input type='hidden' name='AssetDescription[" . $AssetCounter . "]' value='" . $row_ATrack['Description'] . "' /><a href='https://www.google.com/#q=eBay+" . $row_ATrack['Description'] . "' target='_new_AssetSearch'>" . $row_ATrack['Description'] . "</a></td>";
echo "<td>" . $row_ATrack['Type'] . " - " . $row_ATrack['Category'] . "</td>";
echo "<td><input type='checkbox' name='AssetSetUpdate[" . $AssetCounter . "]' value='Now' onchange='this.form.submit();' /></td>";
echo "<td><input type='number' name='AssetValue[" . $AssetCounter . "]' value = '" . $row_ATrack['Value'] . "' style='width: 75px;' /></td>";
echo "<td class='" . $cChAge . "'>" . $ChAge . "</td>";
echo "<td><input type='text' name='AssetNotes[" . $AssetCounter . "]' value = '" . $row_ATrack['Notes'] . "' style='width: 140px;' /></td>";
echo "<td>" . $IfDetails . "</td>";
echo "</tr>";
echo "</form>";
$AssetCounter++;
}
Your JavaScript:
$("#AssetUpdateForm")
… is working on a form with id="AssetUpdateForm".
Your PHP says:
id='AssetUpdateForm[" . $AssetCounter . "]'
which in HTML terms becomes:
id='AssetUpdateForm[something]'
Even if the variable is empty, you still have the square brackets, so the ID is not going to match and the JavaScript event handler will never be bound to that element.
You need to either use the real ID or, since it appears that it can change, add a class to the form and use a .class-selector in the JavaScript.
NB: Your HTML is invalid. The particular problem you have has the potential to cause the same symptoms are you describe so just fixing the problem above might not be enough. Use a validator and write valid HTML too.
Had nothing to do with the HTML or PHP. Turns out that jQuery AJAX was conflicting with the onclick='this.form.submit();' property. I removed that and changed the ajax request to the following - and while it still has bugs as it won't work on the 2nd ajax request, it validates everything else is fine.
$(".Check2Update").on('change', function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'FBook.php',
data: $(this.form).serialize(),
success: function(html) {
console.log('Successfully submitted AJAX!');
$("#TableAssets").replaceWith($('#TableAssets', $(html)));
}
});
});
I want to know how to write a pice of PHP code into JavaScript/Ajax.
This is my PHP code:
if ($folder = opendir('data/Tasklist/')) {
while (false !== ($file = readdir($folder))) {
if ($file != '.' && $file != ".."){
$data=file_get_contents("data/Tasklist/".$file);
$poc=explode(";",$data);
echo '<li class="taskli">
<button id="'. $file . '" class="Del"> Delete </button>
'. $poc[0] . " " . $poc[1] . '<div class="hidinfo">' . $poc[2] . '</div></li>';
}
}
closedir($handle);
}
And i want to write : id="'. $file . '" inside this code:
$.post( "data/remove.php",{HERE})
Since you're storing the $file variable in the <button> id, you can grab it from there:
$('.Del').click(function(){
var file = $(this).attr('id');
$.post( "data/remove.php",{id:file});
return false;
});
I'm trying to alter the src of imgs loaded via. AJAX, wherein the <select> and <option> elements used to control the function are also loaded by AJAX.
I'm trying to do this in order to change the size of Flickr images on the page.
I've tried loading the element, and calling an existing function to update it, but of course the <select> option doesn't exist on document.ready() and thus returns null when I try to get it.
I've also tried loading a new <script type='text/javascript'></script> in the PHP file I'm using for my XML response, but although this shows on the page it obviously isn't picked up as a source.
How can I tell the Document to 're-ready' itself, or acknowledge new sources?
Here's my code as it stands:
Making the request
function makeRequest (url, userID, searchString, selectedLicense) {
event.preventDefault();
var formData = new FormData();
formData.append("userID", userID);
formData.append("searchString", searchString);
formData.append("selectedLicense", selectedLicense);
var xmlRequest = new XMLHttpRequest();
xmlRequest.open("POST", url, true);
xmlRequest.send(formData);
xmlRequest.onreadystatechange=function()
{
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
document.getElementById("results").innerHTML=xmlRequest.responseText;
} else {
document.getElementById("results").innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
}
}
The PHP
//more code before
$resultString = $resultString . "<script type='text/javascript'>"
. "function sizeChanged(i, select) {
var sel = getSelectedOptionValue(select);
var imgURL = document.getElementById(i.toString());
alert(imgURL);
}"
. "</script>";
//main loop
foreach ($XML->photos->photo as $photo):
$resultString = $resultString . '<div class="photoBox"' . photoBox($photoCounter) . "> <p>" . $photoCounter . ". " . $photo['title'] . "" . "</p>"
. " <p>" . "<img id='" . $photoCounter . "' src=\"http://farm" . $photo['farm'] . $imgURL . "/" . $photo['server'] . "/" . $photo['id'] . "_" . $photo['secret'] . "_" . $size . "\" alt=\"" . $photo['title'] . "\">" . "</p>"
. "<select form='addInformationForm' id='selectSize" . $photoCounter . "' onChange='return sizeChanged(" . $photoCounter . ", selectSize" . $photoCounter . ");'>"
. "<option value='n'>Small (320)</option>"
. "<option value='z' selected='selected'>Medium (640)</option>"
. "<option value='h'>Large (1600)</option>"
. "</select>"
. "</div>";
$photoCounter++;
endforeach;
//more code here
echo $resultString;
The HTML Output (Example)
<div class="photoBox" style="background-color:#FFFFFF">
<p>1. Killip's Adirondack Travelog, page 20</p>
<p><img id="1" src="http://farm9.staticflickr.com//8184/8427833074_2f7e22e7ce_z.jpg" alt="Killip's Adirondack Travelog, page 20"></p>
<select form="addInformationForm" id="selectSize1" onChange="return sizeChanged(1, selectSize1);">
<option value="n">Small (320)</option>
<option value="z" selected="selected">Medium (640)</option>
<option value="h">Large (1600)</option></select>
</div>
Any advice much appreciated!
NOTE: This code is for an internal tool, not a client-facing website.
The <select> doesn't exists at onload, but it does when you create it:
var res = document.getElementById("results");
xmlRequest.onreadystatechange = function() {
if (xmlRequest.readyState===4 && xmlRequest.status===200) {
document.getElementById("working...").innerHTML="<p style='background-color:#BCED91; width:200px; text-align:center;'>Done!</p>";
res.innerHTML = xmlRequest.responseText;
var select = res.getElementsByTagName('select')[0];
/* Use select here */
} else {
res.innerHTML="<p>Ready State: " + xmlRequest.readyState + "</p> <p>Status Code: " + xmlRequest.status + "</p>";
}
};
Note that the <img> element should be available too, but you won't know its dimensions because it won't be downloaded. If you want to wait until it's loaded, you can add a load event listener.
I would like to show the geozone in the registration account step as dropdown menu, just like the zone (region). But the value of the geozone is dependent to what customer choose in the zone (region).
The Picture
In the process, I already did some modifications to the controller, view, including controller. Just like in the pic below :
The geozone field is Kotamadya/Kabupaten.
But when I choose the region Aceh, the geozone field is not refreshed.
Error Message
I got error message like below :
SyntaxError: Unexpected token <
OK
<br />
<b>Fatal error</b>: Call to a member function
getGeozonesByZoneId() on a non-object in <b>
/home/........../catalog/controller/account/register.php
</b> on line <b>513</b><br />
The Code
In ../controller/account/register.php, I added some modifications as below :
public function zone() {
$json = array();
$this->load->model('localisation/zone');
$geozone_info = $this->model_localisation_zone->getZone($this->request->get['zone_id']);
if($geozone_info)
{
$this->load->model('localisation/geo_zone');
$json = array(
'country_id' => $geozone_info['country_id'],
'name' => $geozone_info['name'],
'code' => $geozone_info['code'],
'zone' => $geozone_info['zone_id'],
'geozone' => $this->model_localisation_geozone->getGeozonesByZoneId($this->request->get['zone_id']),
'status' => $geozone_info['status']
);
}
$this->response->setOutput(json_encode($json));
}
line 513 is :
'geozone' => $this->model_localisation_geozone->getGeozonesByZoneId($this->request->get['zone_id'])
I don't know what's wrong with the getGeozonesByZoneId function, because I think I already write the function correctly in ../model/localisation/geo_zone.php as below :
<?php
class ModelLocalisationGeozone extends Model {
public function getGeozone($zone_id) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "geo_zone WHERE geo_zone_id = '" . (int)$geo_zone_id . "'");
return $query->row;
}
public function getGeozonesByZoneId($zone_id) {
$geozone_data = $this->cache->get('geozone.' . (int)$zone_id);
if (!$geozone_data) {
$query = $this->db->query("SELECT * FROM " . DB_PREFIX . "zone_to_geo_zone WHERE zone_id = '" . (int)$zone_id . "'");
$geozone_data = $query->rows;
$this->cache->set('geozone.' . (int)$zone_id, $geozone_data);
}
return $geozone_data;
}
}
?>
and I already added javascript to register.tpl in view as below :
$('select[name=\'zone_id\']').bind('change', function(event, first_time) {
$.ajax({
url: 'index.php?route=account/register/zone&zone_id=' + this.value,
dataType: 'json',
beforeSend: function() {
$('select[name=\'zone_id\']').after('<span class="wait"> <img src="catalog/view/theme/default/image/loading.gif" alt="" /></span>');
},
complete: function() {
$('.wait').remove();
},
success: function(json) {
var html = '<option value=""><?php echo $text_select; ?></option>';
var selected = false;
if (json['geozone'] && json['geozone'] != '') {
for (i = 0; i < json['geozone'].length; i++) {
html += '<option value="' + json['geozone'][i]['geo_zone_id'] + '"';
if (json['geozone'][i]['geo_zone_id'] == '<?php echo $geo_zone_id; ?>') {
html += ' selected="selected"';
selected = true;
}
html += '>' + json['geozone'][i]['name'] + '</option>';
}
} else {
html += '<option value="0" selected="selected"><?php echo $text_none; ?></option>';
}
$('select[name=\'geo_zone_id\']').html(html);
if(typeof first_time === "undefined" && selected) {
$("#register_details_form").validate().element('#register_details_form select[name="geo_zone_id"]');
}
},
error: function(xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
});
$('select[name=\'zone_id\']').trigger('change', ['first_time']);
anyone can help me to resolve this issue? or maybe have same experiences with me and willing to share your solutions to me?
thanks before in advance.
Use model_localisation_zone (defined variable) instead of model_localisation_geozone (not defined), or make sure the latter is defined.
if i am not wrong you are forgetting to load model Geozone in your register.php controller file add this line
$this->load->model('localisation/geozone');
to register.php
before calling function
$this->model_localisation_geozone->getGeozonesByZoneId($this->request->get['zone_id'])