Javascript url 404 error - javascript

I'm have a problem loading a site. Using this code:
$.ajax({
type: "POST",
//url: '#Url.Action("/TellFriendPopup")',
url: '/Property/TellFriendPopup',
data: { "SenderName": SenderName, "senderMail": senderMail, "receiverMail": receiverMail, "comments": comments, "urlLink": urlLink, "subjectId": subjectId },
success: function (data) {
$("#result").html("<ul><li>Name: " + data.nameret + "</li><li>Email: " + data.emailret + "</li><li>Message: " + data.messageret + "</li></ul>");
$(".dialog").dialog("close");
},
The problem is that I had to move the code to a JavaScript file, instead of the MVC4 View, where i could use the #Url.Action method. But it is not working in JavaScript. It Just gives me this error POST http://localhost:54717/Property/ContactPopup 404 (Not Found). The reason as I can see is that it's the Globalization that it's missing. Because the url should look like this http://localhost:54717/da/Property/ContactPopup or http://localhost:54717/en/Property/ContactPopup

You could get the first folder of the pathname. As long as that is where the language code is on every page.
var language = location.pathname.split("/")[1];
url: language + '/Property/TellFriendPopup'

You can have language in hidden field.
var language = document.getElementById('language`).value;
url: '/' + language + '/Property/TellFriendPopup'

Can you try changing this: url: '/Property/TellFriendPopup',
to this url: '../Property/TellFriendPopup',

Related

Why append part does not work in ajax call

In the code below after I upload my document I wrote a loop which is supposed to add some images into a division called Divnavigation, but this part doesn't work.
Also when I make it uncommented even my documentViewer can not be loaded. Am I allowed to add something to my division from AJAX call?
function navigate(target) {
$.ajax({
url: '#Url.Action("Download", "Patient")',
type: 'GET',
async: true,
dataType: 'json',
cache: false,
data: { 'filepath': target },
success: function (results) {
// documentViewer.loadDocument(results);
documentViewer.uploadDocumentFromUri(results[results.length -1]);
documentViewer.addEventListener(gnostice.EventNames.afterDocumentLoad, function (eventArgs) {
document.getElementById("TotalPage").textContent = documentViewer.viewerManager.pageCount;
document.getElementById("pageNumber").value = documentViewer.viewerManager.currentPage;
$("#Divnavigation").empty();
//Get all images with the help of model
for (var i = 0; i < results.length; i++) {
$("#Divnavigation").append(" <ul> " +
"<li>" +
"<img src=" + results[i] + ">" + "</img>" +
"" + "" +
"</li>"
+ "</ul>");
}
});
//showImages();
},
error: function () {
alert('Error occured');
}
});
}
Hi Answer to your question first:
Am I allowed to add something to my division from .ajax call?
you are 100% allowed to add something to your division from .ajax call. there is no doubt in that. I done personally many times
This time you are not getting because of some other reason.
Now my suggestion is try using $("#Divnavigation").html().
Official doc: https://api.jquery.com/html/
so first as first step try by putting simple html like this $("#Divnavigation").html("<p>test</p>) and see whether you get the output. if you get then change, html string whatever you want ,that can be hardcoded string or even you can get that string from the action method.
Hope above information was helpful. kindly share your thoughts
Thanks

jQuery string appearing in form

I am seeing a sporadic issue that is causing me a headache to investigate.
I have a PHP page with a basic form with a few simple text fields.
jQuery is used to send this POST data back to the server which in turn saves a record in MySQL and sends email notifications. This works fine throughout the day but randomly (I cannot recreate it). the server will add the same record 5-10 times in the DB and send the same amount of emails.
The only clue to me which is causing this is that random a random jQuery string is included in some of the returned data (see below)
Comments: Please can you sendjQuery17209552029577380006_1461157696021
this to me.
I am using jQuery 1.7.2 which explains the jQuery172, but not sure what the rest of this is.
Any ideas on where I should go with this? I may upgrade jQuery to see if this resolves it but thought I would ask here also?
jQuery 1.7.2 Code Below:
$(document).ready(function() {
$('#quick_form').submit(function(e) {
e.preventDefault();
$.ajax({
url: baseUrl+'products/send_quote',
dataType: 'json',
type: "POST",
async: true,
cache: false,
data: 'prod_id='+$('input[name="prod_id"]').val() + '&' +
'quote_name='+$('input[name="quote_name"]').val() + '&' +
'quote_email='+$('input[name="quote_email"]').val() + '&' +
'quote_phone='+$('input[name="quote_phone"]').val() + '&' +
'quote_company='+$('input[name="quote_company"]').val() + '&' +
'quote_cols='+$('input[name="quote_cols"]').val() + '&' +
'quote_size='+$('input[name="quote_size"]').val() + '&' +
'quote_qty='+$('input[name="quote_qty"]').val() + '&' +
'quote_comments='+$('#quote_comments').val() + '&' +
'token='+$('input[name="token"]').val(),
success: function(response) {
if(response.success) {
$('#quote').slideUp('fast',function() {
$('#quote').empty().html('<div class="successMessage">'+response.message+'</div>');
}).slideDown('fast');
}
else {
$('.errMess').empty();
$.each(response.messages,function(k,v) {
$('.errMess').append('<div>'+v+'</div>').show();
});
}
}
});
});
});

Why do url variables cause issues with ajax relative url?

So, I'm doing a normal ajax call like this:
$.ajax({
type: "GET",
url: this.Controller + "/" + this.Action,
data: data,
cache: false,
dataType: "json",
success: function (data) {
var json = $.parseJSON(data);
$("#Debug").html(JSON.stringify(json, undefined, 4));
},
error: function (jqXHR, textStatus, errorThrown) {
var errorMessage = "Unable to retrieve data."
if (jqXHR.responseText != null) {
errorMessage += "\n\nError Message: " + jqXHR.responseText;
}
alert(errorMessage);
}
});
When I use a relative path for the ajax url, it works fine, as long as there are no url variables in the current page's url. It will correctly go to http://domain.com/controller/action
If there is a url variable, the ajax url tries to hit http://domain.com/controller/controller/action, which does not exist.
If I add a slash like so:
url: "/" + this.Controller + "/" + this.Action
This fixes the issue of that the url variables cause, but only locally. When I deploy to our servers, my app is located in a sub-directory, so the url is http://domain.com/myapp. The slash solution does not work as the root is http://domain.com and not http://domain.com/myapp.
you can try this $.ajax({url: document.domain + this.Controller ... }) .
I tried all kinds of ways to do this via JS and none of them worked for both server (with sub-directory) and local (without).
So, my solution was to add the name of the sub-directory in my web.config's appsettings. In the main web.config, I have: <add key="Subdirectory" value="" />
In the web.release.config, I have: <add key="Subdirectory" value="SubDirectoryName" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
By leaving it blank in the web.config and setting it in web.release.config, the sub-directory will be transformed and set only when published to the server.
On the _Layout.cshtml page, I have:
<script>
var subdirectory = '#ConfigurationManager.AppSettings["Subdirectory"]';
if (subdirectory != '') {
subdirectory = '/' + subdirectory;
}
</script>
Then, anywhere in my JS that I am trying to do an ajax call, I set the url to:
url: subdirectory + "/" + this.Controller + "/" + this.Action, // subdirectory comes from _Layout.cshtml

$ajax is not working with ASP.Net

I am debugging my solution on localhost and this piece of code is not hitting the server
var cartInfo = $j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val() + '&email=' + email.val() + '&phone=' + phone.val() + '&date=' + date.val() + '&cart=' + cartInfo;
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
What am I missing here?
the are 2 potential problems
the url
the data
aspx assumes webforms, the page life cycle, etc. when all you want is to send response and get a reply. instead try targeting either a
web service (asmx)
generic handler (ashx)
a static pagemethod think ajax server hanlders embedded within a page object
second is the data. instead of passing a string as the data try passing a json object
data = {
name: "john",
email: "john#email.com",
...
}
Since you are passing the cartInfo as an html, it should be url encoded before it is posted. I think this is wat causing this issue. Try this
var cartInfo =
$j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val()
+ '&email=' + email.val()
+ '&phone=' + phone.val()
+ '&date=' + date.val()
+ '&cart=' + encodeURIComponent(cartInfo);
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
As suggested by in other answer you can also pass data as a key/value pair object to ajax method, jQuery will take care the rest but you still have to encode the html content.
Url Doesnt call any method ?
url: "LightBoxContactSender.aspx",
If yoy are trying to call a WebMethod inside aspx
url :"LightBoxContactSender.aspx/callStaticMethod",
Try to form Data as
dataString = "{'name=' + '"+name.val()+"'}"

Post Forms Using Javascript URL

I'm trying to submit a form to a website not my own (salesforce.com with their web-to-lead function) and I'm doing it through a javascript modal window.
Basically once all the entries are tested and made sure there are no errors, I use this:
if(error_count == 0) {
$.ajax({
type: "POST",
url: "[salesforce url]",
data: "first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&firm=" + firm + "&[salesforceid]=" + AUM + "&[salesforceid]=" + custodian + "&[salesforceid]=" + custodian_other,
error: function() {
$('.error').hide();
$('#sendError').slideDown('slow');
},
success: function () {
$('.error').hide();
$('.success').slideDown('slow');
$('form#callToAction').fadeOut('slow');
}
});
}
If tested the form without using javascript and the url works, so I'm thinking maybe the way javascript handles the url is the issue?
The issue: the data is not getting successfully submitted to Salesforce. Again, regular HTML form works, javascript doesn't. So I've identified it as a javascript issue.
You cannot make a XHR cross domain request unless the receiving server has allowed it and the browser supports CORS. You can however do a blind submit like this which will assume success:
var $form = $("<form>", {
method: "POST",
action: "[salesforce url]",
target: "my-iframe"
}).appendTo("body");
var $iframe = $("<iframe>", {
name: "my-iframe"
}).bind( "load", function () {
$('.error').hide();
$('.success').slideDown('slow');
$('form#callToAction').fadeOut('slow');
$iframe.remove();
$form.remove();
}).appendTo("body");
$.each(("first_name=" + first_name + "&last_name=" + last_name + "&email=" + email + "&firm=" + firm + "&[salesforceid]=" + AUM + "&[salesforceid]=" + custodian + "&[salesforceid]=" + custodian_other).split("&")), function (index, value) {
var pair = value.split("=");
$form.append("<input>", {
type: "hidden",
name: pair[0],
value: pair[1]
});
});
$form.submit();
+1 for Jim Jose. This sort of thing could be interpreted as an XSS attack against the user, so most likely the browser will not allow it.
You could check out your browser's error logs, see if there's any security errors when you try to run your script. If that doesn't do anything, try to install a tool like Firebug and see if it can pinpoint the problem.
You could also improve your error handling by trying a different sort of method signature for the error function, like this:
error: function(jqXHR, textStatus, errorThrown) {...}
This way you can check what sort of error is being thrown from the Ajax call.

Categories