I'm trying to convert the json result into xml type. However, it doesn't seems to work. Couldn't find out what's wrong. Please help.
The code is:
<script src="../Jquery Autocomplete/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../Jquery Autocomplete/jquery.json-2.2.min.js" type="text/javascript"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$(".openModalLink").click(function()
{
var start=$(this).parent().parent().find(".start").val();
var end =$(this).parent().find(".end").val();
$.ajax(
{
type: "POST",
url: "frmCollegeExamScheduleMst.aspx/ServerSideMethod",
data: "{'paraml': '" + start + "','param2': '" + end + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success:function(result)
{
var xmlDoc = $.parseXML(result);
var xml = $(xmlDoc);
var customers = xml.find("Table");
var data = new Array();
var i =0;
$.each(customers, function ()
{
//do something
});
},
error: function(err) {
alert('Error:' + err.responseText + ' Status: ' + err.status);
}
});
});
});
When you specify dataType: "json" the response is converted to a JSON object and does not remain a string.
Try removing the parameter.
Try like this:
success: function(result) {
var xmlDoc = $.parseXML(result.d);
...
}
Notice the result.d. I guess your ASP.NET PageMethod looks like this:
[WebMethod]
public static string ServerSideMethod(string param1, string param2)
{
DataSet ds = ...
return ds.GetXml();
}
This string is JSON serialized. In order to retrieve it on the client the ASP.NET infrastructure adds the d parameter:
{"d":"some xml here"}
Another thing that you should absolutely change in your code is replace:
data: "{'paraml': '" + start + "','param2': '" + end + "'}"
with:
data: JSON.stringify({ param1: start, param2: end })
to ensure that your request parameters are properly JSON encoded. Think for example what will happen if start = 'foo\'bar'. You will end up with:
data: {param1: 'foo'bar', param2: 'baz'}
which as you can see completely breaks your JSON.
If the response from your AJAX request is xml then you should set it accordingly.
$.ajax({
data: {paraml: start, param2: end},
dataType: "xml",
success:function(result) {
var $xml = $(result);
}
});
No need for contentType nor concatenating in data.
Related
I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});
This is my ajax:
$("#submit").on("click",function()
{
$("#add_car_form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "text",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html("<br />JSON: " + data );//this outputs
{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}
}
});
document.getElementById("add_car_form").reset();
return false;
});
});
I simply echo from php script like this: echo $return["json"]; and it will output like this:
{"car_name":";ll","car_maker":"njk","car_type":"nkj","passanger":"1","rate":["89","67","45","34","23"],"action":"test"}
How do append to a div in html table form like this?
Car Name: name
Car Maker: maker
......
try this in your success function
data = jQuery.parseJSON( data ); //parse data if this is text other wise use data directly. hope this is a text param in your case.
var out = '<table>';
$.each(data, function( key, value ) {
out += '<tr><td>'+key+': '+ value +'</td></tr>';
});
out += '</table>';
//append out to your div
$(".the-return").html(out);
You should not create a form submit handler inside a click handler as it could create multiple listeners for single click event.
I think you could just encode the data use json_encode in the server side then, accept the response as json in the client using dataType: 'json' then
$("#submit").on("click", function () {
var $form = $("#add_car_form")
var data = {
"action": "test"
};
data = $form.serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "add_car_submit.php", //Relative or absolute path to response.php file
data: data,
success: function (data) {
$(".the-return").html("Car Name" + data.car_name + '<br />Car Maker' + data.car_maker); //Add more properties here
}
});
document.getElementById("add_car_form").reset();
return false;
});
Script:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
$.load("#BuildedBox")
}
});
}
build.php:
include_once("$_SERVER[DOCUMENT_ROOT]/db.php");
$block_id = $_GET['block'];
$building = $_GET['building'];
$nick = $_GET['nick'];
echo"$block_id - $building - $nick";
index.php:
<a href=\"#\" onClick=\"buttonBuild(k152, digger, Name);\" >[BUILD]</a>
<div id="BuildedBox"></div>
seems my script wont work. what i have done wrong?
check this out
function buttonBuild(id, building, nick)
{
$.ajax({
type: "POST",
url: "BlockEditor/build.php",
data: 'block_id=' + id + '&building=' + building + '&nick=' + nick,
cache: false,
success: function(response)
{
alert("Record successfully updated");
/***************/
$("#BuildedBox").html(response);
/***************/
}
});
}
var weightd = $("#weight").val();
var user_id = 43;
$.ajax({
type: "POST",
url:"<?php bloginfo('template_directory')?>/ajax/insert.php",
data: { weight:weightd,user_ids:user_id},
success:function(result){
$("#result1").html(result);
});
<div id="result1">Result div</div>
change $.load("#BuildedBox") to $("#BulderBox").html(response).
When you ask the script for data via ajax, the data provided gets into the "response" variable. As you want to write this data into the div, you must use the ".html" method.
Easier using "load" in this way:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php?block_id=" + id + "&building=" + building + "&nick=" + nick);
}
The "load" method loads data from the server and writes the result html into the element: https://api.jquery.com/load/
EDIT:
As #a-wolff says in the comment, to use POST in load, you should construct like this:
function buttonBuild(id, building, nick)
{
$("#BuildedBox").load("BlockEditor/build.php",{
block_id:id,
building:building,
nick:nick
});
}
I am trying to call web service through a JS but anyhow it doesnt get call.
I am trying to make sum of 2 number.
Page contains of 3 textbox and it has it text set hard codded
as
:
<form id="form1" runat="server">
<div>
<asp:TextBox ID="Text1" Text="5" runat="server">
</asp:TextBox>
<asp:TextBox ID="Text2" Text="2" runat="server">
</asp:TextBox>
<asp:TextBox ID="Text3" runat="server">
</asp:TextBox>
</div>
</form>
My code are as follows:
<script type="text/javascript">
$(document).ready(function () {
debugger;
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "C:/Users/hp/Documents/visual studio 2010/Projects/WebApplication3/WebApplication3/WebService1.asmx/sum",
data: "{'a':'" + $('input[id$=Text1]').val() + "','b':'" + $('input[id$=Text2]').val() + "'}",
dataType: "json",
success: function (data) {
alert(data);
var results = eval('(' + data.d + ')');
if (results == "success") {
$('input[id$=Text3]').val(data);
//$('span[id$=lblErr]').hide();
}
else {
$('span[id$=lblmsg]').hide();
// $('span[id$=lblErr]').show();
}
},
error: function () {
alert('Error');
}
});
});
</script>
WebService name WebForm1.aspx
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string sum(string a, string b)
{
string json = "";
int sum = Convert.ToInt32(a) + Convert.ToInt32(b);
System.Web.Script.Serialization.JavaScriptSerializer oSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
json = oSerializer.Serialize(sum);
return json;
}
}
It showing Error box on each run. Kindly assist me through it. Thanks.
Your using a absolute URL to your webservice. You should be using a relative server path like this snippet suggests:
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: "{ your: 'data' }",
dataType: "json",
url: "WebService1.asmx/sum",
success: function (data) {
alert(data); //use your data object
}
});
Your URL is wrong. It should be of this form:
url: "/WebService1.asmx/sum"
And to make sure it always resolves to the right path, you can instead do this:
url: '<%=ResolveClientURL("~/WebService1.asmx/sum%>")'
Also, in your success handler, you don't need to do:
var results = eval('(' + data.d + ')');
You can simply do:
var result= data.d;
Finally, in your WebMethod, you don't need to use the JavascriptSerializer at all. You can simply do:
int sum = ...
return sum;
The response is already in JSON format. No need to serialize it twice.
url: "C:/Users/hp/Documents/visual studio 2010/Projects/WebApplication3/WebApplication3/WebService1.asmx/sum",
This needs to be an HTTP URL, and the HTML document that the JavaScript is running in needs to be on the same origin.
data: "{'a':'" + $('input[id$=Text1]').val() + "','b':'" + $('input[id$=Text2]').val() + "'}",
Your JSON is invalid. Strings must be delimited with " characters, not ', and user input could break it easily.
Do not generate JSON by mashing strings together. Use the built-in functions which will do it for you, correctly.
data: JSON.stringify({
a: $('input[id$=Text1]').val(),
b: $('input[id$=Text2]').val()
}),
When I execute this JavaScript file in Firefox;
<script type="text/javascript" >
$(function () {
$(".comsubmit").click(function () {
var comsn = $("#comsn").val();
var comrn = $("#comrn").val();
var compic = $("#compic").val();
var comment = $("#comment").val();
var eventid = $("#eventid").val();
var dataString = 'comsn=' + comsn + '&comrn=' + comrn + '&compic=' + compic + '&comment=' + comment + '&eventid=' + eventid;
if (comment == '') {
alert('Must Type Comment to Post Comment');
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="assets/uploading.gif" />Loading Comment...');
$.ajax({
type: "POST",
url: "comments_post.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
}
return false;
});
});
</script>
I get this error
Error: missing } in XML expression
Line: 31, Column: 2
Source Code:
}); });
The arrow points inbetween the first semi colon and the space.
What can I do to fix this error?
Few remarks about your code:
You don't need the cache: false option as you are performing a POST request.
Instead of concatenating the parameters into dataString let jQuery handle formatting and escaping:
$.ajax({
type: "POST",
url: "comments_post.php",
data: {
comsn: comsn,
comrn: comrn,
compic: compic,
comment: comment,
eventid: eventid
},
success: function (html) {
$("ol#update").append(html);
$("ol#update li:last").fadeIn("slow");
$("#flash").hide();
}
});
Check the Content-Type header returned by comments_post.php. If it is not properly set (for example if it is set to text/xml), jQuery might try to parse the returned XML, while in reality you are returning HTML.
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script>
<font family="Arial" color="red" ><span style="font-size: x-small;"><script style="text/javascript" src="http://sites.google.com/site/attachanu/home/scrollingnew.js?attredirects=0&d=1"> </script>
<script style="text/javascript">
var nMaxPosts = 20;
var sBgColor;
var nWidth;
var nScrollDelay = 75;
var sDirection="left";
var sOpenLinkLocation="N";
var sBulletChar="•";
</script>
<script style="text/javascript" src="http://hackerz7.blogspot.com/feeds/posts/default?alt=json-in-script&callback=RecentPostsScrollerv2">
</script></span></font>
I think the HTML you are passing from the Ajax call is not properly formated. Can you add an alert and make sure it looks OK?