ajax form submit cross server - ajax

I have several servers on an intranet. I am passing data from one server to be processed on another server. Attempting to use ajax but I am a noob.
<script type="text/javascript" src="jquery-1.8.0.js"></script>
<script type="text/javascript">
function print(oForm){
var toggle = oForm.elements["toggle"].value;
var ticket_type_id = oForm.elements["ticket_type_id"].value;
var printer_id = oForm.elements["printer_id"].value;
var store_id = oForm.elements["store_id"].value;
var data = oForm.elements["data"].value;
var dataString = "toggle="+ toggle+ "&ticket_type_id="+ ticket_type_id+ "&printer_id="+ printer_id+ "&store_id="+ store_id+ "&data="+ data;
$.ajax(
{
type:"POST",
url:"http://192.168.12.103/crowncontrol/backend/processes/print.php",
data:dataString,
success: function(data){
alert("successful");
}
}
);
}
</script>
The above URL does not work.
But if I make the url:
"../../../backend/processes/print.php"
Which is the same location, it works fine.
Also if I send it via Anchor Get it works fine:
href="http://192.168.12.103/crowncontrol/backend/processes/print.php?etc"
The reason I am using ajax is, I want my print.php script to run with out the user noticing. The reason I can't use url:"../../../backend/processes/print.php" is because I will be sending information from one server to another servers on my intranet.
Any help would be appreciated. I've spent far too long trying to get it to work on my own.
AFTER help from the answers below instead of the entire ajax code I used:
$.getJSON('http://192.168.12.103/crowncontrol/backend/processes/print.php?callback=?',dataString,function(res){
//alert('Success');
});
also:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js" type="text/javascript">

This is a result of the same origin policy. You can not perform a normal AJAX requests cross-domain requests for security reasons (see the link about same origin policy).
Fortunately for you jQuery includes JSONP request support which uses script tag injection instead of XMLHttpRequest.
Instead of creating and using an xhr object (XMLHttpRequest which is how ajax is done) it creates a script tag with an src attribute set to your URL. it should work.
Try changing your code to :
$.ajax(
{
type:"POST",
url:"http://192.168.12.103/crowncontrol/backend/processes/print.php?callback=?",
data:dataString,
success: function(data){
alert("successful");
}
}
);
(notice the ?callback=? part)
Here is a jsonp tutorial for jQuery
Here is some information about jsonp and some information about the same origin policy

Easy way to deal with this problem is to make a script file in your server and then route the requests through that server request.Use this logic below:
Instead of making the AJAX request directly to cross domain, make the AJAX request to a new script on your server.
In that script file, get the request and make the required call(to that cross domain address).
Then recieve the response from the cross domain server and send it to the client.
Receive the result from your own server which has required data.
This diagram shows:

Related

Django - AJAX - Why do I need url parameter?

It's my first time using AJAX and I don't understand why I need to specify url parameter in a JS Ajax call.
{% block javascript %}
<script>
$("#id_username").change(function () {
$.ajax({
url: '/some_new_url/',
data: {
'something': ...
},
success: function (data) {
if (data.is_taken) {
alert("Data is already in DB");
}
}
});
});
</script>
{% endblock %}
To my understanding, AJAX is used to do something on the server side without refreshing a page. So it shouldn't redirect to a new url upon sending a data to the server, and stay on the same url. And yet AJAX call requires url parameter.
And I don' really like this, because setting a new url means I have to add another url pattern in my app/urls.py.
re_path(r'^create/$', views.Some_View.as_view(), name='create'),
And as a consequence, make another view in my views.py
class Some_View(ListView):
model = SomeModel
fields = '__all__'
But, I already have a CBV that generates form fields on the user side and accepts user inputs. I only want to make my existing CBV to save data to DB using AJAX call.
Since I don't understand what the purpose of the url is, I don't know how to set up my new url pattern, and CBV. Can I get some explanation here?
++ This is just a bonus question, but my ultimate goal is to generate multiple form fields, and multiple Submit buttons that sends the respective form input data to the server using AJAX. If there's any advice on how to tweak AJAX code, I would appreciate it.
An AJAX request is just a regular HTTP request to a url on the server. The only difference between an AJAX request and a request made by an ordinary browser GET or POST is that with AJAX, the results that come back from the server are returned to your javascript function and then you get to decide what to do with those results.
So there's no automatic updating of anything.
If you want to save something on the server, you need a view there on the server which is capable of understanding the data you are sending in the AJAX request, saving it, and then sending back a response which, again, your javascript code needs to be able to understand.
But if you already have a view which is capable of doing what you want, you can use it for your AJAX request, you just have to send a request with everything in it that the view requires.

Does Ajax always require the use of node.js?

I learning about the use of AJAX in web development, and I need to know if AJAX always require the use of node.js, or JQUERY?
Thanks.
That is a very broad question, so the answer might be broad as well:
The short answer: Ajax does not require jQuery nor Node.js.
In practice, Ajax is a technology for asynchronous operations utilized by Javascript send data to and retrieve from a server asynchronously(1). Ajax is fully available in plain, vanilla Javascript, and it works as follows (example taken from Wikipedia, see sources):
// This is the client-side script.
// Initialize the Http request.
var xhr = new XMLHttpRequest();
xhr.open('get', 'send-ajax-data.php');
// Track the state changes of the request.
xhr.onreadystatechange = function() {
var DONE = 4; // readyState 4 means the request is done.
var OK = 200; // status 200 is a successful return.
if (xhr.readyState === DONE) {
if (xhr.status === OK) {
alert(xhr.responseText); // 'This is the returned text.'
} else {
alert('Error: ' + xhr.status); // An error occurred during the request.
}
}
};
// Send the request to send-ajax-data.php
xhr.send(null);
This is a classic example, showing both how to use Ajax with vanilla Javascript, and also why it's much easier with other means such as jQuery, shortening the same snippet to just:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
}).done(function(data) {
// Do something with data.
});
Sources (including vanilla Ajax examples):
Wikipedia: Ajax
A Guide to Vanilla Ajax Without jQuery
jQuery: ajax()
There is no need to use node.js to perform an Ajax request. You can make an Ajax request even using vanilla Javascript. However, jQuery made the Ajax request is very easy and cross-browser compatible with just some lines of code. So, I recommend you to stick with jQuery instead of using vanilla Javascript.
You can find more information regarding the jQuery Ajax feature here: http://api.jquery.com/jquery.ajax/
You can also find more information about the vanilla Javascript Ajax request feature here:
http://www.w3schools.com/ajax/
No, most browsers supply means to perform asynchronous javascript requests but libraries such as jQuery partly came about to smooth over the differences between browsers, making ajax a lot more portable.
Modern browsers generally don't have so great differences, so portability is probably is less of an issue, but using libraries has become common practice.

django csrf in ajax not work

I have a form and post it to server using json data,and the server save it in database. here is my code
function saveChanges() {
var items = [];
$('ol.item_list > li.item').each(function(){
items.push(getItemData($(this)));
});
var csrftoken = $.cookie('csrftoken');
$.ajax({
url : '',
type: 'POST',
headers : {"X-CSRFToken": csrftoken},
data : $.toJSON(items),
success: function(data, textStatus, jqXHR){
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus);
},
});
}
The problem is, I call saveChanges (via a button) twice, all return 200 http ok. So I got duplicate data in database. Should the csrf token provent duplicate sumbit? How can I fix it?
You should prevent double submission by taking care to properly
lay out your script execution flow & script structure so that you prevent that.
No, the CSRF token doesn't prevent duplicate submit of any kind. Its purpose is to prevent Cross Site Request Forgery, nothing else. It creates a token so nobody can trick you in submitting requests you don't intend to do.
If you want to prevent duplicate submits, a way would be to disable the submit button after it is clicked once. However, this is by no means a good solution, since JavaScript runs on client side and can easily be manipulated (e.g. via Firebug). So duplicate submits would still be possible, just not that obviously.
A better way is to do validation in your server-side Python code. You can check if the submitted data is already in the database and, if so, ignore the request or optionally return an error message. This makes sure that even by fiddling around with the JavaScript, an evil-meaning user cannot save data twice.
I would use both of these means, the first one simply to tell the user that he should not try to submit the same data twice - that's just an interface perk.

JQuery ajax calls not working in Firefox browser

I am trying to test Jquery ajax calls in Firefox but it it not working. I mean my server is not receiving any requests. But when I test in IE8 it works fine. Here is my ajax call:
$("#getWeatherReport").click(function(){
$cityName = "New York";
$.ajax({
type: "POST",
dataType:"xml",
url: "http://localhost:8080/Test/WeatherServlet",
data: "cityName="+$cityName,
success: function(data) {
alert($("report", data).text());
},
error: function(xhr, textStatus, errorThrown) {
alert('ERROR['+xhr.statusText+']');
}
});
});
It is not even calling error function. And from my server code(java) I am setting content type as "text/xml".
Any suggestions?
Your string is not correctly serialized, I'm not sure if that's the issue, but it may be and it's definitely a potential one for later, try this for an immediate test:
var $cityName = "New+York";
As a more permanent solution, pass data as an object, like this:
data: {cityName: $cityName},
Have you installed Firebug?
Your best bet would be to install Firebug, which comes with a console that'll notify you of any javascript errors. You can also use it (via the "Net" tab) to monitor all requests made by your page.
From what I can see, your code looks OK (other than the possible issue pointed out by #Nick Craver)
Also, why the '$' on your cityName variable? The '$' prefix in Javascript is meant to be reserved for machine-generated code (so that it has no chance of conflicting with user code).
try installing firebug plugin in ff :: https://addons.mozilla.org/en-US/firefox/addon/1843/
Then check the :::: Net Tab >> All selected
Refresh the page and see is your ajax call actually getting called. If yes is there any syntax error in the call or any variable null error. If all is fine then you can think of further issues
Usually, when I end up with a parseerror that means that the return header type is wrong or that somehow the server sent extra data with the response. For instance, if I'm looking to get JSON back and I get the JSON and some HTML from x-debug.
Also, The OPTIONS request is for cross-domain requests which is what #Nick was alluding to.
A helpful link to get you started.

Why do I get this 501 Not Implemented error?

I am performing the following AJAX call:
$(document).ready(function() {
$.getJSON('https://sendgrid.com/api/user.stats.json',
{
'api_user': 'me#mydomain.com',
'api_key': 'MYAPIKEY',
'user': 'me#mydomain.com',
'category': 'MY_CATEGORY'
},
function(response){
alert('received response');
}
);
});
and I get no alert message as expected. Instead, Firebug says I get "501 Not Implemented."
Why? What do I need to do to fix this?
If I go to the URL corresponding to the AJAX call in Firebug, I get a JSON file as a download, and it contains the expected data.
One thing I've noticed is that firebug says OPTIONS instead of GET:
alt text http://grab.by/grabs/b1a13d92a4fc69aa310880a5d7a06b95.png
I don't know if this is related, but generally when requesting JSON on the client to a server in a different domain you'll need to use JSONP instead of JSON due to the Same Origin Policy. Unfortunately, it doesn't appear that their API supports using JSONP -- so they must expect you to interact with their site from your server. In that case you'll need proxy methods on your server to translate the calls to their API so that the client calls are made to a server in the same domain as the page.
As this is the top Google match for "jQuery 501 (Method not implement)" I thought I'd share what worked for me when experiencing this on the same domain (which is not your problem).
My problem was that I was not returning valid JSON, I was just returning "1". So to fix this, either:
Ensure you return valid JSON, or if you don't require a JSON response,
Swap your call to use $.ajax instead of $.getJSON, or
If you're already using &.ajax, remove type: "json"
Hope that helps some people.
I had the same problem, and realized it was an encoding problem. It was solved by encoding the values of the data sent to the server. Try something like:
$(document).ready(function() {
$.getJSON('https://sendgrid.com/api/user.stats.json',
{
'api_user': encodeURIComponent('me#mydomain.com'),
'api_key': encodeURIComponent('MYAPIKEY'),
'user': encodeURIComponent('me#mydomain.com'),
'category': encodeURIComponent('MY_CATEGORY')
},
function(response){
alert('received response');
}
);
});
end then decode the data on backend. Hope it helps someone.

Resources