Can I test Ajax functions locally? - ajax

I have a simple call to replace the contents of a <div> with those of another HTML file using the .load() function:
$('#content').show().load('01.html');
01.html is in the same folder as this page. But the function isn't being executed. Is there a problem with my code? Or is it that the .load() function won't work until it's being served?
In the latter case, what's a good way to go about testing it?

You'll need to do this instead:
$('#content').load('01.html', function() {
$(this).show();
});
It will show the content after a successful load (under the presumption that content was hidden to start with).

If you're already using jQuery why don't you just go for mocking or simulating ajax requests using jquery-mockjax ?

Related

Loading jsp page using jQuery .load() causes issue

I load a div dynamically with jquery .load() function. I am calling a jsp in which I I performing an operation on window.onload = function() { //some operation} and $(window).unload(function(){//some operation; anotherFunction();})
Now, the problem is that these operations are not being executed, but the call to anotherFunction() is made! I simply put an alert() before the function call and the alert won't fire, whereas the alert that I put inside anotherfunction() will be fired.
I have some javascript code that I have written in $(document).ready(function(){//some javascript code;}). None of my operation in the ready() function gets done when I load the jsp using .load().
all the above operations are working fine when I use <jsp:include page="myPage.jsp"></jsp:include>
does anyone have any idea why .load() would work this way?
My experience with JSP isn't great but I know a fair bit about Javascript and PHP so I assume this will work on a similar principle.
Are you using an onClick listener so for example $("SELECTOR").click(function(){
If so then I think try this for example instead:
$(document).on('click', "SELECTOR", function() {

What is the right away to update a panel using AJAX?

In MVC4 applications, I would like to update a panel using AJAX but using jQuery methods instead using AjaxExtensions from MVC.
But my problem is the updatePanelId.
I've seen several people use this to update it when has success:
success: function (response) {
var $target = $("#target");
var $newHtml = response;
$target.replaceWith($newHtml);
}
But when I do this, it forces me to use in every partial view that includes the id="target" at the root level of my razor view, and I guess that's not a good practice; I said this because I've realized when I use AjaxExtensions it doesn't happens, replace the update and it does not remove the panelId. But using jQuery it does.
Any idea to port the AjaxExtensions feature to jQuery?
You can use just:
$("#target").html(response); // it will just update content of the $("#target") container
Use jQuery's .load function. This will load the contents of the URL you specify into the target element. You can optionally specify a selector after the URL in load to only grab part of the target page.
$(function() {
$("#target").load("/MyURL");
});
JavaScript same origin policy applies to this.

How do I add DOM elements in jasmine tests without using external html files?

I'm writing some simple jasmine tests and I'm getting an exception since the code I'm testing is looking for a form that doesn't exist because there's no DOM when testing a js file only: $("form")[0] in the tested js file leads to:
TypeError: $(...)[0] is undefined
I read a bit about jasmine-jquery and realized I can use some html fixture with an external html file. That flow seems quite messy, since all I need to do is only to add an empty valid form so that the test (which focusing on something else) will run, something like <form></form> appending would be enough I think.
At first I thought that sandbox() function will be the solution, but it seems that it creates only divs, and I need a form.
Any simple way to add some elements by using only code in jasmine spec file?
The simplest solution is to add the form to the DOM by yourself in the before block and then delete it in the after block:
describe(function(){
var form;
beforeEach(function(){
form = $('<form>');
$(document.body).append(form);
});
it('your test', function(){
})
afterEach(function(){
form.remove();
form = null;
});
});
Also writing your sandbox helper isn't that hard:
function sandbox(html){
var el;
beforeEach(function(){
el = $(html);
$(document.body).append(el);
});
afterEach(function(){
el.remove();
el = null;
});
Another approach is to use jasmine fixture
The concept
Here's one way to think about it:
In jQuery, you give $() a CSS selector and it finds elements on the
DOM.
In jasmine-fixture, you give affix() a CSS selector and it adds those
elements to the DOM.
This is very useful for tests, because it means that after setting up
the state of the DOM with affix, your subject code under test will
have the elements it needs to do its work.
Finally, jasmine-fixture will help you avoid test pollution by tidying
up and remove everything you affix to the DOM after each spec runs.
See also: SO: dom manipulation in Jasmine test
You should use sandbox() to create a div and create a form element and append to sandbox, this is the safer way to jasmine take control to this fixtures in the DOM.

very strange jquery issue

I am trying to run a function on page load but its not working. I've added it in every place I can think of and the ONLY thing that works is:
$("html").mousemove(function(event) {
$('#project_thumbs_container').masonry('reload');
});
I've tried delays but I have resorted to the hacky above method :(
Does anyone have any suggestions as to why my function won't run?
UPDATE:
I am using masonry for jquery. My problem is when I load a page that uses masonry with ajax, it shows them in a single column. $('#project_thumbs_container').masonry('reload'); resets it properly, but it only works using the above mousemove method.
It sounds like you have one of two problems:
1) Malformed HTML which is causing an error, which isn't allowing the code to parse correctly when using the document onReady syntax: $(function() { ... });
2) Masonry might be loading asynchronously, which means that the "onReady" callback might not be the one that you want to be using. Your Ajax call would look more like this:
$('body').load('index.html', function() {
$('#project_thumbs_container').masonry();
});
Unless someone has a better answer, I just put the code in my fadeIn(); snippet after ajax call is complete:
this.fadeIn('slow', function() {
$('#project_thumbs_container').masonry('reload');
});
Seems to work.
Try something like this.
$(document).ready(function(){
$('#project_thumbs_container').masonry('reload');
});
You can put this code anywhere on the page and it should work, as long as the dependencies have already been loaded.
Just put your function in this
$(document).ready(function() {
// Handler for .ready() called.
// your function
});
when your page load the function will execute

how to get information from php without refreshing the page

hi
sorry for the bad title but I'm not 100% sure what I need for this problem
I created a welcome page and then when you click on links you get more information, for example:
Click Me
And then the php would get the information based on the id.
so the information received is reloaded on the page after the pages refreshes
what I would like to be able to do is when user clicks on the link, use jquery to not allow the link to run but still run the url in the background (without refreshing the page)
I have no idea where to start from so I really hope you could help
thanks
In a nutshell, it's called Ajax: sending an HTTP request to your server through javaScript, and receiving a response which can contain results, data, or other information.
You mention jQuery, here are the docs about that:
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
are convenience methods, which encapsulate $.ajax with preset options.
http://api.jquery.com/category/ajax/ is an overview of the whole system in jQuery.
The basics go like
//include jquery, etc.
$(document).ready(function(){
$('#some_element').click(function(){
$.get('some_url_on_your_server.php',{'data':'whatever params'},function(data){
do_something();//
},'json');
});
This will bind an element to make an Ajax call on click, and then you use the function ('success' function, in $.ajax) to handle the json data.
Have your server send back the data in JSON by using json_encode in php. Be sure to send the right header back, like
<?php
header('Content-Type: application/json');
echo json_encode($some_array);
exit;
There's a lot of resources on the web and SO for learning about Ajax, it's a big topic. Best of luck.
Make a JavaScript function, like sendData(linkId) and then each tag would have an onclick event called sendData(this). SendData(linkId) can then do an HTTPRequest (also known as an asynchronous or AJAX request) to a php file, let's call it handler.php, which receives GET or POST methods. I prefer using the prototype framework to do this kind of thing (you can get it at prototypejs.org).
Okay, now that I have said all that, let's look into the nitty-gritty of how to do this (way simplified for illustrative purposes).
Download the prototype script, save it on your server (like prototype/prototype.js, for example) and then put somewhere in your html <script type='text/javascript' language='Javascript' src='prototype/prototype.js'></script>
Your tags would look like this:<a id='exampleLink' onclick = 'sendData(this)'>Click me!</a>
You need JavaScript to do this: function sendData(tagId){
var url = 'handler.php?' + 'id=' + tagId;
var request = new AJAX.Request(url, {method = 'get'});
}
Finally, you need a php file (let's call it handler.php) that has the following: <?php
$tag_to_get = $_GET['tagId'];
do_a_php_function($tag_to_get);
?>
That's it in a nutshell, but it's worth mentioning that you should give your user some sort of feedback that clicking link did something. Otherwise he will click the link furiously waiting for something to happen, when it is actually doing just what its supposed to but in secret. You do that by making your php script echo something at the end, like 'Success!', and then add an onSuccess parameter to your JavaScript's new Ajax.Request. I'll let you read how to do that on your own because the prototype website explains how to receive a response from the handler and put the feedback somewhere in your HTML without making the user refresh.
you can achieve that behavior with a jquery function called $.get ... you can get more information on how to use here http://api.jquery.com/jQuery.get/
If you really want to (and I don't think you really do), you can use XMLHTTPRequest (wrapped in jQuery.get) to facilitate loading content into the page without page refreshing. You want an id or class on that tag, i.e. Click Me, and then:
<script>
$(".fetch").bind("click", function(evt)
{
$.get(this.attr("href"), function(data)
{
$("#whereIWantMyContent").html(data);
});
evt.preventDefault();
});
</script>
I would recommend you use AJAX to start with. A good place to being is http://www.w3schools.com/Ajax/Default.Asp
The link comes with a handy AJAX ASP/PHP Example too =))
Good Luck.

Resources