Jquery ajax not getting called in asp.net2.0? - web-services

I am using Asp.Net 2.0.I am trying to learn webservice and call that webservice using jquery ajax method
The problem is jquery ajax is not working properly and i could not find out where i have gone wrong.
Here's my jquery code
<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Button1").click(function(){
$.ajax({
type:"POST",
url:"/WebService.asmx/GetDateTime",
data:"{}",
contentType:"application/json; charset=utf-8",
dataType:"json",
succss: function(msg){
alert("Success");
},
failure:function(response){
alert("Error");
}
});
});
});
</script>
Heres my webservice
[WebMethod]
public string GetDateTime()
{
return DateTime.Now.ToString();
}
Heres the HTML part
<form id="form1" runat="server">
<div>
<input type="button" id="Button1" style="width:75px" value="Submit" />
<span id="output"></span>
</div>
</form>

If your button generated dynamically use "live" to bind event
$("#Button1").live("click", function(){...});
Note : make sure your id is same as generated in page, ASP.NET changes id to 'ct00_button1' check in browser inspect element

Related

Facebook API check if user likes a certain page

I develop a quiz that needs from users to log in to Facebook and like my Facebook page. How can I check if user already likes the page?
`
<?php header('Access-Control-Allow-Origin: *'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<style>
#fblikebutton { display: none; }
</style>
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script><script src="https://cdn.jsdelivr.net/npm/bootstrap#4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
</head>
<body>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_EN/sdk.js#xfbml=1&version=v15.0" nonce="oLBFXWMb"></script>
<section class="main">
<div class="container">
<div id="status"></div>
<div id="fbloginbutton">
<div data-scope="public_profile,email" data-onlogin="checkLoginState();" class="fb-login-button" data-width="" data-size="large" data-button-type="continue_with" data-layout="default" data-auto-logout-link="false" data-use-continue-as="false"></div>
</div>
<div id="fblikebutton">
<div class="fb-like" data-href="https://www.facebook.com/{MyFbPage}" data-width="" data-layout="standard" data-action="like" data-size="large" data-share="false"></div>
</div>
<div id="quiz_container"><!-- here is the quiz --></div>
</div>
</section>
<script>
function statusChangeCallback(response) { // Called with the results from FB.getLoginStatus().
console.log('statusChangeCallback');
console.log(response); // The current login status of the person.
if (response.status === 'connected') { // Logged into your webpage and Facebook.
$('#fbloginbutton').fadeOut();
$('#fblikebutton').fadeIn();
afterLogin();
} else { // Not logged into your webpage or we are unable to tell.
$('#fblikebutton').fadeOut();
$('#fbloginbutton').fadeIn();
$('#status').html('For fill the quiz, please login and follow our page:<br><br>');
}
}
function checkLoginState() { // Called when a person is finished with the Login Button.
FB.getLoginStatus(function(response) { // See the onlogin handler
statusChangeCallback(response);
});
}
window.fbAsyncInit = function() {
FB.init({
appId : '{MyAppID}',
cookie : true, // Enable cookies to allow the server to access the session.
xfbml : true, // Parse social plugins on this webpage.
version : 'v15.0' // Use this Graph API version for this call.
});
FB.getLoginStatus(function(response) { // Called after the JS SDK has been initialized.
statusChangeCallback(response); // Returns the login status.
});
};
function afterLogin() { // Testing Graph API after login. See statusChangeCallback() for when this call is made.
FB.api('/me', function(response) {
$('#status').html('Thank you for login, ' + response.name + '!');
if (user does not like our page yet) {
$('#status').html('Please follow our page to fill the quiz.<br><br>');
} else {
afterFollow();
}
});
}
function afterFollow() {
$('#quiz_container').fadeIn(); // Show the quiz
};
</script>
</body>
</html>
`
And a smaller problem, this Facebook login button parameter doesn't work:
data-scope="public_profile,email"
How can I fix this? Thank you!
I'ver tried /user/likes/ method, but returns nothing, and I think this is not the solution...
`
FB.api(
"/{user-id}/likes",
function (response) {
if (response && !response.error) {
alert('So you like this');
}
}
);
`

got problem in the ajax form submission code

<form action="" method="post" class="f-color" id="email-form">
{% csrf_token %}
<label>Name</label>
<input type="text">
<label>From</label>
<input type="email">
<label>Message</label>
<button type="submit">Sent</button>
</form>
<div class="mt-5" id="spin" style="display: none;">
<div class="loader"></div>
</div>
<div id="msg"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on("submit", "#email-form", function(event){
event.preventDefault();
$('#spin').show();
$.ajax({
url: "{% url 'contact' %}",
type: "POST",
data: $("#email-form").serialize(),
success: function(data){
$("#spin").hide();
if(data.status == "success"){
$("#msg").html("<p class='alert alert-success'>we will get back to you as soon as possible</p>" );
$("#email-form").reset();
}
}
})
})
})
</script>
using this code I can submit the form successfully, but after the form submission the message(msg) not showing, the 'if condition statement' is perfectly working (for the testing I gave the alert, the alert was worked)
another problem is form reset, for this I'm using
$("#email-form").reset();
but the form dose't reset
how can I solve these problems
try
$('#email-form')[0].reset();
https://stackoverflow.com/a/3786702/8640027
I got a solution for the resetting form after the ajax form submission
$("#email-form").trigger("reset");

How can i send a post request using vue to django without getting a 403 error?

Im trying to send information using a post request of Vue, but every time i try i get an error 403 58
my django service is ok , i think that the problem is for the csrf token but i dont know how to send it with vue
var vue = new Vue({
el:"#app",
data: {
nombre:"",
apellido:"",
password:""
},
methods:{
enviar:function () {
data = {
"nombre":this.nombre,
"apelldio":this.apelldio,
"password":this.password
};
this.$http.post("http://localhost:8000/usuarios\\",data).then(function (data, status, request) {
if(status ==200){
console.log(data);
}
},function () {
console.log("Error");
});
}
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<link rel="stylesheet" href="https://bootswatch.com/4/flatly/bootstrap.min.css">
</head>
<body>
<h1>Insertar un nuevo usuario </h1>
<table id = "app">
<tr><td>Nombre:</td><td><input type="texte" class="form-control" v-model="nombre"></td></tr>
<tr><td>Apellido:</td><td><input type="texte" class="form-control" v-model = "apellido"></td></tr>
<tr><td>Password:</td><td><input type="texte" class="form-control" v-model="password"></td></tr>
<tr> <td> <button type="button" id = "enviar" class="btn btn-info" #click="enviar">Enviar</button></td></tr>
</table>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
{% csrf_token %}
<!-- here goes the scripts of vue and vue resource!>
You could use a method that involves fetching the csrf token with javascript and then passing it to the POST request as a header as mentioned here in Django documentation. In that link there is also examples about fetching the csrf token value.
Also, if the endpoint does not require this kind of protection you can disable it like in this example.
You can use something like this:
{% csrf_token %}
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue-resource/0.1.13/vue-resource.min.js"></script>
<script>
var csrf = document.querySelector('[name="csrfmiddlewaretoken"]').value;
Vue.http.interceptors.push(function (request, next) {
request.headers['X-CSRF-TOKEN'] = csrf;
next();
});
// Or maybe
Vue.http.headers.common['X-CSRF-TOKEN'] = csrf;
</script>
You can also use it like this, for example:
<script>
var csrf = '{{ csrf_token }}';
Vue.http.headers.common['X-CSRF-TOKEN'] = csrf;
// Or other way
// Vue.http.interceptors.push(...);
</script>
Note: I'm no django developer but gave you the basic idea, so check the doc for more info.

url should not change on submitting a form

i have this Django application in which when user request for "localhost:8000/time/ ,it is shown html form input.html.
<head>
<!-- paste this in your footer -->
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(),
type: $(this).attr('POST'), // "post"
url: $(this).attr('/poi/'), // "/poi/"
success: function(response) {
// do something here
}
});
return false;
});
});
</script>
<!-- add jquery or it won't work -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
</head>
<body>
<form action="/poi/" method = "post">
<!---------
first name :<input type ="text" name ="fname">
last name:<input type ="text" name ="lname">
------>
enter a days :<input type ="text" name ="days">
<br>
<input type=submit name="submit" onclick="submit_function(); return false;">
</form>
</body>
when form is submitted user sees response.html page and URL is changed to "localhost:8000/poi/ is shown having
urls.py
urlpatterns = patterns('',
(r'^hello/$', hello),
('^time/$', current_datetime),
('^poi/$', next_datetime),
)
views.py
def current_datetime(request):
return render_to_response('input.html')
def next_datetime(request):
now = datetime.datetime.now()
now_day = now.day
now_month = now.month
now_year = now.year
return render_to_response('response.html', {'now_day': now_day, 'now_month'}}
now i have to do same thing but the url should not change from "localhost:8000/time/ to "localhost:8000/poi/
but it should be "localhost:8000/time/
how to accomplish that?
You have to use ajax to accomplish this
With jquery it would look something like
<form id="myForm"> ... </form> <!-- add an id to your form -->
<!-- paste this in your footer -->
<script type="text/javascript">
$(document).ready(function() {
$('#myForm').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(),
type: $(this).attr('method'), // "post"
url: $(this).attr('action'), // "/poi/"
success: function(response) {
// do something here
}
});
return false;
});
});
</script>
<!-- add jquery or it won't work -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
and it should work out of the box
this is with an anonymous function, but you can put the code inside a named one and then add it to the button:
<input type="submit" onclick="submit_function(); return false;" />
it's basically the same

sent image data using jquery ajax won't be saved using ModelForm

I'm going to edit an ImageField using jquery ajax,so I've used jquery form plugin,this is the code:
<form id='form_upload' action="." method="POST" enctype="multipart/form-data">
<input type='file' id='id_HeadImage' name='id_HeadImage' />
</form>
<script typr="text/javascript">
var options = {
dataType: 'xml',
url: '{% url DrHub.views.editNews param1,param2 %}',
}
$('#form_upload').ajaxSubmit(options);
</script>
in <head>:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
and in server side :
if ('id_HeadImage' in request.FILES) and (request.FILES['id_HeadImage']):
gForm=GalleryForm(request.POST,request.FILES,instance=newsInstance.gallery_ptr)
if gForm.is_valid():
gForm.save()
as U can see I'm going to edit ImageField of a model named Gallery.
How can I do this?
this is Gallery Model:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery",blank=True,null=True)
While gForm.is_valid() returns True,but It won't be saved and Image of HeadImage Field won't be changed.
Note : I've checked this in firebug and I'm sure that data is sent and request.FILES has value.
what's wrong here?
EDIT : I've worked based on this article: http://www.laurentluce.com/posts/upload-to-django-with-progress-bar-using-ajax-and-jquery/
Try ajaxForm in place of ajaxSubmit:
`
<form id='form_upload' action="." method="POST" enctype="multipart/form-data">
<input type='file' id='id_HeadImage' name='id_HeadImage' />
</form>
<div id="empty">
</div>
<script type="text/javascript">
function handleResult(responseText, statusText, xhr, $form) {
//do stuff here
};
jQuery(document).ready(function() {
var options = {
target: '#empty',
// Not sure if you should use xml here, I would suggest json . ,
dataType: 'xml',
url: '{% url DrHub.views.editNews param1,param2 %}',
success: handleResult,
}
$('#form_upload').ajaxForm(options);
});
</script>`