$find doesn't work in external javascript file - javascript

I have a jQuery code that when click on a button in page, show some information (from database) in a asp:RadEditor.
My code work properly when it's inserted internally in page inside tag , but not working in .js file!
function setShowRow(btn, url) {
$.ajax({
type: "POST",
url: "../" + url + "/EditMessage_JQ",
data: "{ 'key':" + "'" + btn + "' }",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (Data) {
if (Data.d[0] != null) {
$("#MainContent_TextBoxMain").val(Data.d[0]);
}
if (Data.d[1] != null) {
$find("#MainContent_TextRadEditorAbst").set_html(Data.d[1]);
}
if (Data.d[2] != null) {
$find("#MainContent_RadEditorText").set_html(Data.d[2]);
}
$("#insert").css("display", "none");
$("#DiveditBtn").css("display", "block");
$("#DivcancelBtn").css("display", "block");
}
});
}

$ is an object, so you have to use the dot-notation: $.find(...)

Related

Ajax never calls my .NET method?

Hi I have the following AJAX which references a method in my .aspx page. I've done some console debugging and my data.d is always undefined. So I've put a breakpoint in the .aspx page on the first line of the method referenced and it never hits it.
I'm really stuck - so if someone could point me in the right direction that would be great.
AJAX:
var param = { "mySearchString": str };
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: JSON.stringify(param),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
{
$("#MyResults").empty();
}
}
});
The initial set up for my .NET method:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public static IEnumerable<MyItem> myMethod(string searchString)
{
I'm passing the right type across, and there are no errors on build or when I run it. So I'm a bit stumped!
Add this to your ajax call to see more about the error:
error: function (request, status, error) {
alert('Error: ' + error);
}
Is this an MVC application? Should the url actually be myForm.aspx/myMethod or just myForm/myMethod? What I am getting at is have you ever hit a breakpoint on the server side and is the path correct?
Try adding this as part of the signature
[HttpPost]
You can add the below attribute to the class, which enables the web method to be called from an ajax script.
[System.Web.Script.Services.ScriptService]
you have
var param = { "mySearchString": str };
but the parameter in you Method is
public static IEnumerable<MyItem> myMethod(string searchString)
Both parameters should have the same name.
You're passing a string as parameter, you should pass an object with a string attribute named searchString:
var param = { "mySearchString": str };
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: param,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
$("#MyResults").empty();
}
});
kindly remove the following properties, and remove the JSON.stringfy
contentType: 'application/json; charset=utf-8',
dataType: 'json',
and kindly don't remove the async because it will freeze your UI if you set it to false.
you can do it like this:
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: param,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
{
$("#MyResults").empty();
}
}
});
I found my answer here: ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"
I was hitting this error:
Object {Message: Ajax error: "Authentication failed.", StackTrace:
null, ExceptionType: "System.InvalidOperationException"}
Turns out that I needed to do:
Inside ~/App_Start/RouteConfig.cs change:
settings.AutoRedirectMode = RedirectMode.Permanent;
To:
settings.AutoRedirectMode = RedirectMode.Off;
Hopefully this will help someone else!

detect which button has been clicked and submit with ajx

I need help getting a value of a clicked button and send this information using AJAX. the two scripts work individually. but i need the "buttonvalue" to be passed to AJAX "data" value "action". what i am using is below.
$("document").ready(function(){
$(".js-ajax-php-json").on("click", "button[name=mysqljob]", function (){
var buttonvalue = $(this).attr("value");
alert(buttonvalue);
});
$(".js-ajax-php-json").submit(function(){
var data = {"action": buttonvalue};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "phpVars/ajaxUpload.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
data["form"]
);
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
I would prevent the form from submitting do what you want then post the data via an ajax call. Try the following:
$("document").ready(function(){
$(".js-ajax-php-json").on("click", "button[name=mysqljob]", function (e){
e.preventDefault();
var buttonvalue = $(this).attr("value");
var data = {"action": buttonvalue, "formData": $(this).serialize() + "&" + $.param(data) };
$.ajax({
type: "POST",
dataType: "json",
url: "phpVars/ajaxUpload.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
data["form"]
);
// alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
Not tested.

jQuery dropdown not firing the delete button

In my small practice project, I have a dropdown with a delete button:
function getMessages() {
$.ajax({
type: "POST",
url: "/Message/GetMessageMethod",
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(data) {
var jsonData = $.parseJSON(data);
var newHtml = "<table style='width: 100%;'class='table-hover'><tr><th>Message</th><th>Date Posted</th><th>Posted by</th></tr>";
for (var i = 0; i < jsonData.length; i++) {
newHtml += "<tr><td>" + jsonData[i].message + "</td><td>" + jsonData[i].date + " - " + jsonData[i].time + "</td><td>" + jsonData[i].name + "</td><td><div class='btn-group'>"+
"<a class='btn dropdown-toggle' data-toggle='dropdown' href='#'> Actions " +
"<span class='caret'></span></a>" +
"<ul class='dropdown-menu' role='menu'>" +
"<li role='presentation'><input type='button' role='menuitem' value='Delete' class='btn btn-danger delMsg'/></li>" +
"</ul></div></td></tr>";
}
newHtml += "<table>";
$('#txfMessage').html(newHtml);
}
});
};
But my delete button is not firing when I click on it... I have a break point in firebug, but its not reaching it...
$('.delMsg').on('click', function () {
$.ajax({
type: "POST",
url: "/Message/DeleteMessage",
contenetType: "application/json; charset=utf-8",
datatype: "json",
cache: false,
data: JSON.stringify({
id: $('#txfMessage').val()
}),
success: function() {
getMessages();
}
});
});
What could be I doing wrong, I've been busy with this since yesterday but couldn't find anything... Help please!
Thank you in advance!
You need to use jQuery event delegation, because you are attempting to attach an event to an element which does not yet exist in the DOM.
Change:
$('.delMsg').on('click', function () {
to:
$(document).on('click', '.delMsg', function () {
Check out this link for more information.
Since the delete button is created AFTER the AJAX call, your "on" method does not attach the event to it. You may use the live method. It will account for elements created after the method is attached.
EDIT: By the way, this depends on the JQuery version. live still works. If you have to use on, use it correctly, like pointed out by Pierre Granger and Jamie Dunstan.
You have to do something like:
$('#txfMessage').html(newHtml);
$('.delMsg').on('click', function () {
$.ajax({
type: "POST",
url: "/Message/DeleteMessage",
contenetType: "application/json; charset=utf-8",
datatype: "json",
cache: false,
data: JSON.stringify({
id: $('#txfMessage').val()
}),
success: function() {
getMessages();
}
});
});
i.e. bind each time you append new html elements, or use event delegation as in the other answers.

How to correctly post data with ajax into div?

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

ajax doesn't update on first click

I have a problem with my code, it's a like button. It shows the number of likes. If user haven't voted yet (cookie) he can click and counter increases. Problem is counter doesn't update on first click (if i deactivate cookie check and vote several times) on next refresh is everything updated. It seems some count happens before insert in the backend. I suppose probem is in JavaScript, ajax post cross domain works but gives error that's why "error: setCookieAndUpdateButton()"
here is my frontend code:
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<div><a id="like_button" href="#">Like</a></div>
<script>
var url = "http://thumbs-up.some-server.com/";
var appName = "next_test";
document.write("<script src=\"" + url + "jquery.cookie.js\"><\/script>");
$(document).ready(function(){
updateButton();
$("#like_button").click(function(){
if ($.cookie(appName + "_voted") == "true") {return;}
$.ajax({
type: "POST",
dataType: "json",
crossDomain: true,
url: url + "increase_counter.php",
data: {referrer: appName},
success: setCookieAndUpdateButton(),
error: setCookieAndUpdateButton()
});
});
});
function setCookieAndUpdateButton()
{
updateButton();
$.cookie(appName + "_voted", "true", {expires: 20*365});
}
function updateButton()
{
$.ajax({
type: "GET",
async: false,
contentType: "application/json",
dataType: "jsonp",
jsonpCallback: 'callback4jquery',
url: url + "get_counter_for_referrer.php",
data: {referrer: appName},
success: function (json) {
if ($.cookie(appName + "_voted") != "true"){
$("#like_button").html("<a id=\"like_button\" href=\"#\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</a>")
}
else{
$("#like_button").html("<span id=\"like_button\"><img src=\"" + url + "like.png\">Good to know " + json.count + "x</span>");
$('#like_button').unbind('click');
}
}
});
}
</script>
In first ajax call change your code like this:
success: setCookieAndUpdateButton,
error: setCookieAndUpdateButton
without () in both of them

Categories