AJAX and ASP Image Loading Problems - ajax

Im working on a production interface and im need to load some images. Im working in jsp mainly but using AJAX to request the images.
The AJAX itself works, if I create an HTML page with a simple:
<div id='holding'><img id='myImage' src='images/image.png' alternate='check' width='64' height='64' /></div>
and request it through the AJAX method the image loads and displays fine by setting something's inner.HTML to the response. I want to be able to change the source path dynamically so in asp i've created:
<%
x=Request.QueryString("x")
y=Request.QueryString("y")
Response.Write("<div id='holding'><img id='myImage' src='"&x)
Response.Write("'alternate='"&y"' width='64' height='64' /></div>")
%>
Now when I call my ajax with a query string I no longer get my image loading.
var src = 'images/image.png';
var alt = 'check';
var queryString = "?x="+src+"&y="+alt;
xmlhttp.open("GET", url + queryString, true);
xmlhttp.send();
Ideas?

I have discovered the problem here. Besides a few typos and syntax errors here and there the major issue was that ASP was not installed on the server I was accessing, we use a lot of .asp scripts but they are all tied to a different server.
One issue in particular that would follow to any language is that my queryString contained a '/' that I had not 'escaped'. This has been replaced with '%5c'
Since my work is in JSP anyway I decided to rebuild this using that, what follows is the scriptlet I used to load my images, saved as a .jsp and written in regular java, I call this with my AJAX method and it works beautifully:
<%
String source = request.getParameter("src");
String alternate = request.getParameter("alt");
out.println("<img border='0' src='"+source+"' alt='"+alternate+"' width='128' height='128' />");
%>

Related

Base URL is changing when making Ajax call

I have a CakePHP 3.x app with some APIs being called from AJAX.
On AJAX I call the url like so:
url: 'user/id/' + id,
method: 'get',
dataType: 'json'
// ...
Etc..
My url is http://localhost:8090/users
So the url on ajax is like
http://localhost:8090/currentpage/users/id/
But for some reason sometimes the url changes to http://localhost:8090/users/id/
What should I change?
What is happening?
This is happening because of your action(parameter) in URL.
Here are some examples so you can understand it better.
Let consider we have a link to every page of our project.
Click Here to add a new user
This link will create different URL depending on your current URL
Current URL URL generate by LINK
localhost/products (here index is the method) localhost/users/add
localhost/products/add localhost/products/users/add
localhost/products/edit/1 localhost/products/edit/users/add
To fix this issue, use a "/" at the beginning and provide the path from your webroot
I think the other answer is correct.
On how to solve it, what I commonly do is save the webroot as returned from CakePHP in a javascript variable. By doing this in the header of the template file it will be available everywhere:
<!-- src/Templates/Layout/default.ctp -->
<head>
<script>
var webroot = <?= $this->request->webroot ?>
</script>
</head>
When you then want to create a Ajax call, use this URL as generated from Javascript:
url: webroot + "user/id" + id //...
Now the call will be as expected, regardless of where your application is placed on the webserver.

Ajax helper in ASP.net MVC

I know that this question may not be fit for stack overflow. I've been searching for an example on how to use the ajax helper but most toturials have only gone through the helper and they have not provided any practical example. I already know how to make use of ajax the javascript way but just want to know how I can use the ajax helper that microsoft has provided.
To describe how this GitHUb branch works:
First, let's define an action we're going to request. To keep things simple, let's just make a very basic POST action:
//
// POST: /Home/Ajax
[HttpPost]
public PartialViewResult Ajax()
{
// use partial view so we're not bringing the entire page's theme
// back in the response. We're simply returning the content within
// ~/Views/Home/Ajax.cshtml
return PartialView();
}
Next, setup a destination for your content and give it an id (here I've named it "update-me"):
<div class="well" id="update-me">
Click the button to see some AJAX content.
</div>
Moving on from there we setup the form. The below demonstrates the standard AJAX functionality, but you could bind your own functions to some of the events specified by AjaxOptions.
#using (Ajax.BeginForm("Ajax", new AjaxOptions {
HttpMethod = "POST", // HttpPost
InsertionMode = InsertionMode.Replace, // empty the target first
UpdateTargetId = "update-me" // place content within #update-me
}))
{
<button type="submit" class="btn btn-default">
<i class="glyphicon glyphicon-refresh"></i>
Click Me!
</button>
}
And finally, we need to specify our script libraries responsible for most of the ["automatic"] wiring up of the form functionality:
<script src="~/Scripts/jquery-2.1.1.min.js"></script>
<script src="~/Scripts/jquery.validate.min.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>
That's it. As you begin playing with it you'll find it's pretty simple to extend it. For example, if you wanted to show a "working" icon you could specify custom functions in the OnBegin and OnComplete properties.
Ajax helper of ASP.NET MVC essentially provides Ajax functionality to your web applications. AJAX Helpers are used to create AJAX enabled elements like as Ajax enabled forms and links which performs request asynchronously. Using Ajax helper you can submit your HTML form using Ajax so that instead of refreshing the entire web page only a part of it can be refreshed. Additionally, you can also render action links that allow you to invoke action methods using Ajax. AJAX Helpers are extension methods of AJAXHelper class which exist in System.Web.Mvc.Ajax namespace.
AJAX-enabled link based on action/controller example:-
Following example shows how to use AJAX action link using action and controller in Asp.Net MVC.
#Ajax.ActionLink("Fatch Data", "GetData", new AjaxOptions {UpdateTargetId = "Data-container", HttpMethod = "GET" })
Here is the html output of above code block.
Output:
<a data-ajax="true" data-ajax-method="GET" data-ajax-mode="replace" data-ajax-update="#Data-container" href="/Home/GetData"> Fatch Data </a>
Do you know Unobtrusive AJAX in MVC?
The Unobtrusive Validation and AJAX support in ASP.NET MVC follow many best practices that enable Progressive Enhancement and are also super easy to use. The unobtrusive AJAX library (not the unobtrusive validation library) is admittedly a bit limited in functionality, but if it satisfies the requirements of the application you are writing, then by all means use it. And because the source code of it is in your app (it's JavaScript, after all), it's generally straightforward to make any updates or changes to it as you see fit.

Dynamic display in Grails

I have this problem I'm facing. I have been working on a project using Grails based on the advice from a friend. I'm still a novice in using Grails, so any down to earth explanation would be highly welcomed.
My project is a web application which scans broken or dead links and displays them on a screen. The main application is written in Java, and it displays the output (good links, bad links, pages scanned) continuously on the system console as the scan goes on. I've finished implementing my UI, controllers, views, database using Grails. Now, I will like to display actively in a section of my GSP page say forager.gsp the current link being scanned, the current number of bad links found and the current page being scanned.
The attempts I have tried in implementing this active display include storing the output my application displays on the console in a table in my database. This table has a single row which is constantly updated as the current paged scanned changes, number of good links found changes and number of bad links found changes. As this particular table is being updated constantly, I've written an action in my controller which reads this single line and renders the result to my UI. The problem I'm now facing is that I need a way of constantly updating the result being displayed after an interval of time in my UI. I want the final output to look like
scanning: This page, Bad links: 8, good links: 200
So basically here is my controller action which reads the table from the database
import groovy.sql.Sql
class PHPController {
def index() {}
def dataSource
def ajax = {
def sql = new Sql(dataSource)
def errors = sql.rows("SELECT *from links")
render (view: 'index', template:'test', model:[errors:errors])
}
}
Here is the template I render test.gsp
<table border="0">
<g:each in="${ errors }" var="error">
<tr><td>${ error.address }</td><td>${ error.error}</td><td>${ error.pageLink}</td></tr>
</g:each>
</table>
For now I'm working with a test UI, which means this is not my UI but one I use for testing purposes, say index.gsp
<html>
<body>
<div><p>Pleaseeee, update only the ones below</p></div>
<script type="text/javascript">
function ClickMe(){
setInterval('document.getElementById("auto").click()',5000);
alert("Function works");
}
</script>
<div id="dont't touch">
<g:formRemote url="[controller:'PHP', action:'ajax']" update="ajaxDiv"
asynchronous="true" name="Form" onComplete="ClickMe()" after="ClickMe()">
<div>
<input id="auto" type="button" value="Click" />
</div>
</g:formRemote>
<div id="ajaxDiv">
<g:render template="/PHP/test"/>
</div>
</body>
</html>
The div I'm trying to update is "ajaxDiv". Anyone trying to answer this question can just assume that I dont have an index.gsp and can propose a solution from scratch. This is the first time I'm using Grails in my life so far, and also the first time I'm ever dealing with ajax in any form. The aim is to dynamically fetch data from my database and display the result. Or if someone knows how to directly mirror output from the system console unto the UI, that will also be great.
It sounds like a form would be appropriate for your needs. Check out the Grails documentation on forms. You should be able to render a form with the values you would like without too much trouble. Be sure to pay attention to your mapping and let me know if you have any questions after you have set index.gsp up to render a form for your values.

Grails formRemote redirects rather than to just call method

I'm new to Grails and got some problem with the g:formRemote command..
I want a g:textArea box send a message to my controller and save this messages.
After that the page should be updated via the formRemote Ajax, so that the messages appear on the page.
But instead of updating the page, the formRemote call assumes the given url to be a real link and wants me to redirect to this (non-existing) .jsp site.
The Method I want to start is called in my controller tho
I tried many solutions offered in similar problems, but it seems this problem is different from theirs
Heres the code:
<div id="history">
<g:render template="posts" collection="${ messages }" var="message" />
</div>
<div class="postMessageForm">
<g:formRemote name="postChatMessage" url="[controller: 'meetingRoom',
action: 'postMessage']" update="history">
<div class="msg_box">
<g:textArea name="message" value="" style="width: 630px"/><br/>
</div>
<div style="float: right;">
<g:submitButton name="Send" style="width: 90px; height: 40px;"/>
</div>
</g:formRemote>
</div>
and this is the Action which is called in my MeetingRoomController:
def postMessage() {
if (params.message != "") {
def thisUser = lookUpUser()
def thisRoom = thisUser.joinedRoom
def chatPost = new ChatPost(
message: params.message,
author: thisUser
)
thisRoom.addToChatHistory(chatPost)
}
// def messages = currentChatHistory()
// render template: 'posts', collection: messages, var: 'message'
I saw this kind of approach in Jeff Browns Twitter tutorial.
Possible failures i am seeing:
the out-commented render template command has something to do with the Ajax (When I do not comment it the only thing that happens is that the template posts will be rendered on the redirected page
usage of both Ajax and jQuery (But i dont believe that can be the point because I just have used g: and groovy stuff and havent even imported a jQuery lib)
this could be easier with remoteFunction (I dont really know how to get the remoteFunction work in this case tho)
I hope this information is enough to let someone see what I am missing
When the submit button is clicked on your form, the data is sent to the method listed in the url parameter of the formRemote tag. Then you are inside that method, you get to the commented out render tag that outputs data back to the gsp page in the div mentioned in the update tag of the formRemote tag.
formRemote relies upon a javascript library to handle the ajax stuff as mentioned in the grails documentation:
7.7.1 Ajax Support
By default Grails ships with the jQuery library, but through the
Plugin system provides support for other frameworks such as Prototype,
Dojo:http://dojotoolkit.org/, Yahoo UI:http://developer.yahoo.com/yui/
and the Google Web Toolkit. This section covers Grails' support for
Ajax in general. To get started, add this line to the tag of
your page:
You can replace jQuery with any
other library supplied by a plugin you have installed. This works
because of Grails' support for adaptive tag libraries. Thanks to
Grails' plugin system there is support for a number of different Ajax
libraries including (but not limited to):
jQuery Prototype Dojo YUI MooTools
So remove what is in the history div, uncomment the two lines in your postMessage method, and include one of the referenced javascript libraries.

struts2 ajax redirect

i develop a app that is built with struts2+tiles+dojo (for the ajax part), and i have the following demand: At every 2 seconds i have to check a table from the DB, if certain conditions are met, i have to redirect the user to a special page.
The way that i solved this problem was creating a struts2 actions which`s check the table and render as a response something like :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
<script>
window.location= '<s:property value="url"/>';
</script>
</body>
</html>
and this page is accesed via a ajax call like:
<sx:div href="%{ajaxUrl}"
updateFreq="1200"
cssStyle="float:right"
id="live"
loadingText="Loading..."
executeScripts="true"
parseContent="false">
</sx:div>
and this is how i accomplish the redirect.
I`m sure that there has to be an more elegant and optimized solution.
Any ideeas ?
Use the struts2-json-plugin on the action which is the target of ajaxUrl. I don't use the sx tags, I just use JS (with jQuery, the normal library not using any struts2 plugin). Any ways use JS to asynchronously call your action every 2 seconds with JS (or framework of choice) and you will get back the url as a json string, and you will then redirect to that new url if the string is not empty (or you could return back many variables perhaps, perhaps containing some of the conditions found in the DB and showing them on the page and redirect according to those status variables).

Resources