using jQuery mobile with ajax - javascript

I am trying to print a jQuery mobile thing using ajax but it doesn't encode the result as jQuery mobile is supposed to do.
This is a simplified version of the part of the javascript code that is supposed to do so:
<script type="text/javascript">
function changePage(task) {
var objText = "";
$.ajax({
type: "POST",
url: "DataFetch.aspx/FetchData",
data: '{id: ' + <%=Session["loggedID"] %> + ', task: ' + task + ' }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var obj = JSON.parse(response.d);
if (task == 2)
{
objText += "<div data-role='collapsible'><h3>click me</h3><p>text</p></div>";
}
document.getElementById('content' + task).innerHTML = objText;
}
});
}
</script>
How can I make it work? (when I write it explicitly in the html or outside the ajax functions it works but I need it to work with json)

Try changing
document.getElementById('content' + task).innerHTML = objText;
to
$('#content' + task).HTML(objText).enhanceWithin();
The enhanceWithin() call tells jQM to enhace the new content you added via AJAX:
http://api.jquerymobile.com/enhanceWithin/

Related

I want to set a url inside my ajax call back function

I want to make a clickable link in my ajax success response. But I could not do this.
<td id="attachment"></td>
function DoAction(id) {
$.ajax({
type: "get",
url: "/view_message",
data: "id=" + id,
dataType: 'json',
success: function(data) {
if (data) {
var text = "No Files There !";
$('#myModal').modal('show');
$('#subject').text(data.subject);
$('#body').text(data.body);
$('#created_at').text(data.created_at);
if (data.attachment) {
$('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
} else {
$('#attachment').text(text);
}
}
}
});
}
I want to display a clickable link in my .
I always encounter this when using ajax calls so;
Update your code from this.
$('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
To This.
$(document).find('#attachment').html('<a href="files/' + data.attachment + '" />click</a>');
if the code doesn't work add a console.log("working") function to see if your code is really reaching the success function.
I hope it helps.

JQuery click 1 does nothing

I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.
For the full app: https://codepen.io/xcidis/full/KvKVZb/
var reference = [];
function random() {
$.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
});
}
$("button").click(function(){
random();
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
Your rest of the code ran before your ajax push the value to reference variable.
https://www.w3schools.com/xml/ajax_intro.asp
You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously
$("button").click(function(){
$.when( $.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
})).then(function() {
console.log(reference)
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
});

Returning Response in jquery ajax function

Getting problems in Response.d , based on the result which is returning by the checkusers() function I am saving the values. If the entered name is in already in database it should say "User already exists", if it is not in database it should create a new record.
But I am not getting the correct value from (response), I observed that Console.log(response.d) giving me correct values like 'true' or 'false'. I tried everything I know like-
changing async:"false"
var jqXHR = $.ajax({ and returning jqXHR.responseText
But none of they worked for me . Please help me with this.
submitHandler: function (form) {
var txtName = $("#txtName").val();
var txtEmail = $("#txtEmail").val();
var txtSurName = $("#txtSurName").val();
var txtMobile = $("#txtMobile").val();
var txtAddress = $("#txtAddress").val();
var obj = CheckUser();
if (obj == false) {
$.ajax({
type: "POST",
url: location.pathname + "/saveData",
data: "{Name:'" + txtName + "',SurName:'" + txtSurName + "',Email:'" + txtEmail + "',Mobile:'" + txtMobile + "',Address:'" + txtAddress + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
$(".errMsg ul").remove();
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
bindData();
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
clear();
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
else {
$(".errMsg").append("<ul><li>User Already Exists </li></ul>");
$(".errMsg").show("slow");
}
}
});
$("#btnSave").click(function () {
$("#form1").submit()
});
});
checkusers function is:
function CheckUser() {
var EmpName = $("#txtName").val();
$.ajax({
type: "POST",
url: location.pathname + "/UserExist",
data: "{Name:'" + EmpName + "'}",
contentType: "application/json; charset=utf-8",
datatype: "jsondata",
async: "true",
success: function (response) {
console.log(response.d);
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
Just because your database returns true or false doesn't mean this also gets returned by your CheckUser().
There are several options here:
Either you make a local variable in your CheckUser, Make your Ajax call synchronous, set the local variable to response.d in the success function and then return that local variable.
Another option is to work with Deferred objects and make your submithandler Ajax call wait for the Checkuser Ajax call to return;
A third option is to call your create ajax call from your success callback in your CheckUser Ajax call if the user isn't created yet.
I would recommend either option 2 or 3, because option 1 is not userfriendly.

Parsing json synchronously from url in javascript

I'm trying to get title of a youtube video. So i'm using jQuery to parse json. But it works asynchronously, so the answer comes after the page loaded. The result is:
http://www.youtube.com/watch?v=Ym0hZG-zNOk (undefined)
How can i fix it?
Thanks.
http://jsfiddle.net/3vQht/
<html>
<head>
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";
var videoID = link.substring(link.indexOf("=") + 1, link.length);
document.writeln("<a target='_blank' href='" + link + "'>" + link.bold() + "</a> (" + name(videoID) + ")<br>");
function name(value) {
var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc&callback=?";
var fin;
$.getJSON(source, function(json) {
fin = json.data.title;
console.log(fin);
});
return fin;
}
</script>
</head>
<body>
</body>
</html>
Hy,
here is the solution :)
<script type="text/javascript">
function name(value) {
var source = "http://gdata.youtube.com/feeds/api/videos/" + value + "?v=2&prettyprint=true&alt=jsonc";
$.ajax({
type: 'GET',
url: source,
contentType: "application/json",
dataType: 'json',
success: function (json) {
alert("here is the title: "+json.data.title+" .Use it how you want!");
},
error: function (e) {
alert("error");
}
});
}
$(document).ready(function() {
var link = "http://www.youtube.com/watch?v=Ym0hZG-zNOk";
var videoID = link.substring(link.indexOf("=") + 1, link.length);
name(videoID);
});
</script>
If you want to get your data sync just use this version:
$.ajax({
type: 'GET',
url: source,
async: false,
contentType: "application/json",
dataType: 'json',
success: function (json) {
alert("here is the title: "+json.data.title+" .Use it how you want!");
},
error: function (e) {
alert("error");
}
});
}
getJSON is asynchronous, so when the return fin; is reached, the data hasn't been fetched yet.
Everything that depends on the JSON MUST be inside the success callback.
If you prefere, you can also fetch your data synchronously. Check the jQuery.ajax() documentation for the async parameter.
EDIT: Just figured that you're loading your data using JSONP and that it's not possible to do that synchronously. You need to use asynchronous callbacks instead.
I haven't played with their api, but a quick look at
https://developers.google.com/youtube/2.0/developers_guide_json
indicates that they support jsonp callbacks so that you can prepend a script that does sends the data to a callback function (just add &callback=yourFunction to the end of the url)
function prependScriptFromUrl(s){
var a=document.createElement("script");
var b=document.getElementsByTagName('head')[0];
a.src=s;
b.insertBefore(a,b.firstChild)
}

How to ensure that a function is executed completely, before navigating to another page?

I'm removing certain records using a webservice. The jquery ajax request is written in the onclick of a hyperlink. When im executing the script, line by line using firebug, it's getting removed otherwise it's not. Does any one meet any situation like this before? Please help
Code sample:
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
jQuery ajax functions return deferred objects, thus we return $.ajax. Then you should use deferred.done to execute the callback when the AJAX is fully finished. When the AJAX is done, navigate away using JS instead:
var func = function() {
...
return $.ajax({...}); //return our ajax deferred
}
$(".target").click(function() {
var target = this; //preserve "this" since this in the callback may be different
func().done(function(){ //our done callback executed when ajax is done
window.location.href = target.href; //assuming .target is a link
});
return false; //prevent the natural click action
});
You can use the async: false on the ajax call that is wait there to complete the call.
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: false,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
Alternative you can make the submit after the request.
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
return false;
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: true,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
$("#YourFormID").submit();
}
//Event that'll be fired on Success
});
}
Simply move the Event to the "success" handler in your ajax request:
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed");
//Event that'll be fired on Success
}
});
Alternatively use jQuery ajax callback methods.

Categories

Resources