How to properly concatenate values coming from Javascript and PHP? - javascript

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 + "'

Related

How to get a anchor link text inside a javascript and calling with arguments

I wrote a function like to get a user from server and i got it . Now i create a links for each users using a href inside java script . This is working fine . Now i want to execute a function when i user click the link (with the corresponding user name)
var User_id = document.querySelector(".sidebar-name");
//getting array of user
function list(user){
User_id.innerHTML = "";
for( i = 0; i < user.length; i++ ){
User_id.innerHTML+= "<a href='#' onclick = 'javascript:calluser(this);' style='text-decoration:none'>" + user[i] + "</a>" + "<br />";
}
}
function calluser(this){
alert(user);
// i need to print the corresponding username or anchor text .
// how can i solve this ?
}
I tried with id inside a href . But this is not unique so it won't work . How can i solve this ?
"function calluser(this) " Is a Syntax error.
Rename "this" with something else like "a":
var User_id = document.querySelector(".sidebar-name");
function list(user){
User_id.innerHTML = "";
for(var i=0; i<user.length; i++){
User_id.innerHTML+= "<a href='jacascript:void();' onclick='javascript:calluser(this);' style='text-decoration:none'>" + user[i] + "</a>" + "<br />";
}
}
function calluser(a){
alert(a.text);
}

How can i pass String to onclick message?

public function confirmTransactionButton($confirmationFlag, $buttonName) {
$disabled = '';
$warningMessages = 'Watch Out';
$functionName = "return confirm(" . '\'' . "$warningMessages" . '\'' . ")";
if ($confirmationFlag == constant("Y.ENUM")) {
$disabled = 'disabled';
}
$button = "<input name='$buttonName' type='submit' class='BUTTON' id='$buttonName' onclick='$functionName' value='" . constant('KONFIRMASI.CON') . "' " . $disabled . " />";
return $button;
}
can anyone help me this issue, alert dialog won't appear.
i case i change string to number, its work
$warningMessages = 'Watch Out';
$functionName = "return confirm(" . '\'' . "$warningMessages" . '\'' . ")";
To
$warningMessages = '123';
$functionName = "return confirm(".$warningMessages.")";
The problem is hat you are using the same delimiter for the JS string and for the HTML attribute value, this terminating the attribute value prematurely. Look at the generated source and you will see:
It would look something like
<input ... onclick='confirm('foo')' />
Can you see the problem (the syntax highlighter helps)?
You can fix this by using different quotation marks:
$functionName = "return confirm(" . '"' . "$warningMessages" . '"' . ")";
// ^ ^
So your HTML will become
<input ... onclick='confirm("foo")' />
And of course the best solution would be to not use inline event handlers at all. Have a look at these articles to learn more about event handling.

Php Javascript Youtube API error

I've got this code, which add videos (and videos infos) of a YouTube channel ($_POST) on a div of the Html code :
var args= "url="+urlchaine;
xhr_object.open("POST", "traitement.php", true);
xhr_object.onreadystatechange = function() {
if(xhr_object.readyState == 4) {
eval(xhr_object.responseText);
}
return xhr_object.readyState;
}
xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr_object.send(args);
traitement.php :
<?php
if ( isset($_POST["url"]) && !empty($_POST["url"]) )
$urlchaine = $_POST["url"];
else
$urlchaine = null;
$stringresult = str_replace("http://www.youtube.com/user/", "",$urlchaine);
require_once "Zend/Loader.php";
Zend_Loader::loadClass('Zend_Gdata_YouTube');
$yt = new Zend_Gdata_YouTube();
//Get Video info with channel name $stringresult
$videoFeed = $yt->getVideoFeed('http://gdata.youtube.com/feeds/users/...');
if ( $stringresult != null){
echo "var mydiv = document.getElementById('vids');";
echo "var newcontent = document.createElement('div');";
foreach ($videoFeed as $v): $thumbs = $v->getVideoThumbnails();
$videoId = $v->getVideoId();
$thumb = $thumbs[0]['url'];
$videoViewCount = $v->getVideoViewCount();
$videoTitle = $v->getVideoTitle();
echo "newcontent.innerHTML =
'<div class=\"videos\">' +
' <div class=\"img_videos\">' +
' <img class=\"img_video\" width=\"250\" idvideo=\"".$videoId."\" ' +
' src=\"".$thumb."\"/>' +
' </div>' +
' <h3>$videoTitle</h3>' +
' <p>$videoViewCount views</p>' +
'</div>' ;";
echo "mydiv.appendChild(newcontent.firstChild);";
endforeach;
?>
The problem is, when I want to do that, it works perfectly with some channels, whereas an error has existed for others (Uncaught SyntaxError: Unexpected identifier). After several tests, I saw that by removing the display of $ videoTitle, every channels test worked. What is wrong with my code? O.o
$videoTitle seems to contains a simple quote in somes cases, which break your JS code.
Try escaping this quotes with something like this :
str_replace("'", "‚", $videoTitle)

Rewrite code from javascript to PHP

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 />';
}
}
}

Cannot get the dependent dropdown value from region dropdown

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'])

Categories