javascript: add script to a .js file trouble - javascript

so for pagination I have this url that when a user press the link it goes to the next page (the link parts are in a partial view), for that to work i get the dropdowbox value with javascript and pass to the url
#Html.ActionLink("|Siguiente >", "Index", new { pagina = Model.PageNumber + 1, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro , empresa = "param-empresa" }, new { id = "mylinkSig" })
<script type="text/javascript">
$(function () {
$('#mylinkSig').click(function () {
var empresa = $("#empresa").val();
this.href = this.href.replace("param-empresa", encodeURIComponent(empresa));
});
});
</script>
as I use the script in almost all my page i want to put this script in a js file so i dont have to write it in all my view (pages) y try to copy/paste and put in a js file and it dont work (yes i have the .js file refence in my page)
so iam new to javascript so i dont know if i have to change the function for it could work in the .js file an use it in all my page
edit:
my Helper.js
$(function () {
$('#mylinkSig').click(function () {
var empresa = $("#empresa").val();
this.href = this.href.replace("param-empresa", encodeURIComponent(empresa));
});
});
function deleteConfirmation(response, status, data) {
// remove the row from the table
var rowId = "#widget-id-" + response.id;
$('.widgets').find(rowId).remove();
// display a status message with highlight
$('#actionMessage').text(response.message);
$('#actionMessage').effect("highlight", {}, 3000);
if (response.message == null) {
alert('No se pudo eliminar el registro');
}
else {
alert(response.message);
}
}
my view
<script src="#Url.Content("~/Scripts/Helper.js")" type="text/javascript"></script>
#*navigation << < >>>*#
<div>
Pagina #(Model.PageCount < Model.PageNumber ? 0 : Model.PageNumber)
de #Model.PageCount
#if (Model.HasPreviousPage)
{
#Html.ActionLink("<<|", "Index", new { pagina = 1, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro, empresa = "param-empresa" }, new { id = "mylinkFirst" })
#Html.Raw(" ");
#Html.ActionLink("< Anterior|", "Index", new { pagina = Model.PageNumber - 1, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro, empresa = "param-empresa" }, new { id = "mylinkAnt" })
}
#if (Model.HasNextPage)
{
#Html.ActionLink("|Siguiente >", "Index", new { pagina = Model.PageNumber + 1, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro , empresa = "param-empresa" }, new { id = "mylinkSig" })
#Html.Raw(" ");
#Html.ActionLink("|>>", "Index", new { pagina = Model.PageCount, ordenacion = ViewBag.Ordenacion, filtro = ViewBag.Filtro , empresa = "param-empresa"}, new { id = "mylinkLast" })
}
</div>

If you have a reference to the file, then my best guess is that you are copying the script-tag into the JS-file as well, which you shouldn't.
Try just copying this part:
$(function () {
$('#mylinkSig').click(function () {
var empresa = $("#empresa").val();
this.href = this.href.replace("param-empresa", encodeURIComponent(empresa));
});
});
If you do that, there shouldn't be a difference between having the code within the page, compared to having it in a separate file.

Related

How to change qr code filename while downloading the file using html.twig and javascript

I have a qr-code button. On click, qr-code is generated and dialog to save the image format pops-up. In which the filename always comes as "qrcode.png". I have to dynamically change the filename to the name of the files from where the qr-code is generated.
Please, help. I am new to this technology.
HTML TWIG
<th data-field="QR-BTN" data-width="60px" data-orderable="false">{{ 'QR'|trans }}</th>
JAVASCRIPT
var QREXPORT = (function() {
var qrCodeExport = function (e){
e.preventDefault();
//goqr.me api url
const QRCODE_API_URL = "https://api.qrserver.com/v1/create-qr-code/?"; //Library Used
var $form = $('#modal-qr-export-offering'),
qrFormat = $("input[name='qrCodeType']:checked").val(),
jsFormData = $form.data('bs.modal'),
accessCode = jsFormData.options.accesscode;
var params = {
data: "SESSION-" + accessCode,
size: "250x250",
margin: 0,
download: 1,
format: qrFormat,
};
window.location.href = QRCODE_API_URL + $.param(params);
};
return {
init: function() {
$(document).ready(function(){
$('#radioSvg').prop('checked', true);
$('#modal-qr-export-offering').on('hidden.bs.modal', function() {
location.reload();
});
});
$(document).on('click', '.js-btn-submit-form', qrCodeExport);
}
};
})();
QREXPORT.init();
Try using the a tag with download attribute...?
const linkEl = document.createElement('a')
linkEl.href = QRCODE_API_URL + $.param(params);
linkEl.download = 'download-name-here.png'
document.body.appendChild(linkEl)
linkEl.click()
// Maybe remove the link after it worked...?
linkEl.remove()

How to fix multiple appending in the div using jquery

I have problem regarding on appending a sample a href to the div or to the html elements, I have only 3 array response to my ajax, however the results shows duplicate item to the corresponding div. I will share to you guys my sample code that already made,
I have here my backend php:
<?php
require_once('../ConnectionString/require_db.php');
session_start();
//submit function
$status = 'Active';
$posttype_affiliation_page = 'affiliation_page';
$posttype_member_org_page = 'member_org_page';
$affiliation_member_org_content = $db->prepare('SELECT title,link,posttype FROM tblcontent
WHERE status = ? AND posttype = ? OR posttype = ? ORDER BY contentID DESC')
or die($db->error);
$affiliation_member_org_content->bind_param('sss',$status,$posttype_affiliation_page,$posttype_member_org_page);
$affiliation_member_org_content->execute();
$affiliation_member_org_content->bind_result($title,$link,$posttype);
$result = array();
while ($affiliation_member_org_content->fetch()) {
$result[] = array('title'=>$title,'link'=>$link,'posttype'=>$posttype);
header('Content-type: application/json');
}
echo json_encode($result);
?>
my front end:
$(document).ready(function(){
//mission vision
$.ajax({
url:'./Function/fetch_affiliation_member_org.php',
type:'get',
success:function(response_fetch_affiliation_member_org) {
console.log(response_fetch_affiliation_member_org);
var fetch_affiliation_member_org = jQuery.parseJSON(JSON.stringify(response_fetch_affiliation_member_org));
$.each(fetch_affiliation_member_org,function(i,data){
if(data.posttype == 'affiliation_page') {
const title = data.title;
const link = data.link;
var data = "";
data = '<p style="font-size:14px;" class="list_affiliation_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_affiliation_links').append(data);
}
else if(data.posttype == 'member_org_page') {
const title = data.title;
const link = data.link;
var data = "";
data = '<p style="font-size:14px;" class="list_member_org_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_member_org_links').append(data);
}
});
},
error:function(error) {
console.log(error);
}
});
});
My Html:
<div class="Affiliation">
<h5>Affiliation</h5>
<p style="font-size:14px;" class="list_affiliation_links">
</p>
</div>
<br>
<div class="Member">
<h5>Member Organizations</h5>
<p style="font-size:14px;" class="list_member_org_links">
</p>
</div>
$(document).ready(function(){
//mission vision
$.ajax({
url:'./Function/fetch_affiliation_member_org.php',
type:'get',
success:function(response_fetch_affiliation_member_org) {
console.log(response_fetch_affiliation_member_org);
var fetch_affiliation_member_org = jQuery.parseJSON(JSON.stringify(response_fetch_affiliation_member_org));
$.each(fetch_affiliation_member_org,function(i,data){
if(data.posttype == 'affiliation_page') {
const title = data.title;
const link = data.link;
var data = "";
$('p.list_affiliation_links').html('');
data = '<p style="font-size:14px;" class="list_affiliation_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_affiliation_links').append(data);
}
else if(data.posttype == 'member_org_page') {
const title = data.title;
const link = data.link;
var data = "";
$('p.list_member_org_links').html('');
data = '<p style="font-size:14px;" class="list_member_org_links"><a href='+link+'>'+title+'</a></p>';
$('p.list_member_org_links').append(data);
}
});
},
error:function(error) {
console.log(error);
}
});
});
You should first clear html content and then set to DOM element. Might be it works for you.
you're appending a second p tag with your HTML that also gets selected in your append later in the code. You should only build the link withing the var data.
Greetings

Ajax call falls into error before running the controller

I have an ajax call that is falling into error block before even running the controller.
The strange thing is that sometimes(after multiple requests) it does run succesfully but it does not save the cookies in the controller.
I think it could be the ajax call or some permission error.
AJAX CALL:
$('#loginAWGPE').on('click', function () {
var cpfLogin = $('#cpfValidacao').val().replace(/[^\d]+/g, '');
console.log(cpfLogin);
console.log(urlOrigem + appPath + "Login/validaCPF");
$.ajax({
type: 'POST',
url: urlOrigem + appPath + "Login/validaCPF",
datatype: String,
data: {
cpf: cpfLogin
},
success: function (teste) {
console.log('dataS: ' + teste);
if (teste = true) {
window.location = urlOrigem + appPath + "ProjetoEletrico/Index";
} else {
alert('CPF não cadastrado na Agência Virtual!');
}
},
error: function (teste2) {
console.log('dataE: ' + teste2);
alert('Erro na execusão');
}
});
});
-------CONTROLLER:
public JsonResult validaCPF(String cpf)
{
if (String.IsNullOrEmpty(cpf))
{
Response.StatusCode = (int)HttpStatusCode.Unauthorized;
return Json(false);
}
WebAPIPArameter id = new WebAPIPArameter();
id.ParameterName = "id";
id.ParameterValue = cpf;
List<WebAPIPArameter> list = new List<WebAPIPArameter>();
list.Add(id);
Usuario userInfo = (Usuario)apiClientSistema.GetItem<Usuario>(serviceNameUserInfo, list);
if (userInfo == null)
{
return Json(false);
}
else
{
CultureInfo cult = new CultureInfo("pt-BR");
String dataStr = userInfo.DTH_ULTIMO_ACESSO.ToString("dd/MM/yyyy HH:mm:ss", cult);
HttpCookie cook = new HttpCookie("UserInfo");
cook["cpfCnpj"] = userInfo.NUM_CPF_CNPJ_CLIENTE.ToString();
cook["nomeCompleto"] = userInfo.NOM_CLIENTE;
cook["dataAcesso"] = dataStr;
cook["email"] = userInfo.END_EMAIL;
cook.Expires = DateTime.Now.AddHours(4);
Response.Cookies.Add(cook);
//cookie de autenticacao
FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(
1,
cpf, // Id do usuário é muito importante
DateTime.Now,
DateTime.Now.AddHours(4),
true, // Se você deixar true, o cookie ficará no PC do usuário
"");
HttpCookie cookieAuth = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(authTicket));
Response.Cookies.Add(cookieAuth);
}
Response.Redirect("~/ProjetoEletrico/Index");
return Json(true);
}
I figure it out. It was a stupid mistake....
I forgot the "submit" in my form button and I also the ajax call.

Wordpress Modification To A Five-Star Rating Script

I have added custom javascript code to the header.php file of my wordpress site. I have tested this code on a basic html file and it works fine, but I cannot seem to make the vote recording function work on a wordpress post. The other components of the script are working fine (hover, vote display from a .txt file), but I cannot get the function to record the vote working. All files have read/write access.
I would greatly appreciate it if anyone could assist me or point me in the right direction to solve this.
Here is the part of the script that records the vote, I am fairly new to php and was wondering if there is something I can add/replace to modify so the code so it will work properly on Wordpress.
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
Here is a visual example for reference
Thank you for taking time to look at this, if there is any additional information that I can provide please let me know.
Here is the ratings.php that was mentioned in the script that was placed in the header.php.
ratings.php:
<?php
$rating = new ratings($_POST['widget_id']);
isset($_POST['fetch']) ? $rating->get_ratings() : $rating->vote();
class ratings {
var $data_file = 'http://localhost/url/wordpress/wp-content/ratings.data.txt';
private $widget_id;
private $data = array();
function __construct($wid) {
$this->widget_id = $wid;
$all = file_get_contents($this->data_file);
if($all) {
$this->data = unserialize($all);
}
}
public function get_ratings() {
if($this->data[$this->widget_id]) {
echo json_encode($this->data[$this->widget_id]);
}
else {
$data['widget_id'] = $this->widget_id;
$data['number_votes'] = 0;
$data['total_points'] = 0;
$data['dec_avg'] = 0;
$data['whole_avg'] = 0;
echo json_encode($data);
}
}
public function vote() {
preg_match('/star_([1-5]{1})/', $_POST['clicked_on'], $match);
$vote = $match[1];
$ID = $this->widget_id;
if($this->data[$ID]) {
$this->data[$ID]['number_votes'] += 1;
$this->data[$ID]['total_points'] += $vote;
}
else {
$this->data[$ID]['number_votes'] = 1;
$this->data[$ID]['total_points'] = $vote;
}
$this->data[$ID]['dec_avg'] = round( $this->data[$ID]['total_points'] / $this->data[$ID]['number_votes'], 1 );
$this->data[$ID]['whole_avg'] = round( $this->data[$ID]['dec_avg'] );
file_put_contents($this->data_file, serialize($this->data));
$this->get_ratings();
}
}
?>
Here is the complete javascript code added to the header.php, the mouseover/mouseout seem to be working properly, so I think the javascript should be running.
Javascript added to header.php:
<?php wp_head(); ?>
<script type="text/javascript">
$(document).ready(function() {
$('.rate_widget').each(function(i) {
var widget = this;
var out_data = {
widget_id : $(widget).attr('id'),
fetch: 1
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
out_data,
function(INFO) {
$(widget).data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
$('.ratings_stars').hover(
function() {
$(this).prevAll().andSelf().addClass('ratings_over');
$(this).nextAll().removeClass('ratings_vote');
},
function() {
$(this).prevAll().andSelf().removeClass('ratings_over');
set_votes($(this).parent());
}
);
$('.ratings_stars').bind('click', function() {
var star = this;
var widget = $(this).parent();
var clicked_data = {
clicked_on : $(star).attr('class'),
widget_id : $(star).parent().attr('id')
};
$.post(
'http://localhost/url/wordpress/wp-content/ratings.php',
clicked_data,
function(INFO) {
widget.data( 'fsr', INFO );
set_votes(widget);
},
'json'
);
});
});
function set_votes(widget) {
var avg = $(widget).data('fsr').whole_avg;
var votes = $(widget).data('fsr').number_votes;
var exact = $(widget).data('fsr').dec_avg;
window.console && console.log('and now in set_votes, it thinks the fsr is ' + $(widget).data('fsr').number_votes);
$(widget).find('.star_' + avg).prevAll().andSelf().addClass('ratings_vote');
$(widget).find('.star_' + avg).nextAll().removeClass('ratings_vote');
$(widget).find('.total_votes').text( votes + ' votes recorded (' + exact + ' rating)' );
}
</script>
To solve this all I had to do was place my ratings.php file and ratings.data.txt within my wordpress theme folder and link the custom javascript to these files within my header.php file. The javascript now operates properly. This is not the proper way to do this though, ideally I should use the wp_enqueue_scripts hook in the header.php and have the custom css and js in the css/js folders. But for now this temporary fix works and I can continue experimenting.

Object [object Object] has no method 'set'

I'm using Kendo UI Mobile via Icenium Extension for Visual Studio. I'm very new at this, but I'm stumbling along. I've written a method (called popDataSource) in a view that gets some data (reads the names of files in a folder) and returns those file names. The method works perfectly if I wire it up to a button click event, but what I really want is for the method to be called when the page first loads. I've tried setting data-show=popDataSource and even data-after-show=popDataSource, but when I do that I get the error Object [object Object] has no method 'set' when I try to return the data. I'm also not that well versed in javascript, which I'm sure isn't helping me any.
Here's my code:
Snippet from index.html:
<div id="tabstrip-listSonicImages" data-role="view" data-title="Sonic Images List" data-model="app.listSonicImagesService.viewModel"
data-after-show="app.listSonicImagesService.viewModel.popDataSource">    
<div data-role="content" class="view-content">
<div data-role="scroller">
<div class="buttonArea">
<a id="btnShowList" data-role="button" data-bind="click: popDataSource"
class="login-button">Display List</a>
</div>
<ul class="forecast-list" data-role="listview" data-bind="source: sonicImagesDataSource" data-template="sonic-image-list-template">
</ul>
</div>
</div>
</div>
<script type="text/x-kendo-tmpl" id="sonic-image-list-template">
<a data-role="listview-link" href="\#tabstrip-playSonicImage?fileName=${fileName}">${fileName}</a>
</script>
listiconimages.js
(function(global) {
var SonicImageListViewModel,
app = global.app = global.app || {};
SonicImageListViewModel = kendo.data.ObservableObject.extend({
popDataSource: function () {
var that = this;
var listSI = new Array();
try{
window.requestFileSystem(LocalFileSystem.PERSISTENT, 0,
function (fileSys) {
fileSys.root.getDirectory("SIData", { create: true, exclusive: false},
function (dataDirEntry) {
var directoryReader = dataDirEntry.createReader ();
directoryReader.readEntries(
function (entries) {
var rows = entries.length;
for (i = 0; i < rows; i++) {
var fName = entries[i].name;
listSI[i] = { "fileName": fName, "image": "xxx" };
}
},
function (error) {
alert("error: " + error.code);
}
);
},
null);
},
null
);
var dataSource = new kendo.data.DataSource(
{
data: listSI,
filter: { field: "fileName", operator: "endswith", value: ".simg" }
}
);
that.set("sonicImagesDataSource", dataSource);
} catch (ex) {
alert(ex.message);
}
}
});
app.listSonicImagesService = {
viewModel: new SonicImageListViewModel()
};
}
)(window);
app.js
(function (global) {
var mobileSkin = "",
app = global.app = global.app || {};
document.addEventListener("deviceready", function () {
app.application = new kendo.mobile.Application(document.body, { layout: "tabstrip-layout" });
}, false);
app.changeSkin = function (e) {
if (e.sender.element.text() === "Flat") {
e.sender.element.text("Native");
mobileSkin = "flat";
}
else {
e.sender.element.text("Flat");
mobileSkin = "";
}
app.application.skin(mobileSkin);
};
})(window)
As I said, I'm new to Icenium and Kendo, and my javascript knowledge is limited, so I'm not quite sure where the answer lies. Any help would be greatly appreciated.
Thanks

Categories

Resources