I have written a Phonegap application and I would like to know how can I submit a form to Django using Javascript or Jquery. I have already implemented a JSON API using Tastypie.
Can anybody provide me with some ideas, or any guidance on how to implement such a function?
You just have to do ajax call to tastypie api url in the below format.
$.ajax({
type: 'POST',
url: site_url+'api/v2/user/login/',
data: '{"username": "developer", "password":"imagine2"}',
processData: false,
crossDomain: true,
success: function (response, textStatus, xhr) {
console.log('jquery worked');
//results=JSON.stringify(response);
setCookie( "sessionid", response.sessionid);
setCookie( "app_version", response.app_version);
window.location.href = 'home/';
$('#overlay').hide();
},
error: function (res) {
msg = (res.responseText) ? res.responseText : res.statusText;
console.log(msg+",res.status="+res.status);
alert(msg);
},
dataType: "json",
contentType: "application/json; charset=utf-8"
});
Also you need to enable cross domain.
There are multiple ways to do this. Since you are using an API with tastypie I would suggest not submitting the form itself, but extracting the form data before submitting the form with JavaScript. On submit you pass the data you want to submit in the request body to your API endpoint.
As an example you could have an api endpoint for blog entries, lets say its http://example.com/api/v1/entry. Considering your API allows cross-domain requests (e.g. via CORS) you could do something simple as this to "submit" your form (e.g. creating a new entry):
$('#myForm #mySubmitButton').click(function() {
$.post('http://example.com/api/v1/entry', $('#myForm').serialize(), function(data) {
// deal with the response data
}
});
I am not sure tastypie supports this kind of data structure. A little longer version of this could be to do something like this (here I am sure tastypie does support it), which submits the data as a JSON:
$('#myForm #mySubmitButton').click(function() {
var data = {'title': $('#myForm #titleInput').val(), 'description': $('#myForm #descriptionInput').val()};
$.post('http://example.com/api/v1/entry', data, function(data) {
// deal with the response data
}
});
This examples do not deal with form validation, error handling etc.. You could have look into tastypie validation for more details and potentially also add frontend specific validation with HTML5. I would also suggest you to use a more sophisticated JavaScript framework like AngularJS for single page apps like a PhoneGap app. JQuery will bloat your app soon, when it grows.
Related
I'm working in a contact form for our clients that creates webpages with us with their own domain. We offer them a hosting and a web editor to create their websites. When they create a contact form in their websites, whoever that visit their websites and fills a form to contact them, it is sent to our platform and it sends a email to our client notifying him/her that someone filled his/her contact form.
To make it work, we are using a jsonp ajax call in our clients webpage to send the form to our platform, which performs the email template and sends the email.
The problem now is that our clients asked to add a input field type to allow whoever that visits their page to attach a file to the form, so they can see an attached file in the contact notification email, but I can't find a way to do it using jsonp because it uses GET method to create a crossdomain request and everthing I've serarched in Stackoverflow, talks about using a POST method to send files with a form and get form data as new FormData().
Here is the code I had before trying the implementation:
var $form = $('form');
$form.submit(function(e){
e.preventDefault();
$.ajax({
url: url,
dataType: "jsonp",
data: $form.serialize(),
beforeSend: function () {
$form.data('allowSending', false); // To prevent multiple sendings while processing
},
success: function(data) {
alert(data.message);
$form.data('allowSending', true);
}
});
});
This is the code that I've tried, but it's not handled as expected:
var $form = $('form');
$form.submit(function(e){
e.preventDefault();
$.ajax({
url: url,
processData: false,
contentType: false,
dataType: "jsonp",
data: new FormData(this),
beforeSend: function () {
$form.data('allowSending', false); // To prevent multiple sendings while processing
},
success: function(data) {
alert(data.message);
$form.data('allowSending', true);
}
});
});
When it sends the filled form with the code that I've tried (the second one), tries to send the data as an object through the URL, like: ?callback=jQuery111107622947758095266_1459251318335&[object%20FormData]&_=1459251318336
How can I solve this?
Thanks in advance.
Regards.
PS: To make things harder, forms are completely dynamic, so if a solution is passing parameters manually, etc. it must be in a dynamic way with a for loop.
The short answer is that you can't.
Your attempt is failing because, since JSONP makes a GET request, contentType is ignored and data is treated as a string (since you said processData: false).
As you say, JSONP works by encoding everything in the URL. While it is possible to use the File API to read the content of the file and convert it into a base64 encoded string, that will exceed URL length limits for all but the smallest of files which makes it impractical.
Stop using JSONP. It is a, frankly dirty, hack that was used to sneak around the Same Origin Policy. We now have CORS, which is a standard, non-hacky, highly flexible method to selectively disable the same origin policy. One of the advantages of its flexibility is that you can make cross-origin POST requests using it.
I'm trying to operate two servers.
MVC Web API service.
MVC Web application.
The idea is that the web application renders a page filled with javascript requests, which populate the actual data from the remote API service. The web application will never itself touch the database, or the API service (besides setting up authorisation tokens initially).
What is the best way to achieve this?
So far I've been using JQuery AJAX requests, attempting to use JSONP. However I always get "x was not called" exceptions.
$.ajax({
url: '#(ViewBag.API)api/customer',
type: 'get',
dataType: 'jsonp',
jsonp: false,
jsonpCallback: function (data) {
debugger;
// code to load to ko
},
error: function (xhr, status, error) {
alert(error.message);
}
});
Also the jsonpCallback function is called before the request is sent, so I assume its actually trying to call a function to generate a string? If I reform this request:
window.success = function (data) {
debugger;
// code to load to ko
};
... with jsonpCallback being "success", I still get the same error (but the success method is never called.
Any ideas? Thanks.
Edit: I've gotten started on the right course from this:
http://www.codeproject.com/Tips/631685/JSONP-in-ASP-NET-Web-API-Quick-Get-Started
Added the formatter, and replaced jsonCallback with success, like a normal ajax. However this only seems to work for get. I cannot delete or update. :(
Can you get it to work using the $.getJSON method?
$.getJSON( "ajax/test.json", function( data ) {
//handle response
});
Have you fired up developer tools in IE and watched the network traffic to see precisely what is being sent and returned?
Can any one please tell me how to send data to web service using jquery and receive data from web service?
If we are using web service should we need to use url to get records?
$j.ajax({
type: "GET",
url: "testing.json",
dataType :'json',
contentType:'application/json; charset =utf-8',
success:function(data)
{
$j.each(data, function(index,element){
$j('#json').append("<li class='ui-li ui-li-static ui-btn-up-c ui-corner-top ui-corner-bottom ui-li-last'>"+element+"</li>");
});
}
})
});
I am developing web application using jQuery mobile.
Can any one please tell me how to send data to web service using jquery
Put it in a data property on the object you pass as the first argument to ajax().
How you format the data will depend on the particular web service.
Your existing code claims that it will be JSON so the data you pass to data should be a string representation of a JSON Text.
You will need to change the type to POST in order to do this though. The content-type request header describes the request body and you don't get one of those with a GET request.
(If the web service does not expect to receive JSON data then you will need to change the code to represent whatever it does expect).
and receive data from web service?
Read it from the first argument to the callback function you pass to the success function.
If it is in a known data format (XML, HTML or JSON), then jQuery should automatically parse it. Note that you have dataType: 'json' which will override whatever the server says it is sending back and try to parse it as JSON data regardless.
If we are using web service should we need to use url to get records?
Yes. URLs are how web server end points are identified.
a liitle example to get data from a web service using jquery ajax call
function GetData() {
$.ajax({
type: "POST",
url: "Members.asmx/GetMemberDetails",//your webservice call
data: "{'MemberNumber': '" + $("#txt_id").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnGetMemberSuccess,
error: OnGetMemberError
});
}
function OnGetMemberSuccess(data, status) {
//jQuery code will go here...
}
function OnGetMemberError(request, status, error) {
//jQuery code will go here...
}
Example: Introduction to using jQuery with Web Services
I have been given a url of type xxxx.xxxxx.com as well as a key of type FGHyehgvc787vbhj
in order to gain read-only access to an sql database and retrieve data from it using javascript.
I have no prior experience with databases and maybe my question will sound completely stupid but I was wondering how can I combine the above information in order to get access to the database (e.g. do an ajax call and retrieve data from it..)
I'm familiar with doing ajax calls to a webpage and getting data from it using jQuery, as in :
$.ajax(/*url of website*/, function (data)
{
var dataRetrieved = $(data);
// do something with the data retrieved...
});
so I was wondering whether there is something equivalent to the above when it comes to making an ajax call to a database, using however a key.
Thank you for any help, and please delete this post if you find it completely pointless and excuse me in advance for that by the way.
It is usually very bad design to allow client side code to interact with your database in any way. This can be a huge security issue. Generally you will want your server side code to do this (e.g PHP, node, etc.). You would send a request to your server with client side code, and the server side code would do the actual work of updating the database.
you can create a wcf service and call that service through ajax, that wont be huge security issue.
try this
$.ajax({
cache: false,
type: "GET",
async: false,
data: {},
url: http:xxxxxxxxxxxx.svc/webBinding/Result?metaTag=" + meta,
contentType: "application/json; charset=utf-8",
dataType: "json",
crossDomain: true,
success:function(result){},
error: function(){alert(err);}
});
Use this
$.ajax({
url: 'path/to/server-side/script.php', /*url*/
data: '', /* post data e.g name=christian&hobbie=loving */
type: '', /* POST|GET */
complete: function(d) {
var data= d.responseTXT;
/* Here you can use the data as you like */
$('#elementid').html(data);
}
});
Hope this helps...
I have created a web service and saved its .wsdl file. I want to consume this service in my HTML file by providing its URL.
Can anybody tell me how to call the URL in HTML and use it?
Like its done here.
http://www.codeproject.com/Articles/14610/Calling-Web-Services-from-HTML-Pages-using-JavaScr/
The only difference is my web service does not have an extention like "asmx?wsdl".
Does that makes any difference.
I followed that tutorial too but it does not produce any output.
Thank You////
You definitly should get familiar with AJAX.
You could use the ajax functionalities provided by jQuery. That's the easiest way, I assume. Take a look at http://api.jquery.com/jQuery.ajax/
You can use this like
$.ajax({
url: "urltoyourservice.xml"
dataType: "xml",
}).done(function(data) {
console.log(data);
});
HTML itself cannot consume a webservice. Javascript ist definitely needed.
The existence of your WSDL File looks like you are probably using a XML format as the return of the web service. You have to deal with XML in javascript. Therefore take a look at Tim Downs explanation.
But keep in mind, that your web service URL must be available under the same domain as your consumption HTML-File. Otherwise you'll receive a cross-site-scripting error.
yes you can use ajax but keep in mind you wont be able to make a request across domains. Consuming web services should be done in server side.
To further gain more knowledge about this, read How do I call a web service from javascript
function submit_form(){
var username=$("#username").val();
var password=$("#password").val();
var data = { loginName: username, password:password };
$.ajax( {
type: "POST",
url:"Paste ur service address here",
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
success: function(data){
var value = data.d;
if(value.UserID != 0){
alert.html('success');
}
},
error: function (e) {
}
});
}
Try this it will help