js file cant use jquery - javascript

I have a weird bug where I include this files in my section
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="js/barScriptOOP.js"></script>
in the barScriptOOP.js I have this
function position_bar(){
//global variable
this.sizes = Array();
}
//class methods => getData (from xml file), draw(draws the bar )
position_bar.prototype ={
getData: function(is_load){
var xmlData = Array();
$.ajax({
type: "GET",
url: "Bar.xml",
dataType: "xml",
context: this,
success: function(xml) {
//extracting new data - some code here
xmldata = "blabla";
this.draw(is_load, xmlData);
}
})//end ajax
},
//other functions
when I use this script, I get a '$.ajax is not a function' error.
1. I tried editing out this.draw(is_load, xmlData); and it didn't errored me.
my programs rpeatly calls the getData function.
note: I also get a '$.browser is undefined' error which is in the other function(this is the first error I get).
meaning ==> the going to another function unables jquery.
any idead what is going on here?

Instead of using $ as your jquery reference, try putting this line at the start of your script
var $j = jQuery.noConflict();
$j(function() {
alert('doc ready');
});
(also, it's strange that your script tag doesn't have a type attribute set, though I doubt that's the issue)

Related

Function Statements no name error

I have the following code:
<script type="text/javascript">
$(document).on("click", "#leftconversation", function(){
var self = this;
var cid = $(this).attr('class'); // getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
$("#right").html(data); // replace the right div with echoed content from php file
});
});
</script>
However, my console keeps giving me the error: “SyntaxError: Function statements must have a name.”
I can't seem to fix the issue and that’s why the AJAX code isn’t running. Where’s this error coming from?
As per what Todd said, i changed the code to following:
<script type="text/javascript">
$(document).on("click", "#leftconversation", function(){
var self = this;
var cid = $(this).attr('class'); //you are getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
self.html("Loading please wait...");
},
success: function(data) {
$("#right").html(data);
},
error: function(request, err){ console.log('An Error Occured' + err); }
});
});
</script>
It fixed the first error, but now its telling me TypeError: undefined is not a function (evaluating 'self.html("Loading please wait...")')
This is fixed, should have used var self = $(this); instead
as per my comment
$(document).on("click", "#leftconversation", function(){
var $self = $(this);
var cid = $(this).attr('class'); // getting the user id here
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: cid },
beforeSend: function(){
$self.html("Loading please wait...");
}
});
//WHEN SUCCESS
request.success(function( data ) {
$("#right").html(data); // replace the right div with echoed content from php file
});
});
You can fix your issue without having to use a variable. Just set the context: property of the $.ajax call.
var request = $.ajax({
url: "conversation.php",
type: "POST",
data: { cid: this.className }, // Quicker way to get the class.
context: $(this), // The context in the callback will be the jQuery object.
beforeSend: function() {
// v-- This is now a jQuery object.
this.html("Loading please wait...");
}
});
Your code, as you have posted it, is correct. The error must be coming from elsewhere. That said, wherever the error is, here’s what to look for:
As you likely know, functions can be defined like this:
function greet(name) { /* ... */ }
This works in a statement context. Functions can also be used in an expression context:
[1, 2, 3].forEach(function(item) { alert(item); });
In an expression context, we can omit the name, as we did above, or we can include a name:
[1, 2, 3].forEach(function foo(item) { alert(item); });
However, what we cannot do is have a standalone function declaration without a name. This is an error:
function(name) { /* ... */ }
That is what your (now first) problem was.
“undefined is not a function”
Your updated code has a different problem. When you set self = this, this is a DOM element, not a jQuery object. You later try to use self.html, but DOM elements do not have a html property. If you wish to use jQuery methods, you must convert the element into a jQuery object, either at the point of assignment (self = $(this)) or at the point of use $(self).html.

Read local file text (tab separated values) with d3 or ajax cause syntax error in firefox development console

The reading works.
However I got a syntax error in the firefox console (which is tiresome when I read 30 files).
The files are annotation files like (time \t value) with no headers like :
0.0 5.2
0.5 5.6
1.0 6.3
...
This is the ajax code :
function getdatafromfile(filename) {
// Read annotation file. Example : %timeinstant \t %value \n
// Return an array of string
var arraydata
$.ajax({
type: "GET",
url: filename,
dataType: "text",
async: false,
success: function(csv) {arraydata = $.csv.toArrays(csv,{separator:'\t'}); }
});
return arraydata}
And with d3:
d3.text(filename, function(text) {
var data = d3.tsv.parseRows(text).map(function(row) {
return row.map(function(value) {
return +value;
});
});
console.log(data);
});
}
It seems that I could use one of those code, but I got a syntax error in both cases (with firefox 33.1).
A file reader could work like the code below.
In the example I've added a flag to use the content of the variable instead of a file. That's just for the demo and can be removed. The same code is here as jsFiddle.
Maybe you could add some validation before or after the $.csv method. So you know that the file was a csv/tsv file.
If you need to open the file with-out user interaction, you have to look for something different because JS is not allowed to open a file with-out the user choosing the file (security concerns, see this SO question).
You could add your data to a database and read it from there. e.g. Firebase or MongoDB or use a JSON file. The code of my other answer should work for a JSON file that you host with your webpage.
var demoTxt = "0.0 5.2\
0.5 5.6\
1.0 6.3";
var flag_usedemofile = true; //if true var demoTxt will be used
function doOpen(evt) {
var files = evt.target.files,
reader = new FileReader();
reader.onload = function() {
if ( !flag_usedemofile) {
var arraydata = $.csv.toArrays(this.result,{separator:' '});
showout.value = arraydata; //this.result;
} else {
var arraydata = $.csv.toArrays(demoTxt,{separator:' '});
showout.value = arraydata;
console.log(arraydata);
}
};
reader.readAsText(files[0]);
}
var openbtn = document.getElementById("openselect"),
showout = document.getElementById("showresult");
openselect.addEventListener("change", doOpen, false);
#showresult {
width:98%;
height: 300px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://cdnjs.cloudflare.com/ajax/libs/jquery-csv/0.71/jquery.csv-0.71.min.js"></script>
<input type="file" id="openselect" />
<textarea id="showresult"></textarea>
I'm not exactly sure what syntax error you are getting. But I think the error have something to do with the mime type of your json request.
I think the best way is to wrap your data in json and then use JSONP. (I have also tried to get it working with text/plain, but with-out success.)
Please check the following example for details. You can also find the same example on
jsFiddle.
(function ($) {
var url = 'http://www.mocky.io/v2/547c5e31501c337b019a63b0'; // dummy url
var jsonCallback = function (csv) {
var arraydata;
console.log(data);
$('#data').html(JSON.stringify(csv, null, 2));
arraydata = $.csv.toArrays(csv.data,{separator:'\t'});
console.log(arraydata);
};
$.ajax({
type: 'GET',
url: url,
contentType: "application/json",
dataType: 'jsonp'
}).done(jsonCallback)
.fail(function (xhr) {
alert("error" + xhr.responseText);
});
})(jQuery);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<pre id='data'></pre>

Ajax Call inside JavaScripts using Yii Framework

I am trying to use ajax function inside javascript, but its not calling its goes to failure part,
JS code :
Yii::app()->clientScript->registerScript('my-event-listener',"
$('#dedup_id').change(function(data){
$.ajax({
type: 'POST',
url: '".$this->createUrl('CheckDedupField')."',
data: {crm_base_contact_id:1652},
success: function(msg){
alert('Sucess')
},
error: function(){
alert('failure');
}
});
});
");
My controller code :
public function actionCheckDedupField($id)
{
echo "Inside CheckDedup".var_dump($_POST);
}
Please anyone find out what mistake am doing here.
You have to call ajax url as
url: '".$this->createUrl('checkDedupField')."', // change C to c
In URL, controller function names will start with lower case.
as per the comment. you are calling controller function with wrong name.
Then For missing parameter, change as
data: {id:1652},

Reading a file into a string in jQuery/JS

The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.

Adding javascripts functions dynamically in mvc3

I'm creating a dynamic-form infrastructure. This infrastructure will get a certain XML which will include all of the form data, from the order in the page to validators.
The dynamic page may also contain fields which will require some sort of validation. The validation is not only trivial (such as "numeric"\"alphanumeric"), it might be something more complicated.
That's why I want to pass in my XML the validators javascripts.
When developing on traditional Web Application, it's simple to plant this code in the page header. But I don't know how to do so when using MVC3, since it's not a normal client-server application.
It's important to explain - in my controller, I pass this dynamic-form class the xml file, it does all it should, and in the end, I plant the result in ViewBag.table.
Anyone know how can I can plant the javascript code from the controller to view header?
EDIT:
I tried thw following:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("SetJScript", "MyPages")',
type: 'POST',
success: function (result) {
var myscript = document.createElement('script');
myscript.setAttribute('type', 'text/javascript');
myscript.innerHTML = '$( document ).ready( function ( e ){' + result + '});';
document.getElementsByTagName('head').item(0).appendChild(myscript);
}
});
and also:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("SetJScript", "MyPages")',
type: 'POST',
success: function (result) {
var myscript = document.createElement('script');
myscript.setAttribute('type', 'text/javascript');
myscript.innerHTML = "function test() {alert('aa');}";
document.getElementsByTagName('head').item(0).appendChild(myscript);
}
});
or change the:
myscript.innerHTML = "function test() {alert('aa');}";
to:
myscript.innerHTML += "function test() {alert('aa');}";
so it will be added to the existing "$documnet.ready" function.
None of it worked.
I kept getting "Unknown error"
Thank you all.
Hope it helps..
$(document).ready(function () {
$.ajax(
{ url: '#Url.Action("SetJScript", "MyPages")',
type: 'POST',
success: function(result)
{ var myscript = document.createElement('script');
myscript.setAttribute('type','text/javascript');
myscript.innerHTML = 'function test() {alert("aa");}';
document.getElementsByTagName('head').item(0).appendChild(myscript);
} //end of success
});
});

Categories