Prototype to jQuery Conversion Confusion - javascript

I have the following function:
function updateproductselectionxxx(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
var target = 'productselectionresult' + productassignment;
var myAjax = new Ajax.Updater(target, checkingurl, {
method: 'post',
parameters: pars
});
}
And I am currently in the process of converting all the javascript on this website to jQuery. Usually I can use something similar to:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
$.ajax({
type: 'POST',
url: 'shopajaxproductselection.asp',
data: $(form).serialize(),
success: function (response) {
$(form).find('productselectionresult' + productassignment).html(response);
}
});
return false;
}
And that does the trick, however I really only want to send over 1 field as indicated in the first function and I would also like to send along the information I am sending directly to the function upon it being called. JavaScript is definitely not my area of expertise but usually I can muddle through, but this time everything I have tried has caused errors and I'm not getting very far. Any help would be greatly appreciated.

Looks like a bit of confusion between POST and GET. Although the request method is set to POST in the older Prototype version the params are being sent via CGI which normally appear on the server as a GET. It's a bit hard to say more without seeing the server-side code, but you could try this, such that the jQuery version more closely mimics the old Prototype version:
function updateproductselection(form, productassignment, mainproductid, subprodqty) {
var checkingurl = "shopajaxproductselection.asp";
var pars = 'productassignment=' + productassignment + '&qty=' + subprodqty + '&mainid=' + mainproductid;
var url = checkingurl + '?' + pars;
$.ajax({
type: 'POST',
url: url,
data: {},
success: function (response) {
$(form).find('#productselectionresult' + productassignment).html(response);
}
});
return false;
}
Note that I have added a hash # to the start of productselectionresult - this is crucial due to the difference in the way PrototypeJS works. In Prototype, you can use an ID selector like:
$('id')
whereas in jQuery it has to be:
$('#id')

Related

Connecting moodle api through web service

Let me explain: My purpose is to create moodle users from a web app.
I am implementing a web app on Tomcat 8.0.15.0. That is, I use java servlets on the server side. Many JSP files and javascript, with much of it in jQuery, resides on the client side.
On the other hand, on another server, I have a test moodle installation. Via site-administration> plugins> web services> external services, I created a ws that enables the core_user_create_users function. Also created a token to access this ws, and put the admin user as authorized user.
And then, typed the following URL on Chrome:
https://mysyte.com/webservice/rest/server.php?wstoken=780f8b3a1164163d4dc00a757071194e&wsfunction=core_user_create_users&moodlewsrestformat=json&users[0][username]=testuser&usr[ [email] =john#smith.com&users [0] [password] = XXXXXX
And it worked. It returned a blank page, with the text
[{"id": 1, "username": "testuser"}]
Thus creating a user in moodle.
My question is: How can I do this from java?, or from javascript?, or from jQuery even better.
And if not, from PHP, I guess I would have no problem calling it from java, or javascript, or jQuery.
My Wrong Hint: In another part of the application I used, in javascript, the call $.getJSON() successfully. That's why I thought would also serve me in this case. But no success now, when the mozilla debugger reaches the call, it hangs.
Any feedback will be most welcome.
The call looks like
function create_moodle_user(username,firstname,lastname,email,password) {
var url = "https://mysyte.com/webservice/rest/server.php?"
+ "wstoken=780f8b3a1164163d4dc00a757071194e" + "&"
+ "wsfunction=core_user_create_users" + "&"
+ "moodlewsrestformat=json" + "&"
+ "users[0][username]=" + username + "&"
+ "users[0][firstname]=" + firstname + "&"
+ "users[0][lastname]=" + lastname + "&"
+ "users[0][email]=" + email + "&"
+ "users[0][password]=" + password;
$.getJSON(url, function(data) { // should return [{"id":4,"username":"testuser"}]
// this point is never reached
if (data.length < 64) {
}
else {
}
});
}
Finally, it worked by changing the call and the way how parameters were passed.
function create_moodle_user(u,f,l,e,fn) {
var domainname = 'https://my.moodle.site.com';
var data = {
wstoken: '780f8b3a1164163d4dc00a757071194e'
wsfunction: 'core_user_create_users'
moodlewsrestformat: 'json',
users: [
{
username:u,
password:'xxxxxxxx',
email:e,
firstname:f,
lastname:l
}
]
};
var response = $.ajax({
type: 'GET',
data: data,
url: domainname + '/webservice/rest/server.php'
});
// pass the function parameter
response.done(fn);
}
And this worked!
My problem now is to get user info, since I don't know how to get the response from core_user_get_users_by_field.
This is what I have:
function get_moodle_user(u,fn) {
var domainname = 'https://my.moodle.site.com';
var data = {
wstoken: '780f8b3a1164163d4dc00a757071194e'
wsfunction: 'core_user_get_users_by_field'
moodlewsrestformat: 'json',
field: 'username',
username:u
};
var response = $.ajax({
type: 'GET',
data: data,
url: domainname + '/webservice/rest/server.php'
});
console.log(response); // this does not show the result data
// pass the function parameter
response.done(fn);
}
Any ideas, please?

How To Open URL In New Tab Using Ajax Success?

Here i am trying to open the file in new tab by calling ViewFile action of Doctor controller using Ajax Success which is in functionabc(this) on click of anchor tag.
Now the problem is that everything is as required but the url doesnot open in new tab.
Below is my Ajax
<script>
function abc(thisEvent) {
debugger;
var getDoCredId = $(thisEvent).attr('docCredId');
var parameter = { id: getDoCredId };
$.ajax({
url: "/Doctor/ViewFile1",
type: "get",
dataType: "html",
data: parameter,
success: function (data) {
debugger;
if (data = true) {
debugger;
var getdoctorId = $(thisEvent).attr('docCredId');
var url = "/Doctor/ViewFile/" + getdoctorId;
window.open(url, "_blank");
}
else {
debugger;
showNotification("Error", "warning");
}
}
});
}
Below is my anchor tag HTML
<a title="View Attachment" docCredId = "' + getDocCredId + '" onclick="abc(this)"><i class="btn btn-web-tbl btn-warning fa fa-eye "></i></a>
Below is code behind
public bool ViewFile1(int id)
{
var document = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);
if (checkFileInFolder == true)
{
return true;
}
else
{
return false;
}
}
public ActionResult ViewFile(int id)
{
var document = _doctorService.GetDoctorCredentialDetails(id);
string AttachPath = ConfigPath.DoctorCredentialsAttachmentPath;
string strFileFullPath = Path.Combine(AttachPath, document.AttachedFile);
string contentType = MimeTypes.GetMimeType(strFileFullPath);
bool checkFileInFolder = System.IO.File.Exists(strFileFullPath);
bool filedata = System.IO.File.ReadAllBytes(strFileFullPath).Any();
byte[] filedata1 = System.IO.File.ReadAllBytes(strFileFullPath);
var cd = new System.Net.Mime.ContentDisposition
{
FileName = document.FileName,
Inline = true
};
Request.HttpContext.Response.Headers.Add("Content-Disposition", cd.ToString());
return File(filedata1, contentType);
}
Since this is too long for a regular comment, I am posting this as an answer, although it isn't directly going solve the problem because I am not able to reproduce it, but might give some insights and let you check the differences with what happens in your code as compared with this simplified example.
Calling window.open() from jQuery ajax success callback works just fine: https://codepen.io/nomaed/pen/dgezRa
I used the same pattern as you did, without your server code but using jsonplaceholder.typicode.com sample API instead.
There are some issues with the code sample that you might want to consider, even though you didn't ask for comments about it and it's not directly related to your issue (probably):
if (data = true) means data will always be true. You probably mean to do a if (data === true) if you know it's a boolean value, or if (data) if you want to accept any truthy value (true, {}, "something", 42, etc). Judging by the Java code and how you define the response format in the jQuery ajax call, it looks like you're expecting the "data" variable result be an HTML and not a boolean. You might want to try and remove the dataType: "html" row and let jQuery set the data format according to what is coming back from the server, and/or send a JSON formatted response, as in a POJO of { result: true } for a successful response. Then make sure that data.result === true to be sure that you got what you expect.
You should probably add arbitrary data to tags DOM elements the data-* attributes and if you're using jQuery, access them using the .data() selector. White adding just random attributs with string values may work, it's considered an abuse of the HTML and DOM, and the data-* attributes are there specifically for adding any data.
In the abc() function you grab the value of the attribute in the beginning (var getDoCredId = $(thisEvent).attr('docCredId');) but in the callback you're trying to get the value once more. You really don't need it since the success() callback is a closure in the scope of the abc() function and it has access to the value already, so doing var getdoctorId = $(thisEvent).attr('docCredId'); in the callback is really not needed.
I'd also suggest naming getDoCredId variable just as docCredId. Having a "get" prefix usually means that it's a getter function or a reference to some getter. Likewise, the "thisEvent" argument of the main function should probably be called "callerElement" or something like that since it's not an event, it's an actual element that you're passing directly from the DOM when calling abc(this) in the onClick event handler of the <a> anchor. This is just to make the code clearer to understand for anyone who's reading it, and for yourself when you're coming back to it several months in the future and trying to figure out what's going on :)
Try adding async: false to your Ajax request
function abc(thisEvent) {
debugger;
var getDoCredId = $(thisEvent).attr('docCredId');
var parameter = { id: getDoCredId };
$.ajax({
async: false, // <<<----------- add this
url: "/Doctor/ViewFile1",
type: "get",
dataType: "html",
data: parameter,
success: function (data) {
debugger;
if (data = true) {
debugger;
var getdoctorId = $(thisEvent).attr('docCredId');
var url = "/Doctor/ViewFile/" + getdoctorId;
window.open(url, "_blank");
}
else {
debugger;
showNotification("Error", "warning");
}
}
});
}

SyntaxError: expected expression, got ')'

I've been stuck at this error for a few days and still couldn't figure out what is wrong. Would be great if someone could just point me to the right direction of solving this issue.
Update:
I realise that error is gone when I commented "addMessages(xml)" in the updateMsg() function. How do I make it work then?
Error:
http://i.imgur.com/91HGTpl.png
Code:
$(document).ready(function () {
var msg = $("#msg");
var log = $("#log");
var timestamp = 0;
$("#name").focus();
$("#login").click(function() {
var name = $("#name").val();
if (!name) {
alert("Please enter a name!");
return false;
}
var username = new RegExp('^[0-9a-zA-Z]+$');
if (!username.test(name)){
alert("Invalid user name! \n Please do not use the following characters \n `~!##$^&*()=|{}':;',\\[\\].<>/?~##");
return false;
}
$.ajax({
url: 'login.php',
type: 'POST',
dataType: 'json',
data: {name: name},
success: function() {
$(".login").hide();
}
})
return false;
});
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()},
})
msg.val("");
return false
});
window.setInterval(function () {
updateMsg();
}, 300);
function updateMsg() {
$.post('server.php', {datasize: '1024'}, function(xml) {
addMessages(xml);
});
}
function addMessages(xml) {
var json = eval('('+xml+')');
$.each(json, function(i, v) {
tt = parseInt(v.time);
if (tt > timestamp) {
console.log(v.message);
appendLog($("<div/>").text('[' + v.username + ']' + v.message));
timestamp = tt
}
});
}
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
msg.appendTo(log)
if (doScroll) {
d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
});
It might help to read up on eval a bit. It looks like it doesn't do what you think it does.
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.
Also
There are safer (and faster!) alternatives to eval() for common use-cases.
It looks like what you're trying to do is get data from the server in the form of JSON. You'll need to make sure that your server returns something that is valid JSON, which you can verify here. Most server-side programming languages have a library that will turn an object into JSON to make that a piece of cake. Here's an example for php.
On the client-side, you'll need to change var json = eval('(' + xml + ')'); to var json = JSON.parse(xml); This will give you the javascript version of your php/perl/python/etc object. If it's an array, you can then iterate through it with a for loop, Array.prototype.forEach, or a variety of functions from different libraries, such as $.each or _.each.
SyntaxError: expected expression, got ')' usually cause by something like
exeFunction(a,b,)
See if your form submit function ajax causing such error
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()}, <-------
})
msg.val("");
return false
});
If you are triggering the java script on click or trigger any click. sometimes missing of 0 gives the above error.
delete
would JSON.stringify({datasize: '1024'}) do the trick? just a guess

JQuery Ajax POST no longer hits ServerSide asp.net Method after adding parameters

Before adding any parameters I had this POST method hitting my serverside code whenever a user would set focus from one control to another. This was good but i need to pass data of the id and value. These values are being populated from what gather in my failure growl.
The issue is that I don't exactly know why it will no longer hit my serverside routine. I did look around stackoverflow a good deal for some help, i did clean up a few things but I couldnt quite pinpoint exactly where my issue is.
$(document).ready(function () {
var id;
var value;
$(".tpControl").blur(function () {
id = this.id;
value = $(this).val();
var postdata = { identifier: id, controltext: value };
$.ajax({
type: "POST",
url: "TimePoints.aspx/ClientSideSave",
contentType: "application/json; charset=utf-8",
data: postdata,
dataType: "json",
success: function (msg) {
if (msg.hasOwnProperty("d")) {
OnSuccess(msg.d);
} else {
OnSuccess(msg);
}
},
error: OnFailure
});
});
function OnSuccess(result) {
$.growlUI('AutoSave Successful');
}
function OnFailure(result) {
$.growlUI("ID: " + id, "Answer: " + value);
}
});
My Server side is pretty simple
[WebMethod]
public static void ClientSideSave(string identifier, string controltext)
{
//Bunch of code, shouldn't affect anything.
}
Thank you in advance. Any help would be great, im pretty new to the world of Jquery and Ajax.
You were close, but remember you are posting JSON, not form value collections. This means JSON strings are quoted during transport and in your example, will be quoted on the backend, probably not what you really want:
var postdata = "{ 'identifier': 'id', 'controltext': 'value' }";
3 mistakes to avoid when using jQuery with ASP.NET AJAX
If you want use JSON(JavaScript Object Notation) the right way, then you should follow this example:
Using complex types to make calling services less… complex

$.ajax json method does not hit the web method

When this function is hit , it does not call my function in code behind? Why could it be doing this? How can I fix this error.
$(document).ready(function() {
$('[id$=btn_Update]').click(function() {
var reten = $('[id$=txt_Reten]').val();
var i=0;
var selectValues = "";
var ProdID = new Array();
$("#lst_ProdId option").each(function() {
selectValues = selectValues + $(this).text() + ",";
ProdID[i] = $(this).text();
i++;
});
for(var j=0; j < ProdID.length;j++)
{
// alert(ProdID[j]);
}
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
$.ajax({
type: "POST",
url: "/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod",
data: params,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(result) {
alert("sucess");
},
error:function(e) {
alert(e.statusText);
// if(errorThrown != null)
// alert(textStatus+ ":"+errorThrown);
// else
// alert("fail");
}
});
return false;
});
return false;
});
This is my webmethod in code behind:
[WebMethod]
public static bool UpdateRetenPeriod(string[] ProdID,string RetenP)
{
for (int i = 0; i < ProdID.Length; i++)
{
update(ProdID[i],RetenP);
}
return true;
}
You're passing your parameters as a string instead of as an object literal:
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
should (almost certainly) be:
var params = {'ProdID': ProdID,'RetenP': reten};
Also, how do you know that the ajax request is not making it to the server? Have you tried tracing the HTTP requests with something like TamperData (for Firefox) or Firebug (also Firefox)?
Does it call the error method?
You need to return JSON. Not a boolean. Perhaps something like {success: true}.
Then:
success: function(data) {
if(data.success) {
...
}
else {
...
}
}
jQuery expects JSON and will throw an error if it doesn't receive well-formed JSON. Also, what is the exact response you're getting back? You can use something like Firebug to figure this out.
One more thing. Can you verify that you can successfully hit that URL? Are you able to successfully point your browser to http://your.url.here/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod?
Also look at Pointy's solution. Your request is unlikely to succeed since you aren't passing in an actual object literal.
Do you have a ScriptManager defined in the markup with EnablePageMethods set to true?
Also, I believe your params line should be:
var params = "{ProdID:'" + ProdID + "', RetenP:'" + reten + "'}";
I have several functions in my own apps that do it this way. You want the value of params to look like this: "{ProdID:'1,2', RetenP:'undefined'}"
Can you place a breakpoint at alert(e.statusText); to see what the error message is?
Have u got error message.. please, try to get the error message
I think, u can use this by replacing error block
error:
function(XMLHttpRequest, textStatus, errorThrown){
alert( "Error Occured!" + errorThrown.toString());
}
I think, problems occurred in code behind method.. if in [web method] has any problem, then ajax doesn't call the method..

Categories