I am implementing the jQuery Easy UI plugin for checkbox tree. I am having a problem while loading the node data from my action class. The url property does not seem to accept the parameters -
If i give url: '/webapp/fetchData' i'm able to get the data. But if I give
url: '/webapp/fetchData?nodeId='+nodeId
my action class is not able to get the nodeId parameter.
Any solution?
Edit Code ported from comment:
onExpand: function(node) {
alert("inside expand");
var nodeId = node.id;
url: '/webapp/fetchdata?nodeId='+nodeId ;
}
Try this:
Using POST
function DoAction( id, name )
{
$.ajax({
type: "POST",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
Using GET
function DoAction( id, name )
{
$.ajax({
type: "GET",
url: "someurl.php",
data: "id=" + id + "&name=" + name,
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
Here is what works for me:
Solution 1: from static HTML
javascript: on the caller side:
function onBeforeLoad (node, data)
{
data.Name=name;
}
HTML on the caller side:
<ul id="ScriptTree1" class="easyui-tree" lines="true" data-options="onBeforeLoad:onBeforeLoad, lines:true, processData:false" url="someural.php"/>
Solution 2: from dynamic code:
HTML
<ul id="ScriptTree2" class="easyui-tree" animate="true"></ul>
Javascript function triggered on any specific event:
function filltree ()
{
$('#ScriptTree2').tree
({
dataType:'json',
method:'POST',
lines: true,
processData:false,
onBeforeLoad: function (node,param) { param.Name=name; return true;},
onLoadError: function (dom)
{
if (!String.prototype.trim)
{
String.prototype.trim=function(){return this.replace(/^\s+|\s+$/g, '');};
}
var sResponse = new String (arguments[0].responseText);
alert ('Compl: ' + arguments[1] + ' ' + arguments[2].description + ' ' + arguments[2].name + '\r\nAnswer:\r\n' + sResponse.trim() + '\r\nQuery: \r\n' + decodeURIComponent(arguments.caller.caller.caller[0].data));
return true;
},
url:'someurl.php'
});
}
and callee script:
someurl.php
<?
if ($_POST['Name'] != '') {$Name=$_POST['Name'];} else {$Name='';};
if ($_POST)
{
$kv = array();
foreach ($_POST as $key => $value)
{
$kv[] = "$key=$value";
}
$query_string = join(" | ", $kv);
}
echo '[{"id":100,"text":"params","state":"open","children":[{"id":104,"text":"query_string: '.$query_string.'","state":"open"}]}]';
?>
Related
i have this web service methode
List<object[]> List1 = new List<object[]>();
[WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public List<object[]> GetData(int ID)
{
var team = db.TEST.WHERE(a => a.id == ID).ToList();
List1.Add(new object[]
{
team
});
return teamList;
}
and this my Function using Javascript & jQuer & Json
function BindList(id) {
$.ajax({
url: "/WebService1.asmx/GetData",
type: "GET",
dataType: "json",
contentType: "application/Json; Charset= Utf-8",
success: function (data) {
var list = "";
$.each(data.d[0][0], function (index, item) {
list += "<li class='text-secondary p-1'><a class='btn-link text-secondary'><b>" + item.Id+ "</b>" + ", " + "<span class='font-italic'><small>" + item.Name + "</small></span><small><a href='#' Onclick='Delete(" + item.Name + ")'> <i class='float-right far fa-trash-alt'></i></a></small></a>" + "</li>";
});
$("#list").html(list);// and this to print data to this list id
},
error: function (response) {
alert(response);
}
});
}
and this my button to get data
<input id="Button1" type="button" onclick="BindMembersList(1)" value="button" />
My problem is where i need to put the id for give just data have id equal 1
thank you
Since it's an url you are calling, pass it on the url of your AJAX call like so:
function BindList(id) {
$.ajax({
url: "/WebService1.asmx/GetData/" + id,
type: "GET",
dataType: "json",
contentType: "application/Json; Charset= Utf-8",
success: function (data) {
var list = "";
$.each(data.d[0][0], function (index, item) {
list += "<li class='text-secondary p-1'><a class='btn-link text-secondary'><b>" + item.Id+ "</b>" + ", " + "<span class='font-italic'><small>" + item.Name + "</small></span><small><a href='#' Onclick='Delete(" + item.Name + ")'> <i class='float-right far fa-trash-alt'></i></a></small></a>" + "</li>";
});
$("#list").html(list);// and this to print data to this list id
},
error: function (response) {
alert(response);
}
});
}
If it's not working or you need to pass more parameter to the action, you can specify them and using the "&" as separator like so:
url: "/WebService1.asmx/GetData?id=" + id + "¶meter2=" + param,
Anyway, your c# method is wrong since you are returning teamList, which is not implemented inside the action
Try this url:
url: "/WebService1.asmx/GetData?id="+id
I am quite new to to ajax, just learning it, and made a simple page on localhost to test gets and posts from/to json file in the same folder.
While GET is working smoothly, I cannot figure out, why post doesn't happen if I click the button I assigned this function to.
Pls take a look into my code and help.
element = $("#mylist");
var item2 = $("#mytable");
$.ajax({
type: "GET",
url: "data.json",
success: function(response) {
$.each(response, function(i, item) {
element.append("<li>" + item.fname + " " + item.lname + "</li>");
item2.append("<tr><td>" + item.lname + "</td>" + "<td>" + item.fname + "</td></tr>");
});
},
error: function() {
alert("error");
}
});
$("#additem").on('click', function() {
var $fname = $("#fname");
var $lname = $("#lname");
var $city = $("#city");
var order = {
fname: $fname.val(),
lname: $lname.val(),
city: $city.val()
};
console.log(order);
$.ajax({
type: "POST",
url: "data.json",
data: order,
succes: function() {
console.log("succes");
},
error: function() {
console.log("no success");
}
});
});
JSFiddle
The problem is you are trying to post to a .json file, like Patrick Evans says in the comments. You need to do the post to a script, in PHP you could do something like this:
$order = $_POST['order'];
// Do something with order...
echo $order; // or echo success message
Of course for this to work you will need PHP to be running on your server (localhost).
My ajax call is returning zero even though I wrote die() at the end of my PHP function.
I looked over the other questions here and did not figure it out, please take a look at my code
I make an ajax call using this function:
$('.aramex-pickup').click(function() {
var button = $(this);
var pickupDateDate = $('.pickup_date').val();
var pickupDateHour = $('.pickup_date_hour').val();
var pickupDateMinute = $('.pickup_date_minute').val();
var pickupDate = pickupDateDate + ' ' + pickupDateHour + ':' + pickupDateMinute;
var orderId = button.data('id');
if (pickupDate) {
//show loader img
button.next('.ajax-loader').show();
var data = {
'action': 'aramex_pickup',
'order_id': orderId,
'pickup_date': encodeURIComponent(pickupDate)
};
$.ajax({
url: ajaxurl,
data: data,
type: 'POST',
success: function(msg) {
console.log(msg);
if (msg === 'done') {
location.reload(true);
} else {
var messages = $.parseJSON(msg);
var ul = $("<ul>");
$.each(messages, function(key, value) {
ul.append("<li>" + value + "</li>");
});
$('.pickup_errors').html(ul);
}
}, complete: function() {
//hide loader img
$('.ajax-loader').hide();
}
});
} else {
alert("Add pickup date");
}
return false;
});
in the back-end I wrote this function just to test the ajax is working ok:
public function ajax_pickup_callback() {
echo 'ajax done';
die();
}
I registered the action by:
add_action('wp_ajax_aramex_pickup', array($this, 'ajax_pickup_callback'));
all of this returns 0 instead of "ajax done".
Any help please?
Actually your hook is not get executed. You have to pass the action in the ajax request as you can see here.
jQuery.post(
ajaxurl,
{
'action': 'add_foobar',
'data': 'foobarid'
},
function(response){
alert('The server responded: ' + response);
}
);
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
});
}
This is my code :
jQuery(document).ready(function () {
jQuery(".jlk").live("click", function (e) {
e.preventDefault();
var task = jQuery(this).attr("data-task");
var post_id = jQuery(this).attr("data-post_id");
var nonce = jQuery(this).attr("data-nonce");
var currentClass = $(this).attr('class');
jQuery(".status-" + post_id).html(" ").addClass("loading-img").show();
jQuery.ajax({
type: "post",
dataType: "json",
url: wtilp.ajax_url,
data: { action: "wti_like_post_process_vote", task: task, post_id: post_id, nonce: nonce },
success: function (response) {
jQuery(".lc-" + post_id).html(response.like);
jQuery(".unlc-" + post_id).html(response.unlike);
jQuery(".status-" + post_id).removeClass("loading-img").empty().html(response.msg);
}
});
});
// Other users tooltip
jQuery("span.wti-others-like").live("mouseover", function () {
jQuery(this).children("span").show();
});
jQuery("span.wti-others-like").live("mouseout", function () {
jQuery(this).children("span").hide();
});
});
And I'm trying to add the conditional statement like this :
if (jQuery(".lc-" + post_id).html(response.like)) {
$(".action-unlike-" + post_id + " img").removeClass('opacity-none'); $(".action-like-" + post_id + " img").addClass('opacity-none'); alert('positive');
}
else if (jQuery(".unlc-" + post_id).html(response.unlike)) { $(".action-like-" + post_id + " img").removeClass('opacity-none'); $(".action-unlike-" + post_id + " img").addClass('opacity-none'); alert('negative'); }
But it always alert 'positive' like its not reading my conditions.
How can i accomplish this?
If (response.like == 'true') {do this} else if (response.unlike == 'true') {do this} ?
the jQuery HTML Method always returns true since it is a method to set HTML when you pass in a value.
See: http://api.jquery.com/html/
If your HTML is an input string your looking for the "Val" Method.
See: http://api.jquery.com/val/
if you literally want to check the HTML you need to check the .html() with NO Values passed in. Then do a string or other comparison of that HTML.
H i,
The if statement is a declaration ( it is setting html, not getting html and checking )
if (jQuery(".lc-" + post_id).html(response.like)) { ...
do you mean to do :
if (jQuery(".lc-" + post_id).html()===response.like) { ...
You should actually check the HTML value like $(".lc-" + post_id).html() with the response.like instead of setting the value in it. You can replace the code with the below one:
if ($(".lc-" + post_id).html() == response.like) {
$(".action-unlike-" + post_id + " img").removeClass('opacity-none');
$(".action-like-" + post_id + " img").addClass('opacity-none');
alert('positive');
} else if ($(".unlc-" + post_id).html() == response.unlike) {
$(".action-like-" + post_id + " img").removeClass('opacity-none');
$(".action-unlike-" + post_id + " img").addClass('opacity-none');
alert('negative');
}
Good luck!