jquery post ajax syntax not working - javascript

i want to pass a post json value to another page. however when i add a json datatype on my post ajax parameter, the javascript code is not functioning. however if i remove the json parameter its working. im just new to jquery. thanks in advance for your help.
<script type="text/javascript">
$('#login_form').submit(function(evt) {
evt.preventDefault();
var url = $(this).attr('action');
var postData = $(this).serialize();
$.post(url, postData, function(o) {
alert(o);
}, "json");
});
</script>

Since you have put "json" in your $.post, your url should return json data. If it is not returning a json then your function will not fire.
Since your JavaScript is functioning without json datatype, you may not returning a json as a response.
Check this JSFiddle, since it returns a JSON, you can see the alert.

Related

Using AJAX return JS variable to JSP

I have a simple JS function which retrieves some data from the URL in browser. Call to that JS function is made in a JSP. The JS function is called from within a tag in JSP.
JS Function:
function parseURL(){
var info = "some value", // This is retrieved from the browser URL which is my.JSP
$.ajax({
method: post,
url: my.jsp // This is the same URL (browser URL) from which I am getting information, so I just send back to it
data: { information: info} )}
.done({
alert("Success");
})
});
}
When I try to retrieve the value in a scriplet in JSP, it is returning null. What am I doing wrong? Any help will be appreciated. Thank You.
i can suggest you to follow these steps and find an approach to your case !!
first in your function
function parseURL(){
var info = "some value", // This is retrieved from the browser URL which is my.JSP
$.ajax({
method: post,
url: anotherPage.jsp // This is the same URL (browser URL) from which I am getting information, so I just send back to it
data: { information: info} )}
.done({
$("div or section where you want to inject the result").html(data);
})
});
}
and in the anotherPage.jsp try to have something like this :
//jsp header and stuff and the data you want to get back such as scriplet or expression just the data that would be injected by the function ahead
if you could post the my.jsp and the anotherPage.jsp that could be helpful

getAttribute() inside ajax jQuery

In this ajax call, I am calling a servlet in which I set an attribute value.
Now, once I receive the response I am trying get the value of the attribute.
I am struggling for the getAttribute value code.
<script type="text/javascript">
$('#PartNo').keypress(function(event){
var keycode = (event.keyCode ? event.keyCode : event.which);
if(keycode == '13'){
varPartCode = $('#PartNo').val();
$.ajax({
type: "Post",
url: "submit",
data: "PartCode="+varPartCode,
success: function(result){
alert($(this).attr("DescAttr"));
}
});
}
});
</script>
I got the below function from the net. But it is not working. Requesting your help in this.
$(this).attr("DescAttr")
Below is my code for setting the attribute value in servlet.
String varPartDescription = descBean.getPartDescription();
request.setAttribute("DescAttr",varPartDescription);
this in the success function isn't an HTML element. It does not make sense to pass it as an argument to the jQuery function.
Java attributes have nothing to do with HTML attributes. Setting an attribute on the Java request object isn't going to give any data back to the browser.
You need to put the data in the response and then read it from the argument to the success function in JavaScript that you have named result.
For example (and I don't do Java so I just cribbed this from the first tutorial I found on Google):
res.setContentType("text/plain");
PrintWriter pw=res.getWriter();//get the stream to write the data
pw.println(descBean.getPartDescription());
and
success: function(result){
alert(result);
}
For more complex data, consider outputting JSON instead.

Retrieve JSON encoded data in AJAX callback

This is the result when I do console.log(data) within my AJAX callback
{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}
but when I do data['image'] or data['url'], it can't retrieve the value correctly. I also tried data[0]['image'] to no avail
So I guess data is returned from a ajax request. Your can use the following code to convert string to object:
data = JSON.parse(data);
If you are using jQuery to do the ajax request, you can add dataType: "json" to the ajax option. In this way, there's no need to convert data.
Your data in callback is JSON Object,then
var image=data.image;
var url=data.url;
have you tried data.image and data.url?
also try var x = eval(data);
then x.image and x.url
Be careful of eval() on untrusted data though!!
You need to parse it to Json
var retrieved = ......;
var json = JSON.parse(retrieved);
and then just use:
var image = json.image;
var url = json.url;
Usualy this code from jQuery API's page works great:
$.ajax({
dataType: "json",
url: url,
data: data,
success: success
});
The success callback is passed the returned data, which is typically a JavaScript object or array as defined by the JSON structure and parsed using the $.parseJSON() method. It is also passed the text status of the response.
However, you must remember about the same origin policy as well as the about the correct server response's content type. For json response it should be application/x-javascript or at least text/json.
javascript does not have associative arrays, You should use a javascript object like
var data = JSON.parse(data)
and then you can acces it by
data.image and data.url
If You are getting string as a response then use like below.
var response = '{"image":"http://placehold.it/290x120","url":"http://www.google.com.my"}';
var data = eval("("+response +")");
console.log(data["image"]);
console.log(data["url"]);

submitting a form using $.ajax

I'm calling this function when the dom is ready on $().submit
but it seems not working there is no response from server
$(function(){
$("#logingform").submit(function(){
var values =$(this).serialize();
call_server("../php/login.php",values);
});
});
function call_server(URL,DATA)
{
$.ajax(
{
type:'POST',
url : URL,
data : DATA,
dataType:'json',
success:function(response){
$("#d1").append(response);
}
}
);
}
nothing seems to get back from the server.
server code
<?php
$email = $_POST['loginemail'];
$password =$_POST['loginpassword'];
echo json_encode(array('returned_val' => 'yoho'));
There is an extra semi colon following your ajax option:
data : $(this).serialize();,
vs correct
data : $(this).serialize(),
You do not need to parse the json that is returned, since you already have dataType:'json' defined in the ajax options.
$("#d1").append($.parseJSON(response));
That is not necessary.
If you want to show the response object as a string, then you need to stringify it instead:
$("#d1").append(JSON.stringify(response));
Also, you have a syntax error on this line:
data : $(this).serialize();,
Remove the ;.
Your data for a POST should be in json format, so rather than $(this).serialize(), use $(this).serializeArray() for your data. This will pass those values for POST body rather than in the querystring.

Ajax Json : XML can't be the whole program.

I am trying to make a simple ajax request(cross-domain) using Json.
Here's my code :
$("#unsub").live('click', function() {
$.ajax({
url: urly ,
type:'GET',
dataType:"json", //type JSON
success: function(data) { //do something
}
});
});
However, the response I am getting from the server is a html Div
<div id="handler"></div>
On button click I get an error on success "XML can't be the whole program".
Please note : i have to USE json to make the call no matter what and the call will always return a div. using jquery 1.3.2
Any help would be highly appreciated.
Thanks for the time.
Most of the time you need to provide the remote server a "callback" in url for the jsonp to be wrapped in. If API is not set up for JSONP, you need to use other methods to egt the JSOn with javascript. First check that API will deliver jsonp, and if so what params to put in the url

Categories

Resources