html javascript - onclick() reference error: function not defined - javascript

Given my html file, the console gives an error code:
Reference Error: loadData not defined.
Based from other answers I've rechecked mine where,
My function is declared just before the </body>,
I included the javascript library at the <head></head> ;
and even changed my <input type= submit to <input type= button
and if it helped, I tried deleting my form tags where it is enclosed (but this is for another question regarding query strings).
Here's how it would look like now:
<head>
<script src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
{%for document in documents %}
<li> {{document.filename}}
<input type="button" id="{{ document.id }}" onclick="loadData(this.id)" name = "load-data" value="Add to Layer"/>
</li>
{%endfor%}
<script type ="text/javascript">
function loadData(documentId){
$.ajax({
url:"/load",
data: {'documentId': documentId},
type: 'GET',
success: function(){
window.location.href = "http://127.0.0.1:8000/url/locations";
}
});
}
</script>
</body>
I can't seem to find an explanation why the function won't fire.

Here's the fix (as my friend explained):
I had to put my script up in the <head> tags.
Why? Because the document is already loaded before the script gets to be.
If I want to retain it at the bottom it had to look something like this:
$(document).ready(
$('input').onclick(function(){})
After putting it up the code works.

I've tested your html and everything seems to be working properly. The only error that I found was that $ajax is not a function. It is missing a dot $ajax => $.ajax
Try using:
function loadData(documentId){
$.ajax({
url:"/load",
data: {'documentId': documentId},
type: 'GET',
success: function(){
window.location.href = "http://127.0.0.1:8000/url/locations";
}
});
}

Related

How to convert JavaScript variable into PHP through ajax

its the code for posting a javascript variable into php...
but its not working..sugesstion...
i want to take value of id from javascript and post into a php.
<!DOCTYPE html>
<html>
<body>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("form").submit(function() {
var id = $("input[type=submit]").attr('id');
alert(id);
$.ajax({
type: 'post',
url:('abcde.php')
data: {id1: id},success: function(response){}
alert(id1);
});
});
});
</script>
</head>
<form action="abcde.php" method="POST">
<!-- other form fields -->
<input type="submit" id="a" name="idVal" value="a">
</form>
</body>
</html>
<?php
if(isset($_POST['id']) ){
$id=$_POST['id'];
echo $id;
}
?>
ohh boy, 1st: it's
data: {'id': id}
secondly, your code is really wrong on this part, you are not doing anything in success, and you just randomly put an alert() in, with a variable that doesn't even exist.
So instead of success: function(response){}, it should be success: function(response){alert(response);} and forget about the alert(id1);
Other errors I saw from looking at it quickly: you are submitting your form from AJAX and HTML as well. You should block the default behavior with a function at the beginning of .submit(funcition() {...}. There already is a function for that, but I can't remember.
Lastly, you are sending the form data to the same page you are submitting from. You will get an answer from AJAX with the same page you are looking at. You should extract the php code to a different file and make abcde.php a simple abcde.html file.
One last thing: instead of alerts, you should use Console.log and watch the browser's console for debugging. You will see a bunch of errors, which makes debugging a lot easier.
You should, instead of blindly coding, be more mindful about what is responsible for what. You should be thinking more about the side-effects of you are introducing to your code. This will come with experience, we've all been there. Make sure one 'thing' is only responsible for ONE task.

Trouble combining jQuery and .php in Wordpress

I am trying to make a simple translation site here:http://traductordeinglesaespanol.co/. I created a simple php code that uses get to an external translation api which works fine. Here's the code:
<?php
if(!empty($_GET['text'])){
$trans_url ='http://api.mymemory.translated.net/get?q='.urlencode($_GET['text']).'&langpair=en|es' ;
$trans_json = file_get_contents($trans_url);
$trans_array = json_decode($trans_json, true);
echo $trans_array['responseData']['translatedText'];
}
?>
Here is the simple html form:
<form id="form" method="get" action="tran.php">Enter Text to be Translated below:
<input name="text" type="text" id="test" />
<button id="but">Translate</button></form>
<div class="results"></div>
The translation works ok now but I what I would like to do is to grab the tran.php result using jQuery and show it in the "result" class below the form. I am trying to do this by the following:
I loaded by editing the functions.php file so it loads jQuery and a .js script named tran.js. When I inspect element I see both jQuery and the script being loaded. In the script I put this basic code:
jQuery(document).ready(function(){
$('#go').click(function() {
$.ajax({
type: 'GET',
url: 'tran.php',
success: function(data) {
$('.result').html(data);
}
});
});
});
and change action to to handle the form from this page. (tran.php is in the root directory.) But it isn't working at all. I suspect there is/are some crucial mistakes in the coding but being a complete beginer I cannot find where the mistakes are so any advice/correction would be greatly appreciated!
I somehow managed it to work! There was a small typo:
data : 'text=' + to_be_translated;
I replaced the ";" in the end with a comma and now I am getting the result like this: Let's say I input the text name to translate (nobre in spanish!), I get this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>estes</title> </head> nombre
So I have to get rid of these headers somehow! Anyway I want to thank you again very much for your help! Gracias!
You should use ajax this way :
var to_be_translated = "Hello";
$.ajax({
type: 'GET',
url: 'tran.php',
data : 'text=' + to_be_translated,
success: function(data) {
$('.result').html(data);
}
});
Here I added the "data" label, it says the JS variable to_be_translated will be seen as $_GET['text'] in PHP.

Execute php file with javascript function

I want to execute php file in javascript function. Code is as shown below:
<a id="cancel" href="./?&_action=list" onclick="javascript:clearRecord();return rcm.command('list','',this,event)">Cancel</a>
<script language="javascript" type="text/javascript">
var u1='michael';
function clearRecord() {
$(function() {
location.href = 'clear.php?h='+u1;
});
}
</script>
But when I click to cancel button, clear.php not executed. How I should come out from this?
full & working answer to your question:
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function cancelClicked() {
// function below will run clear.php?h=michael
$.ajax({
type: "GET",
url: "clear.php" ,
data: { h: "michael" },
success : function() {
// here is the code that will run on client side after running clear.php on server
// function below reloads current page
location.reload();
}
});
}
</script>
</head>
<body>
<a id="cancel" href="#" onclick="cancelClicked()">Cancel</a>
</body>
</html>
if you want to just execute some php and leave current page to the one generated by this php script. then you got it almost right.
I do not see that you are using jquery - so skip this "$(function(){})" part, and i don't see what u1 is added for but this will work:
function clearRecord() { location.href = 'clear.php'; }
and this will do the same:
Cancel
BUT if you want only to run "clear.php" and then reload current page.
One way of doing it can be putting at the end of your "clear.php" file something like:
header("Location:/");
(it will work only if clear.php does't write anything in response).
But you can do it other ways:
- using AJAX - call clear.php with jQuery.get() and call location.reload() on success;
- using IFRAME - set iframe's location to clear.php and then call window.location.reload();
- using IMG - set img.src to clear.php ...
...and possibly many other ways :)

How to load more jquery script to DOM by jquery ajax

I am creating an application that may become very large over time. So in order to keep things simple, we have decided to keep Javascript (mostly jQuery code), CSS and html for one particular feature in one file. for example, if upload is a function, then we have all the jQuery validation and css, html for upload in one file (without head and html tags).
We have a home dashboard in which a click handler will load all the links by ajax and append to the designated DIV of class indicated by additional attribute in links called "whereTOadd". so if a link has its "WhereTOadd" attribute set to ".here" and href set to upload.php then the contents of upload.php will be added to a div of class 'here' in the same page. it is done using script given below.
But the problem i am facing is that I need to include jQuery file again in every file to get the codes working, which is a terrible thing. What can be done to avoid this?
This is html of my dashboard:
<html>
<head>
..
<script src="Path-to-jquery-min-file.php" ></script>
<script>
$( document ).ready(function(){
$(document).on("click","a",function(e){
if( $(this).attr('href'))var ajaxurl = $(this).attr('href').valueOf();
if( $(this).attr('whereTOadd'))
var target = $(this).attr('whereToadd').valueOf();
/*for ajax request */
var options= {
type: 'GET',
url: ajaxurl,
dataType: 'html',
success: function (html, textStatus){
$(target).empty().append(html);
},
error: function(xhr, textStatus){
alert('error');
}
}
$.ajax(options);
return false;
});
});
</script>
</head>
<body>
<a href="upload.php" >Upload data</a>
<div class=".here" ></div>
</body>
upload.php contains:
<script type="javascript" >
$('body').append('load successful!');
</script>
This setup will not work until I make change in upload.php as:
<script src="Path-to-jquery-min-file.php" ></script>
<script type="javascript" >
$('body').append('load successful!');
</script>
Please help in solving this because loading jQuery again and again in the same page may cause errors and conflicts. Please suggest me a better approach to what I am doing.
Thanks

JavaScript not run on onsubmit event

To learn about web programming, I'm trying a simple html/javascript/php "product search" page. Here is the index.php file:
<html>
<head>
<title>Product Search</title>
<script type="text/javascript">
function mySubmit() {
alert("submitting...");
var product_type = $('product_type').value;
$.post('product_search.php', { product_type: product_type }, function (data) {
alert("result = " + data);
$('body').html(data);
}
return false;
}
</script>
</head>
<body id="body">
<script type="text/javascript">
mySubmit();
</script>
<form class="form" id="myform" method="post" onsubmit="javascript:return mySubmit();">
Product Type:
<input id="product_type" type="text" name="product_type"/>
<br/><br/>
<input id="submit" type="submit" value="Submit"/>
</form>
</body>
</html>
and the product_search.php file is very small:
<?php
$product_type = $_POST["product_type"];
echo "<h1>$product_type</h1>";
?>
The problem is that it seems like the onsubmit event is never called for the form. I thought it was a JavaScript problem (as in, not allowed to run), but if I run an alert instead of calling mySubmit() when the onsubmit event is called, it works!
Also, am I wrong in thinking that the JavaScript just under the <body id="body"> should be run? It is never run either.
So, for those who didn't read all that: why is my JavaScript function not being run when the onsubmit event is fired?
I get the following parsing errors when I run your code:
Uncaught SyntaxError: Unexpected token return
Uncaught ReferenceError: mySubmit is not defined
You are missing the closing ) on your $.post call, which is breaking the parser. Once you fix that, you'll get the $ is undefined error until you reference jQuery.
http://jsfiddle.net/Z6hJK/
<script type="text/javascript">
mySubmit();
</script>
above function is called but when it is called, even document.getElementById('product_type').value gives error (which might not be enabled on your browser to catch) as it product_type turn out to be null as javascript in body gets executed before browser has fully rendered the page. The moment it is getting called, product_type is not yet rendered.
On click also your function is getting called, but this time may be it is failing as you do not have reference to Jquery. include one.

Categories