I have this code on my html page:
<span data-miid="{{ orden._id }}"
data-fetxa="{{orden.fetxa}}"
data-linea="1"
ng-mouseenter="arraton(orden.ref);"
ng-click="grafikoa(orden.ref);"
ng-if="isadmin"
ng-bind-html="orden.ref"
>{{orden.ref}}</span>
And this is the angular part:
$scope.arraton = function(val) {
if ( ( val === "" ) || ( val === undefined ) ) { return false; }
var of="";
val = val.replace("<BR>", "<br>");
val = val.replace("<BR />", "<br>");
val = val.replace("<br />", "<br>");
if (val === undefined) {
return false
}
var n = val.indexOf("<br>");
if (n > 0) {
var miarray = val.split('<br>');
of = miarray[1];
}
var url = "SOMEURL/delaoferta?of="+of;
$http.get(url)
.success(function (data) {
$scope.arraton = "A Frabricar: " + parseInt(data.QFabricar)
+ "<br />Iniciada: " + parseInt(data.QIniciada)
+ "<br />Fabricada: " + parseInt(data.QFabricada);
})
.error(function () {
console.log("error al obtener datos");
return;
});
}
The fact is that when I mouse over the span, the first time works fine, but then, I´m getting
TypeError: string is not a function
all the time a mouse over the span.
Any help or clue?
thx
The problem is the success of yout $http request, your setting an string when your ng-mouseenter need a function. Change a variable name and you are done.
Related
I have the following piece of code to retrieve a Wikipedia infobox:
function foo() {
var searchTerm = "Something...";
var bnameonly = "Something else...";
var url = "https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm + "&redirects&prop=text&callback=?";
$.getJSON(url, function(data) {
if (typeof(data.parse) !== 'undefined') {
wikiHTML = data.parse.text["*"];
$wikiDOM = $("<table>" + wikiHTML + "</table>");
infobox = $wikiDOM.filter('.infobox.biota');
$("#wiki").contents().find('#myinfobox').html(infobox);
} else {
var url = "https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + bnameonly + "&redirects&prop=text&callback=?";
$.getJSON(url, function(data) {
if (typeof(data.parse) !== 'undefined') {
wikiHTML = data.parse.text["*"];
$wikiDOM = $("<table>" + wikiHTML + "</table>");
infobox = $wikiDOM.filter('.infobox.biota');
$("#wiki").contents().find('#myinfobox').html(infobox);
}
});
}
});
}
However, if the first query fails (detected by typeof(data.parse) == 'undefined' being true) then the else clause should be executed. The problem is that the bnameonly variable is undefined at that point even when it has been declared in the parent environment.
You can only check to see if the HTML is empty after you know the response has come back from the server (regardless of if it succeeded or failed). You can use jQuery's always method on it's jqXHR to test for this.
function foo() {
var searchTerm = "Something...";
var bnameonly = "Something else...";
function myCallback(data) {
...
}
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm + "&redirects&prop=text&callback=?";
$.getJSON(url,{data})
.done(myCallback)
.always(function() {
//executed only after $.getJSON succeeds or fails
if ($("#wiki").contents().find('#myinfobox').html() === '') {
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + bnameonly + "&redirects&prop=text&callback=?";
$.getJSON(url, {data}, myCallback);
}
})
}
based on the answers I've found in this other forum (https://forum.jquery.com/topic/how-do-i-access-json-data-outside-of-getjson), I've found a solution by using a callback function:
function foo() {
var searchTerm = "Something...";
var bnameonly = "Something else...";
function myCallback(data) {
if (typeof(data.parse) !== 'undefined') {
wikiHTML = data.parse.text["*"];
$wikiDOM = $("<table>"+wikiHTML+"</table>");
infobox = $wikiDOM.filter('.infobox.biota');
$("#wiki").contents().find('#myinfobox').html(infobox);
} else {
$("#wiki").contents().find('#myinfobox').html('');
}
}
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + searchTerm + "&redirects&prop=text&callback=?";
$.getJSON(url, {data}, myCallback);
if ($("#wiki").contents().find('#myinfobox').html() === '') {
var url="https://en.wikipedia.org/w/api.php?action=parse&format=json&page=" + bnameonly + "&redirects&prop=text&callback=?";
$.getJSON(url, {data}, myCallback);
}
}
I am trying to use while loop in Angular.
If I use alert in while loop, it give same quantity output. but I remove alert, the quantity is different. So what is wrong in my code.
var quantity= $scope.quantity;
var i=0;
while(i< quantity)
{
order.createOrderLineItem( localStorage.getItem( "orderID" ), itemStr, undefined, $scope.errorCallback )
.success(function(data){
$scope.lineItemID = data.id;
alert("i:"+i);
var orderLineItemData = {};
if( $scope.cusNote == "" )
{
var existedNote = data.note || "";
orderLineItemData = {
"unitQty": $scope.quantity,
"note": existedNote,
};
//if adding taxRates 0, clover will returns error
if($scope.taxRates !== 0) {
orderLineItemData.taxRates = $scope.taxRates;
}
}
else
{
var customerNote = "";
if( data.note != undefined && data.note != null ) customerNote = data.note;
customerNote = customerNote + "#order-request-[";
customerNote = customerNote + $scope.cusNote;
customerNote = customerNote + "]";
customerNote = customerNote.replace(/\\/g, '\\\\');
customerNote = customerNote.replace(/\"/g, '\\"');
console.log( "customerNote:" + customerNote );
orderLineItemData = {
"unitQty":$scope.quantity,
"note": customerNote,
"taxRates": $scope.taxRates
}
}
order.updateOrderLineItem( localStorage.getItem( "orderID" ), $scope.lineItemID, JSON.stringify(orderLineItemData), undefined, $scope.errorCallback )
.success( function( data ){
if( $scope.modCount == 0 )
{
location.href = "/" + $routeParams.slug;
}
$scope.addModifierItem( $scope.lineItemID );
});
});
i++;
}
So how can I correct this code?
I am not sure but, alert may be the reason of that. Can you try to use console.log("i:"+i); instead of the alert. Browser may interrupt when you use alert because of the pop up.
--Edited--
this is the service that you will need to implement into your application. You will need to notify this service at your success and it will trigger any observe that is implemented after the notify
app.service('checkService',['$q',function($q){
var checkRequest = $q.defer();
this.notifyRequestIsDone= function(){
checkRequest .notify();
};
this.observeRequestStatus = function(){
return checkRequest .promise;
};
}]);
Here is observe example of the code above add this to your controller where you need to increase your value after the request is done
checkService.observeRequestStatus ().then(null,null,function(){
//... Your code
});
I have created this controller for for getting existing value by searching id. this is my controller for searching data by id. this code is running well but result is not acceptable. i am new in jquery that's why i am explaining this very helpfully..
public string Search(string id=null)
{
string[] ci = new string[9];
//return "Artistry";
string cn = null;
cn = Request.QueryString["id"];
if (cn != null)
{
ClientInfo c = db.SingleOrDefault<ClientInfo>("where CId='" + cn + "'");
if (c != null)
{
// ci[0] = c.CId.ToString();
ci[1] = c.CName;
ci[2] = c.CCName;
ci[3] = c.PhoneNo.ToString();
ci[4] = c.Fax;
ci[5] = c.Email;
ci[6] = c.Address;
ci[7] = c.PostalCode.ToString();
ci[8] = c.Country;
return ci[5];
}
else
return null;
}
else
return null;
//*/
}
My view page script for showing my data..
<script type="text/javascript">
$(document).ready(function () {
$('#CId').blur(function () {
var v = $('#CId').val();
var url = "/Clients/Search/" + v;
// alert("Test : " + url);
$.get(url, function (data, status) {
$("#CName").val(1);
$("#CCName").val(2);
$("#PhoneNo").val(3);
$("#Fax").val(4);
$("#Email").val(5);
$("#Address").val(6);
$("#PostalCode").val(7);
$("#Country").val(8);
alert("Test : " + data + " Status :" + status);
});
});
});
</script>
And finally my sql server database for showing data in views are..
SELECT TOP 1000 [CId]
,[CName]
,[CCName]
,[PhoneNo]
,[Fax]
,[Email]
,[Address]
,[PostalCode]
,[Country]
FROM [test].[dbo].[ClientInfo]
I think you should return json type data like so:
public JsonResult Search(string id=null)
{
// view code
return Json(new {info=ci[5]});
}
And client code:
$.get(url, function (data, status) {
alert("Test : " + data.info + " Status :" + status);
});
I'm having trouble uploading a file using a Javascript function that makes an Ajax call to a servlet. The file is uploaded perfectly when I use chrome, but not when I use IE8 (Go figure).
I used to have a file select button on the bottom of my form. When I clicked that button a function would be called and it would upload the file to the servlet using ajax. This worked perfectly in IE8, but the client wanted links instead. So now I have the links in the form, and the buttons hidden with css. The links call the click event of the buttons. Now the file uploading only works with Chrome, and not IE8.
The request never makes it to the servlet for some reason, and for some reason the ajax request returns success. Any idea what the problem might be?
Here is my code:
//Uploading a file
$("#uploaded_file").change(function() {
var filename = $(this).val();
if(isAcceptable(filename)) {
$.ajaxFileUpload
(
{
type: "POST",
url:'GenerateServlet',
secureuri:false,
fileElementId:'uploaded_file',
dataType: 'json',
success: function (data, status)
{
if(typeof(data.error) != 'undefined')
{
if(data.error != '')
{
alert(data.error);
}else
{
alert(data.msg);
}
}
fillTemplate(data);
}
}
)
}
else if(filename.length > 0){
$("#uploaded_file").val("");
alert("Invalid File! Please select another file")
}
});
$("#upload_link").click(function() {
document.getElementById('uploaded_file').click();
return false;
});
Here is the upload function:
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
if(window.ActiveXObject)
{
if(typeof uri== 'boolean'){
iframeHtml += ' src="' + 'javascript:false' + '"';
}
else if(typeof uri== 'string'){
iframeHtml += ' src="' + uri + '"';
}
}
iframeHtml += ' />';
jQuery(iframeHtml).appendTo(document.body);
return jQuery('#' + frameId).get(0);
},
createUploadForm: function(id, fileElementId, data)
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
if(data)
{
for(var i in data)
{
jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = new Date().getTime()
var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
Console.log(form);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ )
{
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {}
if ( s.global )
jQuery.event.trigger("ajaxSend", [xml, s]);
// Wait for a response to come back
var uploadCallback = function(isTimeout)
{
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if ( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if ( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
// If a local callback was specified, fire it and pass it the data
if ( s.success )
s.success( data, status );
// Fire the global callback
if( s.global )
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
} else
jQuery.handleError(s, xml, status);
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
}
// The request was completed
if( s.global )
jQuery.event.trigger( "ajaxComplete", [xml, s] );
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active )
jQuery.event.trigger( "ajaxStop" );
// Process result
if ( s.complete )
s.complete(xml, status);
jQuery(io).unbind()
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100)
xml = null
}
}
// Timeout checker
if ( s.timeout > 0 )
{
setTimeout(function(){
// Check to see if the request is still happening
if( !requestDone ) uploadCallback( "timeout" );
}, s.timeout);
}
try
{
var form = jQuery('#' + formId);
jQuery(form).attr('action', s.url);
jQuery(form).attr('method', 'POST');
jQuery(form).attr('target', frameId);
if(form.encoding)
{
jQuery(form).attr('encoding', 'multipart/form-data');
}
else
{
jQuery(form).attr('enctype', 'multipart/form-data');
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
jQuery('#' + frameId).load(uploadCallback );
return {abort: function () {}};
},
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
eval( "data = " + data );
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
return data;
}
})
That is a typical Microsoft security measure (e.g. to stop automated uploads).
That means you have to originate an upload from an actual user-pressed button click.
Style the button to make it look like a link instead.
I'm working with MarkDownDeep. It has a similar "insert image" function like SO does.
I'd like to extend this function to use a bootstrap modal that would allow the user to upload their own images or at least get a typeahead working so that a user could pick something uploaded from another page.
I've tried to use a callback function in replace of the the prompt below but it doesn't insert str into the textbox like the original function.
pub.cmd_img = function (ctx) {
ctx.TrimSelection();
if (!ctx.CheckSimpleSelection())
return false;
imagePopUp(function(results) {
$("#" + ctx.m_textarea.id).focus();
var url = results;
if (url === null)
return false;
var alttext = ctx.getSelectedText();
if (alttext.length == 0) {
alttext = "Image Text";
}
var str = "![" + alttext + "](" + url + ")";
ctx.ReplaceSelection(str);
ctx.m_selectionStart += 2;
ctx.m_selectionEnd = ctx.m_selectionStart + alttext.length;
return true;
});
return false;
uploadImageUrl is a holding variable because at the moment I'm using an iframe inside the modal so the user can upload, the iframe then sets parent.uploadImageUrl
uploadImageUrl = "baz";
function imagePopUp(callback) {
$('#imageUpload').modal('show');
$('#confirmTrue').click(function () {
$('#imageUpload').modal('hide');
if (callback) callback(uploadImageUrl);
});
}
Original
pub.cmd_img = function (ctx) {
ctx.TrimSelection();
if (!ctx.CheckSimpleSelection())
return false;
var url = prompt("Enter the image URL"); //need to change what this does
if (url === null)
return false;
var alttext = ctx.getSelectedText();
if (alttext.length == 0) {
alttext = "Image Text";
}
var str = "![" + alttext + "](" + url + ")";
ctx.ReplaceSelection(str);
ctx.m_selectionStart += 2;
ctx.m_selectionEnd = ctx.m_selectionStart + alttext.length;
return true;
};
You can see my none-working fiddle
This should do the trick:
pub.cmd_img = function(ctx){
ctx.TrimSelection();
if (!ctx.CheckSimpleSelection())
return false;
//call popup
imagePopUp(function(results){
$("#" + ctx.m_textarea.id).focus();
var url = results;
if (url === null)
return false;
var alttext = ctx.getSelectedText();
if (alttext.length == 0){
alttext = "Image Text";
}
var str = "![" + alttext + "](" + url + ")";
var editor = $(ctx.m_textarea).data("mdd");
editor.cmd_img_core = function(state){
state.ReplaceSelection(str);
state.m_selectionStart += 2;
state.m_selectionEnd = state.m_selectionStart + alttext.length;
return true;
};
editor.InvokeCommand("img_core");
delete editor.cmd_img_core;
});
return false;
};
I had some issues with this code, in that when I tried to insert a second image into the editor it would insert the URL twice, and the third image three times and so on. It seemed to be running the imagePopup callback the same number of times as the number of images inserted. I resolved the issue with the following changes. Not perfect but it works:
var isImageInserted = false;
pub.cmd_img = function (ctx) {
ctx.TrimSelection();
if (!ctx.CheckSimpleSelection())
return false;
isImageInserted = false;
//call popup
imagePopUp(function (results) {
$("#" + ctx.m_textarea.id).focus();
var url = results;
if (url === null)
return false;
var alttext = ctx.getSelectedText();
if (alttext.length == 0) {
alttext = "Image Text";
}
var str = "";
if (!alttext.indexOf(url) > -1) {
str = "![" + alttext + "](" + url + ")";
} else {
str = alttext;
}
var editor = $(ctx.m_textarea).data("mdd");
if (!isImageInserted) {
editor.cmd_img_core = function (state) {
state.ReplaceSelection(str);
state.m_selectionStart += 2;
state.m_selectionEnd = state.m_selectionStart + alttext.length;
isImageInserted = true;
return true;
};
editor.InvokeCommand("img_core");
delete editor.cmd_img_core;
}
});
return false;
}
hope this helps someone else as pretty much every markdowndeep search seems to come here.