XML error in JavaScript file - javascript

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?

Related

Unable to send multiple data parameters with jQuery AJAX

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);
}
});

Get the value of input tag for Ajax Request

<input type="text" id="autocomplete">
<ul></ul>
<script>
var value;
var wikiapi;
$('#autocomplete').on('keypress',function(e){
if(e.which==13){
value=$(this).val();
wikiapi="https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles="+value+"&format=json";
$.ajax({
url:wikiapi,
crossDomain:true,
dataType:"jsonp",
xhrFields: {
withCredentials: true
},
success: function(data){
var links=data.query.pages[171166].iwlinks;
var title=data.query.pages[171166].title;
$.each(links,function(i,val){
$('ul').append('<li><a href='+val.url+'>'+title +'</a></li>');
});
console.log(data.query.pages[171166].iwlinks[0].url);
}
});
}
});
</script>
Hi, I am trying to retrieve the value from input tag. But It seems the method I've tried is not working. The value is not passed to the wikiapi var at all. Hence the ajax request cannot proceed. Can anyone point out the problem please.
I've also tried "..$('#autocomplete').on('click',function(){
........} also but not working.
I did a quick check inside the success function as to what data was storing. After just a couple of examples I noticed the key (the six digits) were different for each example. Therefore, var links=data.query.pages[171166].iwlinks; and var title=data.query.pages[171166].title; will only work for test. In order to get the keys of data.query.pages you need a for loop. I've also added $('ul').empty() to empty out whatever was in the list. Here's the code needed to get it to work:
var value;
var wikiapi;
$('#autocomplete').on('keypress', function(e) {
if (e.which == 13) {
value = $(this).val();
wikiapi = "https://en.wikipedia.org/w/api.php?action=query&prop=iwlinks&iwprop=url&titles=" + value + "&format=json";
$.ajax({
url: wikiapi,
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
},
success: function(data) {
$('ul').empty();
for (var key in data.query.pages) {
if (data.query.pages.hasOwnProperty(key)) {
var links = data.query.pages[key].iwlinks;
var title = data.query.pages[key].title;
}
}
$.each(links, function(i, val) {
$('ul').append('<li><a href=' + val.url + '>' + title + '</a></li>');
});
}
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="autocomplete">
<ul>
</ul>
When I paste your code to jsfiddle with this success function success: function(data){ console.log(data) } the ajax call works fine.
So you have an Problem to handle your result from the API.
I have rewritten your code to make it more readable:
$(document).on('keypress', '#autocomplete', function (e) {
if (e.which === 13) {
var options = {
url: "https://en.wikipedia.org/w/api.php",
data: {
action: "query",
prop: "iwlinks",
iwprop: "url",
titles: $(this).val(),
format: "json"
},
crossDomain: true,
dataType: "jsonp",
xhrFields: {
withCredentials: true
}
};
$.ajax( options ).done(function (data) {
var html ='';
$.each(data.query.pages, function(pageKey, pageValue) {
$.each(pageValue.iwlinks, function(linkKey, linkValue) {
html += '<li>' + pageValue.title + '</li>';
});
});
$('ul').html(html);
}).fail(function (err) {
console.log(err);
alert('Ooops');
});
}
});
I have extracted the ajax options and added the GET parameter from the URL to them. I also iterate over result pages and the link object to generate the listitems.
Here can you read about the jQuery ajax method and the options: https://api.jquery.com/jQuery.ajax/

how to reload a div with form content using jquery ajax

I am working on creating an online visitor chat software using PHP and MySQL. What am i trying to do is load the page on clicking the submit button
id for submit button: send
id for visitor:vid
id for chat:cid
Below is the code snippet for Ajax request made by the code but it is not working.
I have put few alerts within the codes to test whether the function is working fine or not and the function is not working.
Please help me out.
Any other method is also accepted
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("#send").click(function() {
var cid = $("#cid").val();
var vid = $("#vid").val();
var usermsg = $("#usermsg").val();
var submitmsg = $("#submitmsg").val();
var dataString = 'cid='+ cid + '&vid=' + vid + '&usermsg=' + usermsg;
alert(datastring);
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
success:function(result){
alert(result);
}});
});
</script>
Wrap your click function under
jQuery(document).ready(function($){
// your click event here
});
Change your code to:
<script type="text/javascript">
$(document).ready( function() {
$("#send").click(function() {
var cid = $("#cid").val();
var vid = $("#vid").val();
var usermsg = $("#usermsg").val();
var submitmsg = $("#submitmsg").val();
var dataString = 'cid='+ cid + '&vid=' + vid + '&usermsg=' + usermsg;
alert(datastring);
$.ajax({
type: "POST",
url: "chat.php",
data: dataString,
success:function(result){
alert(result);
}});
});
});
</script>

Jquery call PHP response failed

I have two files one php and one html, the html file serves as the users interface where the users input their queries, the php files serves as the process or where the event will happen then it will return them to the html file for the output. According to my friend the best way to link the two is using jquery or ajax which I'm not quite sure. I tried to link them using this code but it didn't work if you can help me find my mistake I would gladly appreciate it.
HTML File
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#setVal').on('click', function () {
var form = $('.buildaddress').not('#formatted_address');
var vals = form.map(function () {
var value = $.trim(this.value);
return value ? value : undefined;
}).get();
$('#formatted_address').val(vals.join(', '));
</script>
when I added this part the link didn't work
<script>
$('#Compare').click(function(e) {
e.preventDefault();
var address = $('#address').val();
var formatted_address = $('#formatted_address').val();
console.log(address);
console.log(formatted_address);
$.ajax({
type: 'POST',
url: 'Corrections.php',
data: {
var1: address,
var2: formatted_address
},
success: function(data) {
document.getElementById('cor').value = data;
}
});
});
});
</script>
PHP file
<?php
$str1 = $_POST['var1'];
$str2 = $_POST['var2'];
$tempArr;
$var2;
$ctr=0;
echo "Input: $str1\n";
echo "Output: $str2\n";
?>
You have an extra }); in your script. Just remove the extra }); in your second script, your code will work
<script>
$('#Compare').click(function(e) {
e.preventDefault();
var address = $('#address').val();
var formatted_address = $('#formatted_address').val();
console.log(address);
console.log(formatted_address);
$.ajax({
type: 'POST',
url: 'Corrections.php',
data: {
var1: address,
var2: formatted_address
},
success: function(data) {
document.getElementById('cor').value = data;
}
});
});
//}); should be removed
</script>

Trying to convert json to xml but shows error

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.

Categories