I have been working on a shopping cart that the user can add/remove order items as they please and am returning an updated sub-total via a webservice using jQuery $.ajax
Here is how I am calling the webservice and setting the sub-total with the response.
//perform the ajax call
$.ajax({
url: p,
data: '{' + s + '}',
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#cartRow" + orderID).find(".subTotal").text(sTotal);
},
failure: function() {
//if the orer was not saved
//console.log('Error: Order not deleted');
}
});
The response I am getting seems perfectly fine:
{"d":"128.00"}
When I display the total on the page it displays as 128 rather than 128.00
I am fully sure it is something very simple and silly but I am so deep into it now I need someone with a fresh brain to help me out!!
Cheers :)
EDIT
I am also using $.ajaxSetup to set the correct contentType:
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
dataFilter: function(data) {
var msg;
if (typeof (JSON) !== 'undefined' &&
typeof (JSON.parse) === 'function')
msg = JSON.parse(data);
else
msg = eval('(' + data + ')');
if (msg.hasOwnProperty('d'))
return msg.d;
else
return msg;
}
});
That is because the value is treated as a number, while you want it treated as a string.
When you are using '.. .text(sTotal)', you are actually calling the .toString() method on the Number object wrapping the primitive sTotal. And since this is a whole number, it displays it without decimals.
You need to use a format the number as a string prior to calling .text(foo) for the number to be formatted like that.
This will give you two decimals
var a=1/3;
a = a.toString();
switch(a.lastIndexOf(".")){
case -1:
a+=".00";
break;
case a.length-2:
a+="0";
break;
default:
a=a.substring(0, a.indexOf(".") + 3);
}
alert(a);
I don't see anywhere in this code where you access the d property of the response.
Perhaps you mean to do this?
$("#cartRow" + orderID).find(".subTotal").text(sTotal.d);
// --------------------------------------------------^^
EDIT
Ok, I see the problem. You're returning JSON but not defining a dataType in the $.ajax() call. This means that jQuery sees your application/json mimetype and interprets the response as JSON. 128.00 in JSON is a Number, not a String. However, "128.00" would be a String.
In order to keep this working, You need to format the response before printing it (as others have suggested), or adjust your endpoint to return a valid JSON string.
Here's my test to prove the solution
<div id="test">
Subtotal <span class="subTotal"></span>
</div>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript" charset="utf-8">
google.load("jquery", "1.4.2");
</script>
<script type="text/javascript" charset="utf-8">
$.ajax({
url: 'test.php',
data: {},
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#test").find(".subTotal").text(sTotal);
}
});
</script>
and test.php
<?php
header( 'Content-type: application/json' );
echo '128.00';
Output
Subtotal 128
But when I change test.php to be this
<?php
header( 'Content-type: application/json' );
echo '"128.00"';
The expected output is generated
Subtotal 128.00
Or, you could alternatively tell jQuery to treat the response as text by specifying a dataType parameter, for example
$.ajax({
url: 'test.php',
data: {},
dataType: 'text', // <---- here
success: function(sTotal) {
//order was updated: set span to new sub-total
$("#test").find(".subTotal").text(sTotal);
}
});
EDIT 2
Ok, after messing with this some more, I see what's going on. The dataFilter handler you defined converts the response into JSON itself, and in this case, returns the string 128.00. However, jQuery still applies the intellgent-guessed dataType (which is JSON) to this value before sending it to the success handler.
There are a multitude of ways to fix this, all of which depend on what other AJAX calls your application relies on this setup for. The quick-fix I applied in my test was to do this
$.ajaxSetup({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{}",
// define the text data type so that we return data.d, jQuery doesn't parse it as JSON again
dataType: 'text',
dataFilter: function(data) {
data = $.parseJSON( data ); // Use jQuery's parsing
if (data.hasOwnProperty('d'))
{
return data.d;
}else{
return data;
}
}
});
But that may not work across the board for you
Please try this:
$("#cartRow" + orderID).find(".subTotal").text(sTotal.toFixed(2));
HTH
Related
I wan't to get string instead of word. how can i do this.
php file code
<?php
$countries = array("Afghanistan", "Albania");
$response=array("countries"=>$countries);
echo json_encode($response);
?>
html file
$(document).ready(function(){
$("button").click(function(
$.ajax({
type:'GET',
url:'./countries.php',
data:{countries:true},
cache:false,
async:false,
success:function(data){
var str="";
for(i=0;i<data.length;i++)
{$("tbody.new").append("<tr><td>" + data[i] + "</td><td></td> <tr>");}
result is like this a f g a every word is separate line
You haven't specified the accepted data type in ajax options object. That's why you are getting a json string instead of parced json data.
Change your code as shown below:
$(document).ready(function(){
$("button").click(function(
$.ajax({
type:'GET',
url:'./countries.php',
data:{countries:true},
dataType: 'json',
cache:false,
async: true,
success:function(data){
var str = "";
for (i = 0; i < data["countries"].length; i++){
$("tbody.new").append("<tr><td>" + data["countries"][i] + "</td><td></td><tr>");
}
}
}
You need to set dataType:'json' since you aren't setting appropriate content type header on server.
This will tell $ajax to parse response to array or object in success callback.
Then you want to access the proper property of the response object which will be data.countries which is an array
Also async:false is a terrible practice. It should never ever be used and you should be seeing deprecation warnings in browser console
I need to pass data from HTML page to PHP page But without data callback ....
i'm used two method but One of them did not succeed
1)
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x },
success: function(data)
{
alert("success! X:" + data);
}
});
2)
$.post("getClassStudent.php",
{
},
function(data){
$("#div_id.php").html(data);
}
);
as i can understand, you just want to send info to a php script and don't need the response, is that right?
try this
$.post("phpexample.php", {voteid:x});
or simply remove the "succes" function from the equation if you feel more confortable using $.ajax instead of $.post
$.ajax({
type: "POST",
url: 'phpexample.php',
data: {voteid: x }
});
your fisrt example is correct, the second is not well formed.
more info:
http://api.jquery.com/jquery.post/
EDIT: to help you some more :)
<button type="button" id="element-id">click</button>
<button type="button" class="class-name">Click</button>
$(document).ready(function(){
//if you are marking ans element by class use '.class-name'
$(".class-name").click(function(){
$.post("getClassStudent.php");
});
//if marking by id element use '#id-name'
$("#element-id").click(function(){
$.post("getClassStudent.php");
});
});
be carefful with the markings, for debuggin try to use "console.log()" or "alert()" so you can see where is the problem and where the code crushes.
var formData = {
'voteid' : 'x',
};
$.ajax({
type : 'POST',
url : 'phpexample.php',
data : formData, // our data object
dataType : 'json',
encode : true
}).done(function(data) {
console.log(data);
});
Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.
Here is my JSON array:
msg={"userid":"82","0":"82","first":"A","1":"A","last":"B","2":"B","email":"w#w.com","3":"w#w.com","username":"n","4":"n","password":"o","5":"o","hash":"3242","6":"3242","active":"0","7":"0","date":"0","8":"0","holding":"","9":"","ip":"0","10":"0","attempts":"0","11":"0"}
now I am trying to get the different parts but nothing I try works. I have tried
msg.first //returns undefined
msg['first'] // returns undefined
msg[0] // returns that first bracket {
I am sure this can be easily solved, I just dont know what the issue is. This array is output by some php using json_encode(). If that code is relavent please let me know and I will put it up. Thanks.
If msg[0] returns the first bracket, your JSON is somehow being interpreted as a string. This can be easily fixed through jQuery's parseJSON():
msg = $.parseJSON(msg);
I tried like this.
<html>
<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
function display(data) {
$.each(data, function(key,value) {
$('#userDetails').append('<li>' + key + " : " +'<span class="ui-li-aside">'+ value +'</span></li>');
});
}
$(document).ready(function() {
msg= {"userid":"82",
"0":"82",
"first":"A",
"1":"A",
"last":"B",
"2":"B",
"email":"w#w.com",
"3":"w#w.com",
"username":"n",
"4":"n",
"password":"o",
"5":"o",
"hash":"3242",
"6":"3242",
"active":"0",
"7":"0",
"date":"0",
"8":"0",
"holding":"",
"9":"",
"ip":"0",
"10":"0",
"attempts":"0",
"11":"0"}
display(msg);
});
</script>
</head>
<body>
<div id="userDetails"></div>
</body>
</html>
I've run into this problem a bunch when using the jQuery ajax function. You need to specify that you're expecting a json response.
If you make this call, the data variable returned will be a string.
$.ajax({
type: "POST",
url: '/controller/function',
data: {
'parameter_name' : value,
},
success: function(data){
console.log(data.blah); // Undefined
},
});
But if you specify the dataType as "json," the data variable will be a json object.
$.ajax({
dataType: "json", // Have to include this
type: "POST",
url: '/controller/function',
data: {
'parameter_name' : value,
},
success: function(data){
console.log(data.blah); // Defined!!!
},
});
I am trying to parse an xml response using jQuery and just output an element the a page but i am unsuccessful in this.
Below is the code that I am using for the response & parsing of it.
$.ajax({
url: UCMDBServiceUrl,
type: "POST",
dataType: "xml",
data: soapMessage,
success: UCMDBData,
crossDomain: true,
contentType: "text/xml; charset=\"utf-8\""
});
alert("Sent2");
return false;
}
function UCMDBData(xmlHttpRequest, status, msg)
{
alert("Came back1");
$(xmlHttpRequest.responseXML).find('tns:CIs').each(function()
{
alert("Came back2");
$(this).find("ns0:CI").each(function()
{
alert("Came back3");
$("#output").append($(this).find("ns0:ID").text());
});
});
}
I am receiving alerts for "Came back1" but it doesnt appear to be going any further. Below is the XML Response that I am trying to parse using my above jquery code. The text that I am ultimately trying to return out of the response is in this element
<?xml version='1.0' encoding='utf-8'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"><soapenv:Header />
<soapenv:Body>
<tns:getFilteredCIsByTypeResponse xmlns:ns0="http://schemas.hp.com/ucmdb/1/types" xmlns:ns1="http://schemas.hp.com/ucmdb/ui/1/types" xmlns:ns2="http://schemas.hp.com/ucmdb/1/types/query" xmlns:ns3="http://schemas.hp.com/ucmdb/1/types/props" xmlns:ns4="http://schemas.hp.com/ucmdb/1/types/classmodel" xmlns:ns5="http://schemas.hp.com/ucmdb/1/types/impact" xmlns:ns6="http://schemas.hp.com/ucmdb/1/types/update" xmlns:ns7="http://schemas.hp.com/ucmdb/discovery/1/types" xmlns:ns8="http://schemas.hp.com/ucmdb/1/types/history" xmlns:tns="http://schemas.hp.com/ucmdb/1/params/query">
<tns:CIs>
<ns0:CI>
<ns0:ID>4d030502995a00afd989d3aeca2c990c</ns0:ID>
<ns0:type>nt</ns0:type>
<ns0:props>
<ns0:strProps>
<ns0:strProp>
<ns0:name>name</ns0:name>
<ns0:value>prodoo</ns0:value>
</ns0:strProp>
</ns0:strProps>
<ns0:booleanProps>
<ns0:booleanProp>
<ns0:name>host_iscomplete</ns0:name>
<ns0:value>false</ns0:value>
</ns0:booleanProp>
</ns0:booleanProps>
</ns0:props>
</ns0:CI>
</tns:CIs>
<tns:chunkInfo>
<ns0:numberOfChunks>0</ns0:numberOfChunks>
<ns0:chunksKey>
<ns0:key1 />
<ns0:key2 />
</ns0:chunksKey>
</tns:chunkInfo>
</tns:getFilteredCIsByTypeResponse>
</soapenv:Body>
</soapenv:Envelope>
So my question is that how do I properly parse the data? I believe the code syntax is correct but I am not getting the expected returned results. I would appreciate any help, thanks.
EDIT
I have modified my code to the following like the suggestion, but still no luck:
$.ajax({
url: UCMDBServiceUrl,
type: "POST",
dataType: "xml",
data: soapMessage,
success: UCMDBData,
crossDomain: true,
contentType: "text/xml;"
});
alert("Sent2");
return false;
}
function UCMDBData(data, textStatus, jqXHR) {
alert("Came back1");
$(data).find('tns:CIs').each(function () {
alert("Came back2");
$(this).find("ns0:CI").each(function () {
alert("Came back3");
$("#output").append($(this).find("ns0:ID").text());
document.AppServerForm.outputtext.value = document.AppServerForm.outputtext.value + "http://localhost:8080/ucmdb/cms/directAppletLogin.do?objectId=" + $(this).find('ns0:ID').text() +"&infopane=VISIBLE&navigation=true&cmd=ShowRelatedCIs&interfaceVersion=8.0.0&ApplicationMode=ITU&customerID=1&userName=admin&userPassword=admin";
});
});
}
When I execute the only alert message i receive back is "Came back1" which means that the code is still not going through the xml properly with jquery. Any other suggestions?
The namespace-scoped names need to be handled a little differently. According to this answer:
jQuery XML parsing with namespaces
you would need to use an attribute selector [#nodeName=tns:CIs] instead.
You may need to drop the "#" for jQuery versions later than 1.3. Another suggestion is to escape the colon: .find('tns\:CIs'), which is hacky because it conflates the syntactic prefix with the semantic namespace (the uri). So if the prefix changed this method would break. A more correct answer will recognize the mapping of prefix to namespace uri. The jquery-xmlns plugin for namespace-aware selectors looks promising in that respect.
Your jQuery success function is of the wrong form. It needs to be of the form
function UCMDBData(data, textStatus, jqXHR) {
alert("Came back1");
$(data).find('tns:CIs').each(function () {
alert("Came back2");
$(this).find("ns0:CI").each(function () {
alert("Came back3");
$("#output").append($(this).find("ns0:ID").text());
});
});
}
In addition, in your $.ajax function, change the contentType line to be contentType: "text/xml" instead of what you have before (assuming that you're sending XML to the server).
See the jQuery.ajax() documentation for more information.
Based on your comment, why do something crazy with jQuery? Just use javascript itself!
var open = '<ns0:ID>';
var close = '</ns0:ID>';
var start = obj.indexOf(open) + open.length;
var end = obj.indexOf(close);
var result = obj.slice(start, end);
Here's a jsfiddle that shows it in action.
Probably the right syntax would be
success: function(xml) {
$(xml).find('tns:CIs').each(function() {
......