jQuery ajax stopped working - javascript

My jQuery script stopped working when I moved my clients site from the dev-site to their own site (which basicly has the same setup using a VPS).
jQuery(document).ready(function() {
jQuery('input[name=button]:button').click(function(){
jQuery("#show").html('<center><img src="http://xxxx/images/ajax-loader.gif"></center>');
jQuery.get("http://xxx/inc/usrreg_ajax.php",{
namn: jQuery("input[name='namn']").val(),
nyhetsbrev: jQuery("input[name='news']").val()},
function(data){
jQuery("#show").fadeIn("slow").html(data);
});
});
});
im using the html
<div id="registering" style="margin-top: 15px;">
<div style="float:left;">
<label for="namn">Namn:</label><br/>
<input type="text" name="namn"><br/>
<input type="checkbox" name="news" value="ja">Ja, jag vill ha nyhetsbrev! <br/>
<div style="clear:both;"></div>
<input type="button" name="button" value="Anmäl dig!">
<div id="show"></div>
</div>
I've not made any changes post move and the jQuery script works perfect on the dev-site.
Very gratefull for any input!
All the best,
Marten

Is xxx/inc/usrreg_ajax.php on the same domain as your new site?
You have to remember that there a same origin policy that, for security reasons, prevent you from perform ajax calls from other domain urls.
http://en.wikipedia.org/wiki/Same_origin_policy
Due to browser security restrictions,
most "Ajax" requests are subject to
the same origin policy; the request
can not successfully retrieve data
from a different domain, subdomain, or
protocol.
You can use jsonp for different domain calls, but you will have to use jQuery.ajax for that, and won't be able to get the html as simple as you are doing right now

I test it here http://jsfiddle.net/bingjie2680/D4NuF/ and it works(get the image to show up), there must be a problem with the link to jQuery library.

Related

Redirect to a SubDirectory via Form Input in JavaScript

When this project was first started we thought it would be super easy but after two days of failure, we are stumped.
Environment: MacBookPro - WordPress with Thrive Themes Architect
Goal: Create a simple form that allows visitors to input the name of a subdirectory into a form that instantly redirects them to that subdirectory upon clicking on the submit button.
Purpose: When a partner gives out their website URL which includes a subdirectory name sometimes the person fails to put in the subdirectory name and they go to the main site instead. This form would make it easy for them to get to the right place so that the right partner gets proper credit.
Theories: Could the redirect be being blocked by Browser security protocols or something? Is the coding off in some way? Is the method flawed?
Three of Many Failed Coding Attempts:
<script type="text/javascript">
function Redirect(){
var subDirectory= document.getElementById("sub_directory").value;
window.location.href= "https://www.thewatercoach.com/" + subDirectory;
}
</script>
<form>
<label>www.theWaterCoach.com/</label>
<input type="text" id="sub_directory">
<button onclick="Redirect()">Submit</button>
</form>
Results: The page simply refreshes or reloads the pre-existing URL, but doesn't work at all.
<script type="text/javascript">
function Redirect(){
var subDirectory= document.getElementById("sub_directory").value;
window.location.replace(subDirectory);
}
</script>
<form>
<label>www.theWaterCoach.com/</label>
<input type="text" id="sub_directory">
<button onclick="Redirect()">Submit</button>
</form>
Results: The page simply refreshes or reloads the pre-existing URL, but doesn't work at all.
<script type="text/javascript">
function Redirect(){
var subLink = document.getElementById("sub_Link");
var subDirectory= document.getElementById("sub_directory").value;
subLink.href = "https://www.theWaterCoach.com/" + subDirectory;
subLink.click();
}
</script>
<form>
<label>www.theWaterCoach.com/</label>
<input type="text" id="sub_directory">
<button onclick="Redirect()">Submit</button>
</form>
<a id="sub_Link" href="https://www.theWaterCoach.com/">.</a>
Results: This Coding Example did work reliably with FireFox but not on Chrome or Safari. It does not work via Chrome on a PC either. For testing purposes, you can enter Becca into the text box.
Any ideas or solutions will be greatly appreciated!
The submit button is located inside a form tag. Therefore, when you click submit, the browser simply sends a GET request to your homepage. The Javascript code to redirect got executed, but then it is terminated right before the GET request is sent.
Solution: You have to prevent the form from being submitted. Find out how: read this stackoverflow question.

Getting around CORS with embedded google forms

I'm trying to send form data to google via an embedded form.
I found this post that seems to answer my question but I'm getting CORS errors. Is there a way to solve this?
Other posts seem to say that CORS isn't an issue but I'm getting the errors.
Here is my code:
-JS-
function ajax_post() {
var field1 = $('#email').val();
$.ajax({
url: "https://docs.google.com/forms/d/e/xxxxxxxxxxxxxxxxxxxxxx/formResponse",
data: {"entry.xxxxxxxxxx": field1},
type: "POST",
dataType: "xml",
statusCode: {
0: function() {
//Success message
},
200: function() {
//Success Message
}
}
});
}
-HTML-
<form id="emailForm" target="_self" onsubmit="" action="javascript: ajax_post()">
<input id="email" type="text" autocomplete="off" tabindex="0" name="entry.xxxxxxxxxx" required>
<button id="send" type="submit">Submit</button>
</form>
The “No 'Access-Control-Allow-Origin' header is present on the requested resource” message indicates that responses from https://docs.google.com/forms/d/e/xxxx/formResponse URLs currently don’t include the Access-Control-Allow-Origin response header, so browsers won’t allow your frontend JavaScript code to access the response.
Given that, from your frontend code there’s no way you can tell if the POST request succeeds or not. But barring any other problems, it seems like the request will always succeed. If the request doesn’t reach the server at all (due to some network error) then you’ll hit a different failure condition that is observable from your frontend code so you can actually catch it.
So the way you know the request has successfully reached the server is just that you don’t get any other failure that’s observable from your frontend code.
I've found that it's actually easier to just POST the form with a hidden iframe as its target, and capture that iframe reload when the response is submitted.
For example, if this is your form:
<form id="my-form" target="my-response-iframe" action="https://docs.google.com/forms/u/1/d/e/<YOUR-ID>/formResponse" method="post">
<input type="text" name="entry.12345678" value="" required>
<input type="submit">
</form>
Then include an iframe on the same page, with the same id AND name you put as target in the form:
<iframe id="my-response-iframe" name="my-response-iframe"></iframe>
When the form is submitted, it should reload that iframe with the "Your response has been recorded." page from Google. We can catch that reload with JavaScript, so include this after your form and iframe:
<script type="text/javascript">
// set the target on the form to point to a hidden iframe
// some browsers need the target set via JavaScript, no idea why...
document.getElementById('my-form').target = 'my-response-iframe';
// detect when the iframe reloads
var iframe = document.getElementById('my-response-iframe');
if (iframe) {
iframe.onload = function () {
// now you can do stuff, such as displaying a message or redirecting to a new page.
}
}
</script>
You can't check whether the response was submitted correctly because you can't inspect the contents of a cross-origin iframe (that'd be a huge security risk), so just assume that if this iframe reloads, the response was ok.
You can hide the iframe with the following CSS:
visibility: hidden
height: 1px;
Much cleaner if you ask me, with no console errors or failed requests.

Web Api 2 - Check if User Is Logged In

I am still finding my way around in ASP.NET.
I am experimenting with getting Angular code talking to a Web API 2 end point, which will only be accessed from within the solution itself.
One thing I want to be able to do is to show or hide edit buttons based on whether the current user is logged in or browsing anonymously.
I could do this in an MVC view by checking User.Identity.IsAuthenticated but I'm curious how I could do it with a pure Angular page, with no .NET coded in it.
I thought I could just do something like this
public class AuthorizationController : ApiController
{
public HttpResponseMessage Get()
{
if (User.Identity.IsAuthenticated)
{
return Request.CreateResponse(HttpStatusCode.OK, "Ok");
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You are not authorized");
}
};
}
And then call it like this
$http.get("../api/authorization")
.then(function (response)
{
if(response.status=="200")
{
// logged in
}
else
{
// not logged in
}
});
Unfortunately, this doesn't do what I was hoping. If the user is not logged in, the API code hits the line creating an error response, but what it actually returns to the Angular callback is
{"data":"<!DOCTYPE html>\r\n<html>\r\n<head>\r\n <meta charset=\"utf-8\" />\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\r\n <title>Log in - My ASP.NET Application</title>\r\n <link href=\"/Content/bootstrap.css\" rel=\"stylesheet\"/>\r\n<link href=\"/Content/site.css\" rel=\"stylesheet\"/>\r\n\r\n <script src=\"/Scripts/modernizr-2.6.2.js\"></script>\r\n\r\n\r\n</head>\r\n<body>\r\n <div class=\"navbar navbar-inverse navbar-fixed-top\">\r\n <div class=\"container\">\r\n <div class=\"navbar-header\">\r\n <button type=\"button\" class=\"navbar-toggle\" data-toggle=\"collapse\" data-target=\".navbar-collapse\">\r\n <span class=\"icon-bar\"></span>\r\n <span class=\"icon-bar\"></span>\r\n <span class=\"icon-bar\"></span>\r\n </button>\r\n <a class=\"navbar-brand\" href=\"/\">Application name</a>\r\n </div>\r\n <div class=\"navbar-collapse collapse\">\r\n <ul class=\"nav navbar-nav\">\r\n <li>Home</li>\r\n <li>About</li>\r\n <li>Contact</li>\r\n </ul>\r\n <ul class=\"nav navbar-nav navbar-right\">\r\n <li>Register</li>\r\n <li>Log in</li>\r\n </ul>\r\n\r\n </div>\r\n </div>\r\n </div>\r\n <div class=\"container body-content\">\r\n \r\n\r\n\r\n<h2>Log in.</h2>\r\n<div class=\"row\">\r\n <div class=\"col-md-8\">\r\n <section id=\"loginForm\">\r\n<form action=\"/Account/Login?ReturnUrl=%2Fapi%2Fauthorization\" class=\"form-horizontal\" method=\"post\" role=\"form\"><input name=\"__RequestVerificationToken\" type=\"hidden\" value=\"5h-wFJ5pn4Vq8uI15BbzTvAwAFuudI1jaF_YsHfpAp9YFaeArEkO4P6i5bFMYgSs6OY6BXDEHzNLFpxYA-IvQJlr7zYY8Bgj9mErF1dgMQQ1\" /> <h4>Use a local account to log in.</h4>\r\n <hr />\r\n <div class=\"form-group\">\r\n <label class=\"col-md-2 control-label\" for=\"Email\">Email</label>\r\n <div class=\"col-md-10\">\r\n <input class=\"form-control\" data-val=\"true\" data-val-email=\"The Email field is not a valid e-mail address.\" data-val-required=\"The Email field is required.\" id=\"Email\" name=\"Email\" type=\"text\" value=\"\" />\r\n <span class=\"field-validation-valid text-danger\" data-valmsg-for=\"Email\" data-valmsg-replace=\"true\"></span>\r\n </div>\r\n </div>\r\n <div class=\"form-group\">\r\n <label class=\"col-md-2 control-label\" for=\"Password\">Password</label>\r\n <div class=\"col-md-10\">\r\n <input class=\"form-control\" data-val=\"true\" data-val-required=\"The Password field is required.\" id=\"Password\" name=\"Password\" type=\"password\" />\r\n <span class=\"field-validation-valid text-danger\" data-valmsg-for=\"Password\" data-valmsg-replace=\"true\"></span>\r\n </div>\r\n </div>\r\n <div class=\"form-group\">\r\n <div class=\"col-md-offset-2 col-md-10\">\r\n <div class=\"checkbox\">\r\n <input data-val=\"true\" data-val-required=\"The Remember me? field is required.\" id=\"RememberMe\" name=\"RememberMe\" type=\"checkbox\" value=\"true\" /><input name=\"RememberMe\" type=\"hidden\" value=\"false\" />\r\n <label for=\"RememberMe\">Remember me?</label>\r\n </div>\r\n </div>\r\n </div>\r\n <div class=\"form-group\">\r\n <div class=\"col-md-offset-2 col-md-10\">\r\n <input type=\"submit\" value=\"Log in\" class=\"btn btn-default\" />\r\n </div>\r\n </div>\r\n <p>\r\n Register as a new user\r\n </p>\r\n</form> </section>\r\n </div>\r\n <div class=\"col-md-4\">\r\n <section id=\"socialLoginForm\">\r\n \r\n<h4>Use another service to log in.</h4>\r\n<hr />\r\n <div>\r\n <p>\r\n There are no external authentication services configured. See this article\r\n for details on setting up this ASP.NET application to support logging in via external services.\r\n </p>\r\n </div>\r\n\r\n\r\n </section>\r\n </div>\r\n</div>\r\n\r\n\r\n <hr />\r\n <footer>\r\n <p>© 2016 - My ASP.NET Application</p>\r\n </footer>\r\n </div>\r\n\r\n <script src=\"/Scripts/jquery-2.2.3.js\"></script>\r\n\r\n <script src=\"/Scripts/bootstrap.js\"></script>\r\n<script src=\"/Scripts/respond.js\"></script>\r\n\r\n \r\n <script src=\"/Scripts/jquery.validate.js\"></script>\r\n<script src=\"/Scripts/jquery.validate.unobtrusive.js\"></script>\r\n\r\n\r\n\r\n<!-- Visual Studio Browser Link -->\r\n<script type=\"application/json\" id=\"__browserLink_initializationData\">\r\n {\"appName\":\"Firefox\",\"requestId\":\"69b5785bb7f0400088c465aa19c19c8a\"}\r\n</script>\r\n<script type=\"text/javascript\" src=\"http://localhost:55784/9f4b9571f5a149d8a3ad956c641aff65/browserLink\" async=\"async\"></script>\r\n<!-- End Browser Link -->\r\n\r\n</body>\r\n</html>\r\n","status":200,"config":{"method":"GET","transformRequest":[null],"transformResponse":[null],"url":"../api/authorization","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":"OK"}
So it seems to be returning a log in page. Can someone tell me what I am doing wrong? Or am I just completely barking up the wrong tree with this approach?
Presumably, you're using forms authentication. By default, forms authentication will detect an unauthenticated event in the pipeline (401) and convert it to a redirect (302) to the login page. If your client is automatically following that redirect (most do), then you'll ultimately get the content of the login page with HTTP success status code (200).
There are two reasonably straight-forward solutions to this:
Don't use forms authentication (OK, not entirely straight-forward if you don't have an alternative authentication middleware to hand).
Set the HttpResponse.SuppressFormsAuthenticationRedirect property to true.
Per documentation for HttpResponse.SuppressFormsAuthenticationRedirect:
By default, forms authentication converts HTTP 401 status codes to 302
in order to redirect to the login page. This isn't appropriate for
certain classes of errors, such as when authentication succeeds but
authorization fails, or when the current request is an AJAX or web
service request. This property provides a way to suppress the redirect
behavior and send the original status code to the client.
And regarding the value of the property:
true if forms authentication redirection should be suppressed;
otherwise, false.
For further reading, and full credit to Phil Haack as my first source of easy information on the topic, check out his blog post on the subject.
I know the question is regarding the server side web api. but If someone want to examine another approach, and it is possible to do it on the client side using javascript/typescript maybe this approach can help future readers:
I prefer to do it locally, using localStorage and save unnecessary calls to the server.this.serverResponse.expires_inis the expiration time in seconds.
extract the expiration date from the web api server:
var tokenexpiration: Date = new Date();
tokenexpiration.setSeconds(new Date().getSeconds() + parseInt(this.serverResponse.expires_in))
console.log(tokenexpiration);
than you can save it to localStorage:
localStorage.setItem('expirationdate',tokenexpiration)
and with simple condition you can check whenever you need if the token was expired.
You should have a look at the AuthorizeAttribute. You can decorate your controllers with it or some of its methods and then handle the UnAuthorized exception in AngularJS (status 401 I think).
.Net will decide if a request is authorized or not based on cookies most of the times, but this really depends on the authentication scheme you're using.

Can't get iframe content

I know there are many topics about it, but none of them worked. I need just to get iframe content(not source code).
I have a form, that posts some parameters to another server and I target it to iframe(that lies on the same page). So I receive server responce code storred in my iframe without page refresh:
<form name='vin_form' id='file_upload_form' action='*****' method='post'>
<input name='name1' value='value1'>
<input name='name2' value='value2' type='hidden'>
<input name='name3' value='value3' type='hidden'>
<div onclick=\"document.getElementById('file_upload_form').target = 'upload_target'; document.vin_form.submit();\">Send form</div>
</form>";
<iframe id='upload_target' name='upload_target'></iframe>
To get iframe content I used everything, but nothing worked:
jQuery('#upload_target').load(function()
{
alert(jQuery('#upload_target').contents().find('body').html());
var myIFrame = document.getElementById('upload_target');
var content = myIFrame.contentWindow.document.body.innerHTML;
alert(content);
alert(window.frames.upload_target.document.body);
}
);
I read about "same origin policy", but I think it shouldn't be forbidden in my case, because I can access that page by url and read all the code, so why I can't do it programmatically?
P.S.: Are there some other ways to get form responce code from another server? (php curl doesn't work because of some site framework defence)
*update - try this:
var t = document.getElementById("upload_target");
var y =( t.contentWindow || t.contentDocument);
alert(y.document.body.innerHTML)

to send a text file to server using javascript

I need to send a text file to server and get it saved. how can i do it using javascript???
There are all sorts of security issues surrounding this. Would you be happy to visit a website that would upload a file from your machine to the server?
For a generic website, where users are likely to have their permissions set to deny this sort of access it isn't possible.
If by chance, you are looking to do this for an application where you have control over the security settings for its users, and that you can guarantee its Windows and IE, then it is possible by reading the file and passing the details by posting to the server. See the following link : http://www.javascripter.net/faq/reading2.htm
However when you move away from IE or Windows, then you are going to struggle.
using ajax of course.
have a file on the server, PHP or ASP - depending on what your internet server is.
this file will accept the text file (data and name), and should also check for size and if this file already exists or not, and if all is ok- it will save it, and return a string "OK"
on the client, javascript side, just send the information to the server using ajax, or HTTPREQUST object - there's plentty of documentation for that around. and if you get back a response of "OK" then you know that it sent well.
even better: don't use HTTPREQUEST, but do dynmaic script tag insertion - where the source attribute of the script you're appending is that file on the server like:
var a = document.createElement('script');
a.type = 'text/javascript';
a.src = "http://server/serverFile.PHP?filename=XXX&data=LONG STRING OF DATA REPRESTING THE DATA TO BE SAVED PROBABLY LESS THAN 2K IN SIZE AND ALSO YOU SHOULD ESCAPE OR ATLEAST URIENCODE IT";
document.body.appendChild(a);
and on the server file, serverFILE.PHP:
<?php
// some code to save the request variable [data].
// if all is ok:
alert("ok")
// or:
result = "ok"
?>
get it?
note: you'll probably have a limit of less than 2K on the file size.
Javascript is a front-end language. You may use php or any server side language.
You can create an Ajax equiv function make an iframe with width and height=0px then make it the target of the form with the file upload input and process it with the action PHP
<form action="upload.php" target="target" method="post"
name="uploadform" id="uploadform" enctype="multipart/form-data">
<label for="input_file_upload">Upload:</label>
<input onchange="document.uploadform.submit();" size="80"
type="file" name="file_upload[]" id="file_upload"
multiple="multiple" />
<input type="hidden" name="fileUpload" value="upload" />
<input type="button" value="Upload" />
</form>
<iframe id="target" name="target" style="width: 0px; height: 0px;">
</iframe>

Categories