I am currently trying to insert some text in a specific spot at a website, http://kawowii.com , however, I keep getting error messages. These error messages seem to originate from the section I am trying to select using javascript (variables txtClasses and styleClasses). The error messages are
Uncaught TypeError: Cannot set property 'textContent' of undefined
So, the variables seem to be undefined but I don't understand why. I have looked at the other answers and still cannot determine what is wrong.
Right now, I have
window.onload = function() {
var txtClasses = document.querySelectorAll("div.coord-control.leaflet-control");
txtClasses[0].textContent = "Server: UP Location:"
}
and I tried this
window.onload = function() {
var styleClasses = document.querySelectorAll(".coord-control leaflet-control");
function insertAfter1(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
var brk = document.createElement("br");
insertAfter1(styleClasses[0], brk);
var div = document.createElement("div");
var textNode = document.createTextNode("Server: UP")
div.appendChild(textNode);
insertAfter1(brk, div);
}
My end goal is to change the website, kawowii.com , such that before Location :, it reads Server: UP using javascript.
I executed document.querySelectorAll("div.coord-control.leaflet-control"); on the website you provided, and it does in fact show an array with that element.
I think div.coord-control.leaflet-control is being inserted dynamically (perhaps after an AJAX request completes).
Therefore, you need to put your controlling logic inside the callback of the request:
whateverRequestIsInsertingThatElement.then(function() {
var txtClasses = document.querySelectorAll("div.coord-control.leaflet-control");
txtClasses[0].textContent = "Server: UP Location:"
});
I don't know if you're using promises or if the async method you're using provides a callback, but onload will happen in parallel with your async request, so you need to query for the dynamic element in the callback of the async request.
Not sure which API you're using to generate the map on your website, but usually any calls for location data will happen asynchronously (like the Google Maps API, for example). You can only manipulate dynamically generated DOM elements once the data has arrived.
Edit
You can see that the client is initially getting the configuration data from the route up/configuration. I would suggest looking for where that async call is being made in your source code, and then call querySelectorAll in its success handler.
I also see that in some of your sources, $.ajax is being called, so I assume somewhere in there, $.ajax is being called to the up/configuration route on your server.
So what I imagine happening is this:
You are querying your page for a your leaflet control but its returning an array of nothing. So when you try and access txtClasses[0] its undefined (since txtClasses.length == 0).
// this illustrates your problem
try {
// I am manually creating an empty array (your results)
var txtClasses = []
// this throws the error
txtClasses[0].bad = "throws an error";
} catch (e) {
// this just displays the error for you to see
document.getElementById("log").innerHTML += e.toString()
}
<div id="log"></div>
If you are expecting something back, you should check your selector is actually working (what I like to do is open up a web console and type my code right in there).
I noticed your selector changed in the first and second example too so make sure you read more about css selectors here.
Related
/**
* Created by quantumveil on 2/10/15.
*/
$(document).ready(function(){
$('a').on('click',function(){
//$href=$(this).attr('href');
//console.log($href);
var $convoid=$(this).attr('id');
console.log($convoid);
//$('#convoarea').load($href);
$.get('inbox.php',{convoid:$convoid},function(data){$('#convoarea').html(data);//the callback sets whati t had to
//now add the on click handler to send button
$('#send').on('click',function(){
var $msgbody=$('#sendbody').val();
console.log($msgbody);
///now what i have to do is sent this $msgbody to the inbox.php thru get k
$.post('inbox.php',{sendbody:$msgbody,convoid:$convoid},function(data){
$('#sendbody').before(data);
console.log('here'+$msgbody);
});//the callback function will append it to other messages :3
return false;
});
}//callback ends hre
);
return false;
});
//for send button
});
Hi. I'm trying to code a social networking site and I want the inbox to be responsive and dynamic. I've recently started learning Jquery for the purpose being. I've googled this before and found no help and so it brings me here on this community. The above Javascript/Jquery code is supposed to pass some post parameters when the SEND button is clicked. Another file, inbox.php, is to receive those and work appropriately. Now here's what bugs me. The callback function to $.post() is executed, so I'm assuming the parameters are being passed to inbox.php. But when I try accessing them in inbox.php using following line
if($msgbody=get_post('sendbody')&&$convoid=get_post('convoid'))
I only receive a value of 1 and not the message's actual body. Here's how the function get_post is defined
function get_post($var1){
if(isset($_POST[$var1])){$var=$_POST[$var1];
return filter($var);}
else return 0;
}
I've tried accessing them directly through $_POST['sendbody'] but an error of undefined index is being generated. Any help will be highly appreciated. (PS the other call to .get() in the beginning of this js file is passing the parameters so there's nothing wrong with file paths)
EDIT: It's fixed but I want an explanation. All I did was in the inbox.php changed the first line which was
if($msgbody=get_post('sendbody')
to
if(isset($_POST['sendbody'])$msgbody=$_POST['sendbody']
Now all I can wonder is if it has something to do with filter() function in the definition of my get_post() function. Anybody?
I have come across a situation that doesn't make much sense to me. Just as some background information, I'm using the Laravel framework. The page in question calls a query when the page is requested using Laravel's '->with('var', $array)' syntax. This query (which I will post later) works perfectly fine on page load, and successfully inserts dummy data I fed it.
I call this same query via an Ajax $.post using jQuery, on click of a button. However, when I do this $.post and call this query, I get an Internal Server Error every time. Everything is exactly the same, information passed included; the only difference seems to be whether or not it is called on page load or via the $.post.
Here is the error:
Below is the code that performs the query on page load:
routes.php sends the HTTP get request to a file called AppController.php
routes.php
AppController.php
The page is then made with the following array acquired from DeviceCheckoutController.php
Which then goes to DeviceCheckout.php
I am able to echo $test on the page, and it returns the ID of a new row every time the page is reloaded (which obviously mean the 'insertGetId' query worked). However, I hooked this query up to the page load just to test. What I really want to happen is on click of a button. Here is the code for that:
$("#checkoutFormbox").on('click', '#checkoutButton', function() {
var checkoutInformation = Object();
var accessories = [];
var counter = 0;
var deviceName = checkoutDeviceTable.cell(0, 0).data();
$(".accessoryCheckbox").each(function() {
//add accessory ID's to this list of only accessories selected to be checked out
if($(this).val() == "1")
{
accessories[counter] = $(this).data('id') + " ";
}
counter++;
});
checkoutInformation['deviceID'] = $(".removeButton").val(); //deviceID was previously stored in the remove button's value when the add button was clicked
checkoutInformation['outBy'] = '';
checkoutInformation['outNotes'] = $("#checkOutDeviceNotes").val();
checkoutInformation['idOfAccessories'] = 2;
checkoutInformation['dueDate'] = $("#dueDate").val();
if($("#studentIdButton").hasClass('active'))
{
checkoutInformation['renterID'] = 0;
checkoutInformation['emplid'] = 1778884;
console.log(checkoutInformation);
$.post("http://xxx.xxx.xxx.xxx/testing/public/apps/devicecheckout-checkoutdevices", {type: "checkoutDeviceForStudent", checkoutInformation: checkoutInformation}, function(returnedData) {
alert(returnedData);
});
}
});
Which is also then routed to AppController.php, specifically to the 'checkoutDeviceForStudent' part of the switch statement:
And then back to that query that is shown previously in DeviceCheckout.php
Finally, here is my DB structure for reference:
Any explanation as for why this would be happening? Also, any Laravel or other general best practice tips would be greatly appreciated as I'm inexperienced in usage of this framework and programming overall.
Sorry for such a long post, I hope there is enough information to diagnose this problem. Let me know if I need to include anything else.
Edit: Included picture of error at the top of the page.
Everything is exactly the same, information passed included
No, it isn't. If it was exactly the same you wouldn't be getting the error you're getting.
These sorts of issues are too difficult to solve by taking guesses at what the problem might be. You need to
Setup your system so Laravel's logging errors to the laravel.log file
Setup you PHP system so errors Laravel can't handled are logged to your webserver's error log (and/or PHP's error log)
Put Laravel in debug mode so errors are output the the screen, and the view the output of your ajax request via Firebug or Chrome
Once you have the actual PHP error it's usually pretty easy to see what's different about the request you think is the same, and address the issue.
I found a resolution to my problem after some advice from a friend; much easier than I anticipated and much easier than any solution that has been offered to me here or other places.
Essentially, what I needed to do was place a try, catch clause in my model function, and then if an exception is encountered I store that in a variable, return it, and use console.log() to view the exception. Here is an example to emulate my point:
public function getUserFullname($userID)
{
try
{
$myResult = DB::connection('myDatabase')->table('TheCoolestTable')->select('fullName')->where('userID', '=', $userID)->get();
return $myResult;
}
catch(Exception $e)
{
$errorMessage = 'Caught exception: ' . $e->getMessage();
return $errorMessage;
}
}
And then on the View (or wherever your model function returns to), simply console.log() the output of your POST. This will display the results of the successful query, or the results of the Exception if it encountered one as opposed to an unhelpful Internal Server Error 500 message.
Well i wanna create an Ajax Drag and Drop Shopping cart using only javascript and ajax. Currently i'm using the example in this page as a stepping stone. Right now it's only with local jquery and it works fine but i want to make the cart work with ajax calls. Note that i do not want to use a server side language( like php, rubby, asp etc), only html and javascript.
My initial thought was that at the $(".basket").droppable i should add an ajax call to another html page containing the "server logic" in javascript, execute in that file all the necessary steps( like reading the get variables (product name, product id and quantity), set a cookie and then return an ok response back. When the server got the "ok" response it should "reload" the cart div with the updated info stored inside the cookie.
If this was with php i would know how to do it. The problem is that as far as i know, you can execute javascript once it reaches the DOM, but how can you execute that js from inside the page that isbeing called upon ? ( thanks to Amadan for the correction)
I've thought about loading the script using $.getScript( "ajax/test.js", function( data, textStatus, jqxhr ).. but the problem with that is that the url GET variables i want to pass to the "server script" do not exist in that page.
I havent implemented all the functionality yet as i am stuck in how to first achieve javascript execution inside an ajax target page.
Below is a very basic form of my logic so far
// read GET variables
var product = getQueryVariable("product");
var id = getQueryVariable("id");
var quantity= getQueryVariable("quantity");
//To DO
//--- here eill go all the logic regarding cookie handling
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if (pair[0] == variable) {
return pair[1];
}
}
alert('Query Variable ' + variable + ' not found');
}
Any help regarding this matter will be appreciated.
Note: Logic in simple words:
1)have an html page with products+cart
2)Have an "addtocart.html" with the "Cart Server Logic"( being the target of the ajax call when an item is dropped into the product.)
If you have some other idea on this, please enlighten me :)
thanks in advance
Foot Note-1:
if i try loading the scipt using
$("#response").load("ajax/addtocart.html?"+ $.param({
product: product,
id: id,
quantity:quantity
})
);
i get the alert about not being able to find the url parameters( something that i thing is normal as because the content is being loaded into the initial page, from which the request is started, there are no get parameters in the url in the first place)
The problem is that as far as i know, you cannot execute javascript contained in the target of an ajax call, as that page never reaches the browser interpreter.
This is either incorrect or misleading. The browser will execute any JavaScript that enters DOM. Thus, you can use $.load to load content and execute code at the same time. Alternately, you can use hacked JSONP to both execute code and also provide content as a JSON document.
EDIT: Yes, you can't get to the AJAX parameters from JavaScript. Why do you want to? Do you have a good reason for it, or is it an XY problem?
The way I'd do it is this:
$('#response').load(url, data, function() {
onAddedToCart(product, id, quantity);
});
and wrap your JS code in your HTML into the onAddedToCart function.
Depending on what exactly you're doing, it could be simplified even further, but this should be enough to cover your use case.
For the last few hours I've been trying to set up this http://code.google.com/apis/books/docs/dynamic-links.html on a WordPress blog. Google's API sends back a JSON response (which is supposed to be "put" into _GBSBookInfo variable). However, that variable never is assigned so my javascript callback function explodes saying the variable doesn't exist. So far, all of my javascript is in the WordPress header.
I tried this outside of WordPress and it works fine.
This is the static page:
<script src="http://books.google.com/books?bibkeys=0307346609&jscmd=viewapi&callback=response_handler">
This is the handler:
function response_handler(data) {
var bookInfo = _GBSBookInfo["0307346609"]; // the var that doesn't exist
document.getElementById("test123").innerHTML = bookInfo.thumbnail_url;
}
Thanks for any help in advance, WordPress has been extremely frustrating by limiting so much! If I'm doing anything stupid please say so, I'm a new javascript programmer.
EDIT:
I've used firebug so far to identify the problem to be: the _GBSBookInfo variable never gets "created" or "exists". I'm not sure how javascript works at this level. Hopefully this helps.
ERRORS:
Error: _GBSBookInfo is not defined
Line: 79
Try replacing _GSBookInfo with data, like so:
function response_handler (data) {
var bookInfo = data["0307346609"];
document.getElementById("test123").innerHTML = bookInfo.thumbnail_url;
}
Based on your post, google returns this:
response_handler({
"0307346609": {
"bib_key":"0307346609",
....
"thumbnail_url":"http://bks2.books.google.com/books?somethumbnailstuff"
}
});
... so the above code should work for you.
I have following workflow
div on the page is used
on users operation request is done
to server side page whose html is
retrived using ajax and dumped into
the div
With html markup some JavaScript is
also dumped however that is not
getting executed.
Why is so ? What could be the possible fix ?
Though i avoid doing things like this but in some old code implementations like these are very common.
Scripts added using .innerHTML will not be executed, so you will have to handle this your self.
One easy way is to extract the scripts and execute them
var response = "html\<script type=\"text/javascript\">alert(\"foo\");<\/script>html";
var reScript = /\<script.*?>(.*)<\/script>/mg;
response = response.replace(reScript, function(m,m1) {
eval(m1); //will run alert("foo");
return "";
});
alert(response); // will alert "htmlhtml"
This will extract the scripts, execute them and replace them with "" in the original data.