Sometimes $(this) is not working with AJAX success code - wordpress

I am using Wordpress AJAX for showing some results.
The function is working very well but while showing the result $(this) is not working.
My code is below:
<script type="text/javascript">
jQuery(document).ready(function () {
$("a.review_status").live("click", function () {
var id = $(this).attr("id");
dataString = 'id=' + id;
jQuery.ajax({
type: "POST",
url: "<?php echo $ajax_status_url; ?>",
data: dataString,
cache: false,
success: function (html) {
$(this).text(html);
}
});
});
});
</script>
In that AJAX is not give me proper result.

There's a change in context in the callback inside the ajax success. The reference to this inside the success funtion points to the success function itself and not to the element that was clicked on.
A way around this is to store a reference to this as self. For example:
<script type="text/javascript">
jQuery(document).ready(function () {
$("a.review_status").live("click", function () {
var self = this;
var id = $(this).attr("id");
dataString = 'id=' + id;
jQuery.ajax({
type: "POST",
url: "<?php echo $ajax_status_url; ?>",
data: dataString,
cache: false,
success: function (html) {
$(self).text(html);
}
});
});
});
</script>

Use this code instead of above code:
<script type="text/javascript">
jQuery(document).ready(function () {
$("a.review_status").live("click", function () {
var element = $(this);
var id = $(this).attr("id");
dataString = 'id=' + id;
jQuery.ajax({
type: "POST",
url: "<?php echo $ajax_status_url; ?>",
data: dataString,
cache: false,
success: function (html) {
$(element).text(html);
}
});
});
});
</script>

Try jQuery instead of $
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery("a.review_status").live("click", function () {
var element = jQuery(this);
var id = jQuery(this).attr("id");
dataString = 'id=' + id;
jQuery.ajax({
type: "POST",
url: "<?php echo $ajax_status_url; ?>",
data: dataString,
cache: false,
success: function (html) {
jQuery(element).text(html);
}
});
});
});
</script>

Related

Adding HTTP and HTTPS Social Share Counts for Pintrest

Trying to retain the social share counts after migrating http to https and revert our social proof. I am looking for help from folks who can advise on how to summarize two functions and output the total number of shares in the DIV:
<div id="pin-div">0</div>
The function returns the count of HTTP url:
<script type="text/javascript" src="//code.jquery.com/jquery-1.12.4.js"></script>
<script type="text/javascript">
$(function() {
var url = "<?php $page_url = "http://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $page_url; ?>";
var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;
$.ajax({
url: apiUrl,
success: function(result) {
$.each(result, function(key, val) {
console.log(key + " - " + val["receiveCount"]["count"]);
var shareCount = val["receiveCount"]["count"];
$("#pin-div").html(shareCount);
});
}
});
});
</script>
Same code returns the count of HTTPS url:
<script type="text/javascript">
$(function() {
var url = "<?php $page_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; echo $page_url; ?>";
var apiUrl = "https://api.pinterest.com/v1/urls/count.json?callback=receiveCount&url=" + url;
$.ajax({
url: apiUrl,
success: function(result) {
$.each(result, function(key, val) {
console.log(key + " - " + val["receiveCount"]["count"]);
var shareCount = val["receiveCount"]["count"];
$("#pin-div").html(shareCount);
});
}
});
});
</script>
What am I missing to sum both results?
Thank you all JS developers and hope this will help thousands of people!

Unknown web method in asp.net

In the below code I have a textbox .My aim is when I focus on textbox it will call the server side code through ajax.But I got a error unknown web method txtField_GotFocus parameter name method name.Please help me to rectify the error.
design code:
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
//alert("success message here if you want to debug");
},
error: function (xhr) {
var rawHTML = xhr.responseText;
var strBegin = "<" + "title>";
var strEnd = "</" + "title>";
var index1 = rawHTML.indexOf(strBegin);
var index2 = rawHTML.indexOf(strEnd);
if (index2 > index1) {
var msg = rawHTML.substr(index1 + strBegin.length, index2 - (index1 + strEnd.length - 1));
alert("error: " + msg);
} else {
alert("General error, check connection");
}
}
});
});
});
<asp:TextBox ID="txtField" runat="server" AutoPostBack="true" OnTextChanged="txtField_TextChanged" ClientIDMode="Static"></asp:TextBox>
field.ascx:
public static void txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];
//code...
}
You are missing [WebMethod] annotation. Also i have modified your code
[WebMethod]
public static string txtField_GotFocus()
{
string foo = HttpContext.Current.Request["foo"];//oops i got my super data
//code...
return "awesome, it works!";
}
Check this Article
Your refactored ajax code
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg);//awesome, it works!
},
error: function (xhr) {
}
});
});
});
Data returned form Server is stored in msg.d field. If you return a single value, you should get it using msg.d. If you return a JSON serialized object you have to parse it using JSON.parse(msg.d)
$(document).ready(function () {
$("#<%=txtField.ClientID%>").bind("focus", function () {
$.ajax({
type: "POST",
url: "<%=Request.FilePath%>/txtField_GotFocus",
data: "{foo:'whatever'}",
success: function (msg) {
alert(msg.d);//awesome, it works!
},
error: function (xhr) {
}
});
});
});

return null with query string whtn i use ajax-jquery

this is my jquery code:
<script type="text/javascript">
$(document).ready(function () {
$("a").hover(function () {
$.ajax({
type: "POST",
url:"Dbread.aspx",
data: "name=salam",
success: function (result) {
alert(result);
} //end of success
});
}, function () {
});
});
</script>
in Dbread.aspx
i wrote:
string str= Request.QueryString["name"];
Response.Write(str);
but the problem is that query string result is null all times!!!
what is problem?
This is the best practice.
$.ajax({
type: "POST",
url:"Dbread.aspx",
data: {name:"salam",qs:"bla"}, //also i appended the qs parameter
success: function (result) {
alert(result);
} //end of success
});
You are using method "POST" and not providing actual query string. Query string is created only for "GET" method and should be the part of the URL, so the fix would be:
$.ajax({
type: "GET",
url:"Dbread.aspx?name=salam",
...
or
$.ajax({
type: "GET",
url:"Dbread.aspx",
data: "name=salam",
...
extra space can cause this problem
PrintPreview.NavigateUrl = "~/ReportViewer.aspx?ReviewID=" + Session["ArticleID"].ToString() + " & User=" + (Session["ID"]).ToString();
above is not working it returns null in ID
but in the below example it works fine just change of space character
PrintPreview.NavigateUrl = "~/ReportViewer.aspx?ReviewID= " + Session["ArticleID"].ToString() + "&User=" + (Session["ID"]).ToString();
http://afzal-gujrat.blogspot.com/

JQuery code not working in IE 8

This code is working in firefox but on IE 8 it returns nothing
<script type="text/javascript">
$(document).ready(function(){
var pageUrl = '<%=ResolveUrl("~/test/test.aspx")%>';
// Test
$('#<%=ddlTest.ClientID%>').change(function(){
var trgId = $(this+'input:checked').val();
$.ajax({
type: "POST",
url : pageUrl+ '/getRecs',
data : '{categ: "' +trgId + '"}',
contentType:"application/json; charset=utf-8",
dataType:"json",
success:function(msg)
{
bindCategories(msg)
}
});
});
});
$('#divLoad').ajaxStart(function() {
$(this).show();
});
$('#divLoad').ajaxStop(function() {
$(this).hide();
});
function bindCategories(msg)
{
if(msg.hasOwnProperty("d"))
alert(msg.d);
else
{
$('select[id$=<%=ddlTrg.ClientID %>] > option').remove();
$.each(msg, function() {
$('#<%=ddlTrg.ClientID %>').append($('<option></option>').val(this['Id']).html(this['Name']));
});
}
}
</script>`
This line doesn't look right?
var trgId = $(this+'input:checked').val();
this is an html element so you can't just use it like you are.
Do you mean something like:
var trgId = $('#' + this.id).val();
or
var trgId = $(this).find('input:checked').val();

Jquery AutoComplete Load Problem

Not Work
Jquery Code:
$('[id$=Name]').autocomplete('CallBack.aspx',{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
Json:
var data = [{NAME:"John",AGE:"57"}];
Work
Jquery Code:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete(data,{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
alt text http://img11.imageshack.us/img11/119/38235621.jpg
Help me pls how its make ? callback.aspx return json not work
Try changing your data to this:
var data = [{id:"John",value:"57"}];
EDIT
Here's a sample of what I think you're trying to do:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete('CallBack.aspx', {
formatItem: function(item) {
return item.NAME;
}}).result(function(event, item) {
location.href = 'somepage.aspx?age=' + item.AGE;
});
Basically you needed to capitalise return item.Name to return item.NAME.
Try This
<script type="text/javascript">
$(document).ready(function () {
$("#TextboxId").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { ids: idstopass },
success: function (retrieveddata) {
alert(retrieveddata);
var dData = JSON.parse(retrieveddata);
alert(dData.Name);
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
</script>

Resources