getAttribute() inside ajax jQuery - javascript

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.

Related

error with split: split is not a function

I have this javascript code that performs an ajax request on button click.
$('#allinea').click(function(e){
e.preventDefault();
var password = $('#password').val();
$.ajax({
type: "POST",
url: "db_align.php",
data: {password:password},
complete: function(data){
data1=data.split("|");
if(data1[0]=="Successo"){
$("#per_all").fadeTo(200,0.1,
function(){
$(this).find('img').attr("src",'../images/ok.png');
$(this).find('.right').html(data1[1]).promise().done(function(){
$(this).fadeTo(900,1);
});
});
}else if(data1[0]=="Errore"){
$("#per_all").fadeTo(200,0.1,
function(){
$(this).find('img').attr("src",'../images/alert.png');
$(this).find('.right').html(data1[1]).promise().done(function(){
$(this).fadeTo(900,1);
});
});
}
}
}); //chiudo $.ajax
});
The php page returns "Successo|Allineamento riuscito" and I see it correctly in firebug but the js returns an error:
Type error: data.split is not a function
data1=data.split("|");
I use this code everywhere in my app without any inconvenient. What am I doing wrong this time?
For what I see btw this is not an array so this should work without any inconvenient!
jQuery will return a jqXHR here, which means that instead of accessing data directly, you will probably need to do data.responseText.
Exo's answer is perfect. It will allow you to edit the raw text.
If you know the type of data returning, you can (must) set it explicitly. jQuery will then programmatically convert data for you in the correct format.
dataType: json for JSON,
dataType: text for plain text
More can be found in the documentation.
You should update your complete method to done for success condition and fail for when the request fails.
complete is deprecated as of version 1.8, it's replaced with always, which returns a data or jqXHR object. When success complete will return a data object according to the functionality of done.

How to get a JSON string result from a database for later use

I am working on the backend for a webpage that displays EPG information for TV channels from a SQlite3 database. The data is provided by a PHP script echoing a JSON string. This itself works, executing the php program manually creates a JSON string of this format
[{"id":"0001","name":"RTL","frequency":"626000000"},{"id":...
I want to use these objects later to create HTML elements but the ajax function to get the string doesn't work. I have looked at multiple examples and tutorials but they all seemed to be focused more on having PHP return self contained HTML elements. The relevant js on my page is this:
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
However the channelList variable remains empty when inspected via console.
What am I doing wrong?
Please ensure that your PHP echoing the correct type of content.
To echo the JSON, please add the content-type in response header.
<?php
header(‘Content-type:text/json’); // To ensure output json type.
echo $your_json;
?>
It's because the variable is empty when the program runs. It is only populated once AJAX runs, and isn't updating the DOM when the variable is updated. You should use a callback and pass in the data from success() and use it where you need to.
Wrap the AJAX call in a function with a callback argument. Something like this:
function getChannels(callback){
$.ajax({
url: 'channellookup.php',
dataType: "json",
success: function(data) {
console.log(data);
if (typeof(callback) === 'function') {
callback(data);
}
},
error: function(data) {
if (typeof(callback) === 'function') {
callback(data);
}
}
});
}
Then use it when it becomes available. You should also use error() to help debug and it will quickly tell you if the error is on the client or server. This is slightly verbose because I'm checking to make sure callback is a function, but it's good practice to always check and fail gracefully.
getChannels(function(channels){
$('.channelDiv').html(channels.name);
$('.channelDiv2').html(channels.someOtherProperty);
});
I didn't test this, but this is how the flow should go. This SO post may be helpful.
EDIT: This is why frameworks like Angular are great, because you can quickly set watchers that will handle updating for you.

jquery post ajax syntax not working

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.

Passing array through ajax

I'm fairly new to the jQuery execute on the same page stuff. So far I have been passing only single values trough ajax which is working fine. Now, I need to pass an array which is created by checkboxes through ajax.
My form html, dynamically created by php:
<input type=checkbox class=box name=box[] value=".$row['DoosID']." />
My jQuery:
var BackorderDate = $("#BackorderDate").val();
var Box = $(".box").val();
if( (TerugleverDatum == "") ){
$("#backorderresult").html(" * Some Error .").fadeIn("Slow").fadeOut(3000);
} else {
$("#backorderresult").fadeOut();
$.ajax({
type :'POST',
url :'./backorder.php',
data : box : Box,
backorderdate: BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
}
My PHP:
$boxlist = json_encode($box);
foreach($boxlist as $boxvalue){
// Do something with every value
}
this gives me a javascript error on submit saying box is not defined.
change this:
data : box : Box, backorderdate: BackorderDate, // invalid way of sending
to this:
data : {box : Box, backorderdate: BackorderDate}, // valid way
data
Type: PlainObject or String
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs.
More Info
Why don't you try enclosing all the data values in a open and close curly braze( { and } ) .
Else it will conflict with the syntax of $.ajax method.
I think it is causing the problem.
You are sending data value in wrongly manner -
The data property should always be a JavaScript object. It's properties are serialized into a regular query string (for GET requests), or a normal post body parameter string (for POST requests). This serialized string is then sent to the server, along with the AJAX request.
On the server you can read the properties of the data object as if they were sent as simple request parameters, via either GET or POST. Just like if the properties had been fields in a form.
Try this :
$.ajax({
type :'POST',
url :'./backorder.php',
data : 'box='+Box+'&backorderdate='+BackorderDate,
dataType:"json",
success: function(data){
// Do Something
}
});
For more information see jQuery Ajax
You might want to refer to the php file like this: url :'../backorder.php' (double dots). At least, that's how I do it always.

jQuery $.post - how to call a callback function if $.post fails and or if the response is not the type you expect

Here's the thing, I have a jquery click event handler, that calls a post on click.
The type that it expects (4th parameter of $.post()) is "json". However, on the
server side; there are two responses to the post: it's either json or html response. The problem is, if it returns html, the callback function isn't called (because the $.post expects a json?).
How can I react to this? I want something that if the server side script returns a json, execute callback, otherwise do another. Is that possible? Can I check the response type with $.post?
You'll most likely want to use the generic jquery.ajax function. In particular the dataType: 'text' property should allow you to parse your return value in whatever method works for you. You can also use the parseJSON function
$.ajax({
url: 'url',
type: 'post'
dataType: 'text',
success: function(text) {
if (json) {
var obj = $.parseJSON(text);
} else {
var html = $(text);
}
}
});

Categories

Resources