Changing a div/text using AJAX - javascript

Hello there I am totally new to ASP.NET and learning it to my own. I am good at Java J2EE (Struts2 Framework)! I know how can i update or change any control/text inside any div element using struts2 and ajax code.
My Problem
Actaully, I'm trying to do the same thing in ASP.NET just for the learning! Suppose that I have a Default.aspx page with the javascript and ajax methods as:
<head runat="server">
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script type="text/javascript">
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "text/html;charset=utf-8",
success: function(msg) {
$("#changer").html(msg);
}
});
}
</script>
<title>Untitled Page</title>
</head>
<body>
<div id="changer">//this is the div i want to update it using ajax
Hello Old Text
</div>
<input type="button"id="but" value="Hello Changer" onclick="Change()"/>
</body>
and suppose that I have my temp.aspx as:
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<div id="changer">
Hello New Text
</div>
</body>
I just want to know if this is possible in ASP.NET because with Java I am familiar with such an operation but I don't know why this is not working in case of ASP.NET!
Any hints or clues are favorable for me, Please don't mind for my question because I am totally new to ASP.NET but I am good at Java
Thanks in Advance!

dataType must define as html like this;
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "html",
success: function(msg) {
$("#changer").html(msg);
}
});
}
From jQuery Docs;
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String
Additionally, you can inspect errors using error.
function Change() {
$.ajax({
type: "GET",
url: "temp.aspx",
dataType: "html",
success: function(msg) {
$("#changer").html(msg);
},
error: function(xhr, status, err) {
console.error(status, err.toString());
}
});
}
This is not related to ASP.NET or other web frameworks. It is just related to jQuery and Javascript. jQuery didn't recognise this "text/html;charset=utf-8". If you didn't use dataType, the ajax request worked successfully. It is just verification and result is interpreted according to dataType. For example, you are returning a JSON and the mime type of the your endpoint is not json (considering its mime type is html) just changing of the dataType as "JSON" you can parse the result as object.
I wrote a little script, in first example, I set dataType as HTML and in other example, I set dataType as JSON.

You could add a generec handler called Temp.ashx wich return the new text.
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write("Hello New Text");
}
In your ajax call you need to specify you are expecting a text.
<script type="text/javascript">
function Change() {
$.ajax({
type: "GET",
url: "temp.ashx",
dataType: "text/plain",
success: function(msg) {
$("#changer").html(msg);
}
});
}
</script>

Related

Html post is not working

I am trying to make a simple website that posts information to an api and shows output as alert. But I can't get any alert.
Code:
<!DOCTYPE html>
<html>
<body>
<b>Enter name</b>
<br>
<input type="text" id="name">
<br>
<button id="button1">Submit</button>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<script>$('#button1').click(function(){
$.ajax({
type: "POST",
url: "http://(api url)",
data :{name:$('#name').value()},
});
});
</script>
</body>
</html>
You're very close, there are a few issues in your code. Your data: {} throws a syntax error since .value() doesn't exist it's instead .val() that you're looking for.
To display the results after a successful request to the API endpoint, you need to have a success callback which can be written as below. I am using a test dummy POST endpoint at the URL https://jsonplaceholder.typicode.com/posts in the code below, replace it as needed with the actual URL you're requesting :
$('#button1').click(function(){
$.ajax({
type: "POST",
url: "https://jsonplaceholder.typicode.com/posts",
data :{name:$('#name').val()},
success: function (data) {
alert(data);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<b>Enter name</b>
<br>
<input type="text" id="name">
<br>
<button id="button1">Submit</button>
If you want to show the result in alert, in that case you need to handle the success callback like following.
$.ajax({
type: 'POST',
url: "http://(api url)",
data: {name:$('#name').val()}
success: function(result) { alert(result) }
});
success Type: Function( Anything data, String textStatus, jqXHR jqXHR
) A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter or the dataFilter callback
function, if specified; a string describing the status; and the jqXHR
(in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the
success setting can accept an array of functions. Each function will
be called in turn
Note that, value() is nothing in jQuery, you need to use val()
I suggest, along with success, you should also handle the error like following.
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Some error occurred");
}
For more details on $ajax, I suggest you to go through the documentation here

pass js variable to php using ajax on the same page

this is my html code:
<form id="form" action="javascript:void(0)">
<input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font-size: 23px;font-weight: normal;color:white;margin-top:-3px;text-decoration: none;background-color: rgba(0, 0, 0, 0.53);'>
</form>
this is my javascript code:
function showtemplate(temp)
{
$.ajax({
type: "POST",
url: 'ajax.php',
data: "section="+temp ,
success: function(data)
{
alert(data);
}
});
}
this is my ajax.php file:
<?php
$ajax=$_POST['section'];
echo $ajax;
?>
The above html and javascript code is included in a file named slider.php. In my index file i have included this slider.php file and slider.php is inside slider folder. So basically index.php and slider.php are not inside the same folder.
Javascript code alerts the data properly. But in my php code (ajax.php file) the value of $_POST['section'] is empty. What is the problem with my code. I tried googling everything and tried a few codes but it still doesn't work. Please help me out
Try this instead:
$.ajax({
type: "POST",
url: 'ajax.php',
data: { 'section': temp},
success: function(data)
{
alert(data);
}
});
It is quite possible that your server does not understand the string you have constructed ( "section="+temp ). When using ajax I prefer sending objects since for an object to be valid it requires a certain format.
EDIT1:
Try this and let me know if it doesn't work either:
$.post('ajax.php', {'section': temp}, function(data}{
alert(data);
});
Add jquery plugin(jQuery library) ,then only ajax call works
for eg
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
check your input data , whether it contain '&,/' charators,then use encodeURIComponent()
for Ajax Call Eg:
var gym_name = encodeURIComponent($("#gym_name").val());
$.ajax({
type: "POST",
url: "abc.php",
data:string_array,
success: function(msg) {
console.log(msg);
}
});
In abc.php
<?php
$id = $_POST['gym_name'];
echo "The id is ".id;
?>
Give a try to the following (although I cannot work out why #Grimbode's answer is not working):
$("#submit-reg").on( "click", function() {
$.ajax({
type: "POST",
url: 'ajax.php',
data: {'section': 'anniversary'},
success: function(data)
{
alert(data);
}
});
});
Note: I don't know what your underlying code is doing. However, I would suggest not using HTML element properties to handle events for numerous reasons, but separate the JS/event handling appropriately (separate js file(s) (recommended) or inside <script> tags). Read more...

Parse json using ajax

I receive a json file from a python server, which I try to parse using ajax to display the values according to the categories(e.g.data_provider,census) in separate drop down menus .But i constantly get the following error:
Uncaught Error: Syntax error, unrecognized expression: [{"data_provider":"census","data_year":"2010","data_series":"sf1","tb_name":"h1","summ_level":"160"},{"data_provider":"census","data_year":"2010","data_series":"sf1","tb_name":"p1","summ_level":"050"}]
Kindly help me out ! Below is the code I wrote.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
function codeAddress() {
var ajax = $.ajax({
//data : params,
type : "GET",
crossDomain: true,
dataType: "json",
//jsonp: "callback",
//callbackParameter: "callback",
//contentType : "application/x-www-form-urlencoded",
url : "http://0.0.0.0:8080/"
});
ajax.done(function() {
var response=ajax.responseText;
var json = jQuery.parseJSON(response);
$(json).each(function(i,val){
$.each(val,function(k,v){
console.log(k+" : "+ v);
});
});
});
ajax.fail(function() {
alert("fail");
});
ajax.always(function() {
alert("done");
});
}
</script>
</head>
<body id="b1" onload="codeAddress();">
</body>
</html>
Because you're setting datatype to json, I'd guess you do not need to parse the JSON yourself. Please note that the parsed response is provided in the done method's first argument, see this example from the jQuery docs:
$.ajax({
url: "http://fiddle.jshell.net/favicon.png",
})
.done(function( data ) {
console.log( "Sample of data:", data.slice( 0, 100 ) );
});
If you're already using jQuery, just let them do the grunt work for you!
$.getJSON("http://0.0.0.0:8080/", function(json){
// do your JSON work here
});
If for whatever reason you can't use $.getJSON, in your $.ajax request, set a success callback function like the one i have over here.

Jquery ajax with google app engine post method

Just trying to learn using ajax with appengine,started with the post method,but it does not work.
This is my HTML Code for the page
<html>
<head>
<title> Hello </title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
success: function(data,status){
alert("Data" + data +"status"+status);
}
});
});
});
</script>
</head>
<body>
<form method="post" action="/test">
<input type="submit" id="subbut">
</form>
<div id="success"> </div>
</body>
</html>
Here goes my python code to render the above html code , its handler is /test1
from main import *
class TestH1(Handler):
def get(self):
self.render('tester.html')
And this is the python script to which AJAX request must be sent to,handler is /test.
from main import *
import json
class TestH(Handler):
def post(self):
t=self.request.get('name')
output={'name':t+" duck"}
output=json.dumps(output)
self.response.out.write(output)
Expected behavior is that when i click on submit button,i get an alert message saying "Hola duck" , get nothing instead.
Any help would be appreciated as i am just starting with AJAX and Jquery withGAE
At first, I suppose you should suppress default behavior of form submitting when you press submit button by adding "return false" to the .click function. But I suppose it would be better to use just
<input type="button" id="subbut">
instead (even without form).
Then you should add "dataType: 'json'" to your ajax call to tell jQuery what type of data you expect from server. Doing this you will be able to get response data by property names like "data.name". So:
var data={"name":"Hola"};
$(document).ready(function(){
$('#subbut').click(function(){
$.ajax({
url: '/test',
type: 'POST',
data: data,
dataType: 'json',
success: function(data,status){
alert(data.name);
alert("Data" + data +"status"+status);
}
});
return false;
});
});
and it would be better if you set appropriate content type header to your response:
response.headers = {'Content-Type': 'application/json; charset=utf-8'}
self.response.out.write(output)

How to post zk url through javascript

I am using JavaScript with ZK framework. In some scenario, I want to post URL from JavaScript in ZK. How to call ZUL file from JavaScript?
Is there any way to post URL using JavaScript in ZK?
Assume you have a content.zul and you want to get it via ajax in javascript, this can be done by using zk built in jquery in zul page or using jquery in pure html.
zul sample:
<zk>
<script><![CDATA[
function loadContent () {
jq.ajax({
url: "content.zul",
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
jq('$content').html(response);
}
});
}
]]></script>
<div id="content"
onCreate='Clients.evalJavaScript("loadContent();");' />
</zk>
html sample:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
window.onload = function () {
$.ajax({
url: "content.zul",
type: "post",
// callback handler that will be called on success
success: function(response, textStatus, jqXHR){
$('#content').html(response);
}
});
}
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>

Categories

Resources