$ not defined ajax request in javascript - javascript

I am trying to send a php file some values using ajax but in the call for ajax I am getting the following error
Uncaught ReferenceError: $ is not defined
at the beginning line for the ajax request as follows:
$.ajax({
type: "POST",
url: 'program3.php',
data: {
player1name: player1name.value,
player2name: player2name.value,
playtopoints: playtopoints.value,
delay: delay.value,
numgames: numgames.value,
gamesplayed: gamesplayed.value,
p1turn: p1turn.value,
p2turn: p2turn.value,
p1total: p1total.value,
p2total: p2total.value
},
success: function (data) {
rolling = data;
}
});
I first thought that it might need the refrence to ajax so i added the following line before the javascript on the html page:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
but i am still getting the erro can anyone offer any insight?
Also i have the data variables all defined as follow:
var player1name = document.JForm.p1name.innerHTML;
is that the correct way to assign them?

The src on your script tag is invalid—at least if you're not running this from http or https. Replace
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
with
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

You are probably accessing the file locally, which won't work with a protocol-relative script tag.
<!-- access from http resolves to this -->
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- local access resolves to this -->
<script src="file://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
The file wouldn't have existed locally, and the script would've never been loaded. Therefore, the variable $ would then be undefined.

Related

Get document information where ajax is loaded

This might not be a well formulated question, what I need is the metadata from the document where the script is begin executed not from where the data is extracted...
We have foo.com/some_title_article.html
inside of it, we have an script
<script>
(function($) {
$(document).ready(function(){
var id = data.qids;
var theTime = new Date().getTime();
$.ajax({
url: "http://foo.com/apis/shares/api.php?ids="+id+"&time="+theTime
}).done(function(data) {
$('#showData').html(data); // This will show a basic html form...
});
});
})(jQuery);
</script>
inside the file api.php I call a few other java scripts that are related to where that file is stored, as it is right now is working fine, but what I need is to get metadata from some_title_article.html into my other java scripts that is loaded via ajax... sortof like var currentURL = window.location.href; which is declared inside and a java script inside the api.php file, it load the full url as foo.com/some_title_article.html and not foo.com/apis/shares/api.php ...get it?., So, how can get information from the url where the ajax is executed and pass it to the other scripts that are called after the ajax script...
Does this help:
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.0.min.js"></script>
<div id="showData"></div>
<script type="text/javascript">
$.ajax({
url: "http://foo.com/apis/shares/api.php?ids="+id+"&time="+theTime
}).done(function(data) {
var content = data.content;
var metadata = data.metadata;
$('#showData').html(content); // This will show a basic html form...
//Then, do whatever you want to with metadata
});
</script>
You make api.php return an object where the first key is the content and the second key is the meta data.
Otherwise, if api.php returns a string that already contains meta tags in it, you would need to parse them or add them to the dom and access them that way.
Can you share a sample of what is returned by api.php?

JSON to xml conversion using jQuery javascript

I'm new to Javascript and jQuery and I want to create a function to convert JSON to XML. I searched through the internet and the only one I got is http://code.google.com/p/x2js/
Below is the function I wrote and it does not work.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='https://code.jquery.com/jquery-git.js'></script>
<script type='text/javascript' src="x2js-v1.1.5/xml2json.min.js"></script>
<script type='text/javascript'>
$(window).load(function(){
var json = null;
var x2js=newX2JS();
$.ajax({
'async': false,
'global': false,
'url': "sample.json",
'dataType': "json",
'success': function (data) {
json = data;
}
});
function convertJsonToXml(){
var xmlDOM=x2js.json2xml(json);}
});
</script>
</head>
</html>
The json file I want to read is "sample.json". It is at the same directory as the html file.
Someone please help me to make this work.
This is the error I'm having in the console
TypeError: url.indexOf is not a function jquery-git.js:9217:8
The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol.
jQuery is trying to use the Ajax load method instead of binding a load event handler. The function you are passing isn't a URL string so it errors.
You want:
$(window).on('load', function(){
instead.
Try if this works. In this way you will be able to locate the problem.
$(window).load(function(){
var json = {'a': 'b'};
var x2js=new X2JS().json2xml(json);
}

jQuery.getJSON() Not working

I'm trying to get JSON array from my php-script. Following is my Jquery code written in my jsp file-
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://example.com/root_dir/test_json.php', function(data)
{
alert(data);
});
});
but, above code showing only outer alert (i.e. alert("Inside Ready");) and not showing inner alert (i.e. alert(data); ). I'm getting expected json when I hit URL in browser. So definitly there is no problem in URL and php-script.
following is test_json.php
<?php
//Create an array
$json_response = array();
$row_array['label'] = 'A';
$row_array['value'] = $row['0 to 2'];
$row_array['color'] = '#FA2020';
array_push($json_response,$row_array);
$row_array['label'] = 'B';
$row_array['value'] = $row['2 to 3'];
$row_array['color'] = '#2BD95A';
array_push($json_response,$row_array);
$row_array['label'] = 'C';
$row_array['value'] = $row['above 3'];
$row_array['color'] = '#F7F739';
//push the values in the array
array_push($json_response,$row_array);
echo json_encode($json_response);
?>
Getting following json when I hit URL in browser-
[{"label":"A","value":"19","color":"#FA2020"},{"label":"B","value":"1","color":"#2BD95A"},{"label":"C","value":"2","color":"#F7F739"}]
I'm using jquery-1.10.2.js. Thank You..!
Try This one...Hope so it is useful to you
$(document).ready(function()
{
$.ajax({
type:'POST',
url:'http://example.com/root_dir/test_json.php',
dataType:'JSON',
data:{
},
success:function(data1){
alert(data)
},
error:function(XMLHttpRequest,textStatus,errorThrown){
alert("error");
}
});
});
Your code seems to be working fine -
I just created a test page with your code and it works -
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
alert("Inside Ready");
$.getJSON('http://<<CHANGE SERVER NAME>>/zz-test/get_json.php', function(data)
{
alert(data);
});
});
</script>
</head>
<body>
</body>
</html>
Your jQuery and PHP code looks fine so, in my experience, it is usually an error caused by calling your PHP script from a different domain (i.e.: file:///). If you can access your browser's console, you should be able to see if this is in fact the error causing the data not to be displayed.
One solution for this is to add at the top of your PHP code:header('Access-Control-Allow-Origin: *');. There are however some security concerns with this, so it should not be used permanently.
Alternatively, you could upload all your HTML, CSS, JS, jQuery, etc. code to the web server hosting the PHP file, which is a far better option.
Finally, if the option above is not possible you could use JSON-P (although this does not work with POST requests), there is a question about this at Simple jQuery, PHP and JSONP example?

Issue when separating JS code from grails view to external JS file

I have some working JS code which I put on the sections of my create and edit views, and it's working fine.
However, when I attempted to move the code to a separate JS file, the code would no longer call the controller action.
Here the JS code:
<g:javascript>
$(document).ready(function(){
<g:remoteFunction controller="project" action="ajaxGetClient" onSuccess="updateClient(data)"/>
});
function updateClient(data){
var element = $("#project\\.client");
element.empty();
element.val(data.name);
}
</g:javascript>
Here's the controller action:
def ajaxGetClient = {
if(!params.id){
params.id = Project.find("FROM Project ORDER BY id").id
}
def projectInstance = Project.get(params.id)
render projectInstance?.client as JSON
}
And here's the GSP code:
<g:textField name="project.client" id="project.client" maxlength="9" required="" disabled=""/>
<g:select id="project" name="project.id" from="${myPackage.Project.list()}" optionKey="id" required="" value="${productInstance?.project?.id}" class="many-to-one"
onchange="${
remoteFunction(
controller: 'project',
action: 'ajaxGetClient',
onSuccess: 'updateClient(data)',
params: '\'id=\' + this.value'
)}"
/>
I added a resource to ApplicationResources.groovy and changed the above JS code to this:
<g:javascript library="updateclient"/>
I simply copy/pasted the code into a JS file and then got a message:
Uncaught SyntaxError: Unexpected token <
which I understood came from it not recognizing the GSP syntax, so I tried some AJAX, which I'm pretty unexperienced at:
$(document).ready(function(){
$.ajax({
type: 'POST',
url: "${remoteFunction(controller:'project', action:'ajaxGetClient', onSuccess:'updateClient(data)')}"
});
});
Here's what I'm getting from the browser console:
http://localhost:8080/MyApp/product/$%7BremoteFunction(controller:'project',%20action:'ajaxGetClient',%20onSuccess:'updateClient(data)')%7D 404 (Not Found)
Quite frankly, I'm at a loss right now. Any help would be appreciated.
The reason for this is that Javascript (.js) and other non GSP (.gsp) files aren't parsed through the Groovy server pages engine. Thus, tag libraries such as the or ${g.remoteFunction} aren't parsed.
There are several ways to accomplish this however.
One is to keep the code in your GSP and not externalize it into javascript files.
Second is to move your code into javascript files but have configuration values in your GSP file. Here is a very simple example of using the message taglib:
// inside the .js file
function myFunction() {
console.log("I would use this value: "+_VALUE_FROM_GSP);
}
<script type="text/javascript">
// inside the .gsp file
var _VALUE_FROM_GSP = "${message(code: 'just.an.example')";
</script>
Finally, there plugins (listed below) that allows you specify some resources (javascript files in your case) to be parsed through the Groovy Server Pages engine.
GSP-arse plugin and GSP Resources
I'll be answering my own question here, since the bulk of it came from valuable advice from a friend of mine, but Joshua's answer was also very important, so I ended up combining both of them.
This is how I solved it:
On the GSP:
<script type="text/javascript">
var _URL = '${resource(dir: "")}/project/ajaxGetClient';
</script>
<g:javascript library="updateclient"/>
The reason I'm using the <script> tag is because in order for the _URL variable to become usable across different files, it had to be declared before the file using it. At least that's what this other SO answer said:
Global variables in Javascript across multiple files
Separate JS file:
$(document).ready(function(){
getClientAjax(null);
});
function getClientAjax(id) {
$.ajax({
url: _URL,
type: "POST",
data: { id: id },
success: function(data) {
updateClient(data);
}
});
}
function updateClient(data){
var element = $("#project\\.client");
element.empty();
element.val(data.name);
}
And the controller action remained the same.
At the end, there had to be created another JS function, but I gotta say I'm happy with the result.
Thanks for all the help.

Jquery error : Object doesn't support this property or method

I am trying to using a tree structure on my JSP Page along with Jquery. Tree Structure requires to import few Jquery files. When I run the JSP page, I get the error code "Object doesn't support this property or method".
I tested the code by running the Tree Structure (Dyna Tree) code seperately and it works fine. Then I tried running the Jquery that I have written and it also works fine. The above mentioned error only appears if I integrate both the code. I have writted my custom code and error where exactly it appears.
NOTE : fm is name of the form on my JSP Page.
<script type="text/javascript">
var url;
function newUser(){
$('#dlg').dialog('open').dialog('setTitle','Create New Access');
$('#fm').form('clear'); // ERROR AT THIS LINE
url = 'saveaccess.jsp';
}
function editUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$('#dlg').dialog('open').dialog('setTitle','Edit Access');
$('#fm').form('load',row);
alert("test"+row);
//url = 'AddNeditApplication.jsp';
}
}
function saveUser(){
$('#fm').form('submit',{
url: url,
onSubmit: function(){
return $(this).form('validate');
},
success: function(result){
//var result =new Object();
alert(result);
if (result){
$('#dlg').dialog('close'); // close the dialog
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({
title: 'Error',
msg: result.msg
});
}
}
});
}
function removeUser(){
var row = $('#dg').datagrid('getSelected');
if (row){
$.messager.confirm('Confirm','Are you sure you want to remove this Access?',function(r){
if (r){
$.post('AddNeditApplication.jsp',{id:row.id},function(result){
if (result.success){
$('#dg').datagrid('reload'); // reload the user data
} else {
$.messager.show({ // show error message
title: 'Error',
msg: result.msg
});
}
},'json');
}
});
}
}
</script>
$('#fm').form('clear'); - Whenever JavaScript says "Object doesn't support this property or method", it's talking about the . operator. Which means the object returned by calling $('#fm') doesn't support the method form.
I can't find any documentation in the jQuery API for a form method. Perhaps you're trying to use EasyUI? Are you including the EasyUI scripts in your HTML in addition to jQuery (After jQuery, and before your code)?
Something like this:
<script src="http://www.jeasyui.com/easyui/jquery.easyui.min.js"></script>
...?
Reasons for Object doesn't support this property or method' exception:
Check and compare the browser version compatibility/support of the Jquery version.
i.e. IE8 does not support Jquery2x versions. In this scenario, use versions accordingly
The order of the files are wrong in your html/aspx file. Change order.. for example..
From...
<script src="js/jquery.easing.js"></script>
<script src="js/jquery.js"></script>
<script src="js/jqueryFileTree.js"></script>
<script src="js/default.js"></script>
<script src="js/jquery-1.4.1-vsdoc.js"></script>
<script src="js/jquery-1.4.1.js"></script>
<script src="js/jquery-1.4.1.min.js"></script>
To:
<script src="js/jquery-1.4.1-vsdoc.js"></script>
<script src="js/jquery-1.4.1.js"></script>
<script src="js/jquery-1.4.1.min.js"></script>
<script src="js/jquery.js"></script>
<script src="js/jqueryFileTree.js"></script>
<script src="js/default.js"></script>
<script src="js/jquery.easing.js"></script>
I was getting similar exception and now got resolved.

Categories