How to send an integer from ajax without jquery? - javascript

I am trying to send an integer called 'petadid' from this js to the django view called 'petadlikeview'. But it looks like the data is not going there in the view.If i print 'petadid' in the view, it shows 'None'. Can anyone please tell me what is wrong? I am new to ajax and django.
Here is my js:
<script>
$(document).ready(function(argument) {
$.ajaxSetup({cache:false});
var element = document.getElementById("likes");
var petadid = $(this).attr("data-petadid");
element.addEventListener("click",function(){
var req = new XMLHttpRequest();
req.open("POST",'/petadlike/')
req.onload = function(){
console.log(req.responseText);
console.log(petadid);
var data = JSON.parse(req.responseText);
}
req.setRequestHeader("X-CSRFToken", '{{ csrf_token }}');
var data = {
'petadid':petadid,
}
req.send(data);
});
});
</script>
And here is my django-view:
def petadlikeview(request):
print("vau")
if request.method=="POST":
print("vai")
petadid = request.POST.get('petadid')
print(petadid)
petad = PetAd.objects.get(pk=petadid)
like_count = petad.petadlikes_set.all().count()
like, created = petadlikes.objects.get_or_create(user=request.user,petad=petad)
print(created)
if created is False:
petadlikes.objects.get(user=request.user,petad=petad).delete()
like_count -= 1
liked = False
else:
like.save()
like_count += 1
liked = True
dict = {'like_count':like_count}
return JsonResponse(dict)
return HttpResponse(str(like_count)+' people have liked this')
else:
return HttpResponse('Bad Request')

XMLHttpRequest will not automatically convert an object to POST data as jQuery does, you need to create the URL-encoded string yourself.
var data = "petadid=" + encodeURIComponent(petadid);
Also
var petadid = $(this).attr("data-petadid");
should probably be
var petadid = $(element).attr("data-petadid");

Related

ServiceNow UI Page GlideAjax

I created a form using UI Page and am trying to have some fields autopopulated onChange. I have a client script that works for the most part, but the issue arises when certain fields need to be dot-walked in order to be autopopulated. I've read that dot-walking will not work in client scripts for scoped applications and that a GlideAjax code will need to be used instead. I'm not familiar with GlideAjax and Script Includes, can someone help me with transitioning my code?
My current client script looks like this:
function beneficiary_1(){
var usr = g_user.userID;
var related = $('family_member_1').value;
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee',usr);
rec.addQuery('sys_id',related);
rec.query(dataReturned);
}
function dataReturned(rec){
//autopopulate the beneficiary fields pending on the user selection
if(rec.next()) {
$('fm1_ssn').value = rec.ssn;
$('fm1_address').value = rec.beneficiary_contact.address;
$('fm1_email').value = rec.beneficiary_contact.email;
$('fm1_phone').value = rec.beneficiary_contact.mobile_phone;
var dob = rec.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0] ;
$('fm1_date_of_birth').value = date;
}
}
fm1_address, fm1_email, and fm1_phone do not auto populate because the value is dot walking from the HR_Beneficiary table to the HR_Emergency_Contact table.
How can I transform the above code to GlideAjax format?
I haven't tested this code so you may need to debug it, but hopefully gets you on the right track. However there are a couple of steps for this.
Create a script include that pull the data and send a response to an ajax call.
Call this script include from a client script using GlideAjax.
Handle the AJAX response and populate the form.
This is part of the client script in #2
A couple of good websites to look at for this
GlideAjax documentation for reference
Returning multiple values with GlideAjax
1. Script Include - Here you will create your method to pull the data and respond to an ajax call.
This script include object has the following details
Name: BeneficiaryContact
Parateters:
sysparm_my_userid - user ID of the employee
sysparm_my_relativeid - relative sys_id
Make certain to check "Client callable" in the script include options.
var BeneficiaryContact = Class.create();
BeneficiaryContact.prototype = Object.extendsObject(AbstractAjaxProcessor, {
getContact : function() {
// parameters
var userID = this.getParameter('sysparm_my_userid');
var relativeID = this.getParameter('sysparm_my_relativeid');
// query
var rec = new GlideRecord('hr_beneficiary');
rec.addQuery('employee', userID);
rec.addQuery('sys_id', relativeID);
rec.query();
// build object
var obj = {};
obj.has_value = rec.hasNext(); // set if a record was found
// populate object
if(rec.next()) {
obj.ssn = rec.ssn;
obj.date_of_birth = rec.date_of_birth.toString();
obj.address = rec.beneficiary_contact.address.toString();
obj.email = rec.beneficiary_contact.email.toString();
obj.mobile_phone = rec.beneficiary_contact.mobile_phone.toString();
}
// encode to json
var json = new JSON();
var data = json.encode(obj);
return data;
},
type : "BeneficiaryContact"
});
2. Client Script - Here you will call BeneficiaryContact from #1 with a client script
function onChange(control, oldValue, newValue, isLoading, isTemplate) {
if (isLoading || newValue === '') {
return;
}
var usr = g_user.userID;
var related = $('family_member_1').value;
var ga = new GlideAjax('BeneficiaryContact'); // call the object
ga.addParam('sysparm_name', 'getContact'); // call the function
ga.addParam('sysparm_my_userid', usr); // pass in userID
ga.addParam('sysparm_my_relativeid', related); // pass in relative sys_id
ga.getXML(populateBeneficiary);
}
3. Handle AJAX response - Deal with the response from #2
This is part of your client script
Here I put in the answer.has_value check as an example, but you may want to remove that until this works and you're done debugging.
function populateBeneficiary(response) {
var answer = response.responseXML.documentElement.getAttribute("answer");
answer = answer.evalJSON(); // convert json in to an object
// check if a value was found
if (answer.has_value) {
var dob = answer.date_of_birth;
var arr = dob.split("-");
var date = arr[1] + "/"+ arr[2] + "/" + arr[0];
$('fm1_ssn').value = answer.ssn;
$('fm1_address').value = answer.address;
$('fm1_email').value = answer.email;
$('fm1_phone').value = answer.mobile_phone;
$('fm1_date_of_birth').value = date;
}
else {
g_form.addErrorMessage('A beneficiary was not found.');
}
}

Jquery post response not available

I'm new to javascript, and this problem may be trivial but I need help.
My goal is to send a post to a python server based on tornado.
In the following function :
var machin = $.post( '/room/testroom', function( data ) {
truc = data;
return truc;
I never get back the content of truc.
This variable has an url inside it who will be used to create a new Websocket connection.
When I do console.dir(machin); I see the wanted responseText with the wanted url in the console, but I'm not able to get it outside of the console.
The variable data itself inside the function has my wanted data, as if I do :
alert(data)
I see an alert box with the wanted url.
Feel free to ask me for details as I may not be entirely clear.
Server side, my python code is this one:
def post(self, RoomName):
print 'je poste'
db = connect(host=config.SQLSERVER, user=config.SQLUSER, passwd=config.SQLPASS, db=config.SQLDB)
cursor = db.cursor()
uri = self.request.uri
url = uri.split('/')
RoomName = url[2]
sql = 'SELECT RoomID FROM abcd_un WHERE RoomName = %s', [RoomName]
cursor.execute(*sql)
RoomID = cursor.fetchone()
print 'RoomID', type(RoomID)
RoomID = str(RoomID[0])
RoomID = RoomID.decode()
fullurl = 'ws://' + self.request.host + '/socket/' + RoomID
#print uri
db.close()
wsurl = {
'url': fullurl,
}
wsurl_encoded = tornado.escape.json_encode(wsurl)
self.write(wsurl_encoded)
Try:
var machin = function (){
$.post( '/room/testroom', function( data ) {
truc = JSON.parse(data);
return truc;
}
Now call the function:
var response = machin();
Try:
var machin;
$.post( '/room/testroom', function( data ) {
machin = JSON.parse(data);
return True;
})

Dynamics CRM Sdk.ExecuteMultiple.js Response Items all have same id

I'm using the modern SOAP endpoint and Sdk.Soap.js and Sdk.ExecuteMultiple.js to execute a bunch of create requests from Javascript. Everything works fine, except when I get the response items back, it logs out the same id for each response item. I can't figure out how to get the ids out of the response item. At the bottom, where I log out the ids, I get the same id logged out over and over again. Yet all of the records get created and they all have unique ids. Not sure how to get all of the response ids out. Here is my code:
createOpportunities = function(data) {
var createRequest = new Sdk.Collection(Sdk.OrganizationRequest);
var requestSettings = new Sdk.ExecuteMultipleSettings(true,true);
var pricelevel = {
'id': $("#season").find(':selected').data('pricelevelid'),
'name': $("#season").find(':selected').text()
};
var stage = {
'id': $("#stage").find(':selected').data('stageid'),
'name': $("#stage").find(':selected').text()
};
var product = {
'id': $("#product").find(':selected').data('productid'),
'name': $("#product").find(':selected').text()
};
var source = {
'id': $("#source").find(':selected').data('sourceid'),
'name': $("#source").find(':selected').text()
};
data.forEach(function(d,i){
var Opportunity = new Sdk.jms_opportunity();
Opportunity.JMS_ContactId.setValue(new Sdk.EntityReference('contact', d.contactid));
Opportunity.OwnerId.setValue(new Sdk.EntityReference('systemuser', d.ownerid.getId()));
Opportunity.JMS_pricelevelid.setValue(new Sdk.EntityReference('JMS_pricelevel', pricelevel.id));
Opportunity.JMS_stageid.setValue(new Sdk.EntityReference('str_ticketstage', stage.id));
Opportunity.JMS_ProductId.setValue(new Sdk.EntityReference('JMS_product', product.id));
Opportunity.JMS_sourceid.setValue(new Sdk.EntityReference('jms_source', source.id));
createRequest.add(new Sdk.CreateRequest(Opportunity));
});
var request = new Sdk.ExecuteMultipleRequest(createRequest, requestSettings);
Sdk.jQ.execute(request).done(function(resp) {
var responses = resp.getResponses();
responses.forEach(function(responseItem) {
var id = responseItem.getResponse().getId();
console.log(id);
});
}).fail(function(error) {
console.log(error);
});
};
EDIT
After doing some more debugging, the response body is coming back with the correct guids, but when that response gets parsed the same guid gets added each time the parse function loops...and that's where I am stuck.
Response body:
<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">
<s:Body>
<ExecuteResponse xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\">
<ExecuteResult xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">
<a:ResponseName>ExecuteMultiple</a:ResponseName>
<a:Results xmlns:b=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">
<a:KeyValuePairOfstringanyType>
<b:key>IsFaulted</b:key>
<b:value i:type=\"c:boolean\" xmlns:c=\"http://www.w3.org/2001/XMLSchema\">false</b:value>
</a:KeyValuePairOfstringanyType>
<a:KeyValuePairOfstringanyType>
<b:key>Responses</b:key>
<b:value i:type=\"c:OrganizationResponseCollection\" xmlns:c=\"http://schemas.microsoft.com/xrm/2012/Contracts\">
<c:ExecuteMultipleResponseItem>
<c:Fault i:nil=\"true\"/>
<c:RequestIndex>0</c:RequestIndex>
<c:Response>
<a:ResponseName>Create</a:ResponseName>
<a:Results>
<a:KeyValuePairOfstringanyType>
<b:key>id</b:key>
<b:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">df07d3fb-862c-e511-bdfe-00155d01050d</b:value>
</a:KeyValuePairOfstringanyType>
</a:Results>
</c:Response>
</c:ExecuteMultipleResponseItem>
<c:ExecuteMultipleResponseItem>
<c:Fault i:nil=\"true\"/>
<c:RequestIndex>1</c:RequestIndex>
<c:Response>
<a:ResponseName>Create</a:ResponseName>
<a:Results>
<a:KeyValuePairOfstringanyType>
<b:key>id</b:key>
<b:value i:type=\"d:guid\" xmlns:d=\"http://schemas.microsoft.com/2003/10/Serialization/\">e107d3fb-862c-e511-bdfe-00155d01050d</b:value>
</a:KeyValuePairOfstringanyType>
</a:Results>
</c:Response>
</c:ExecuteMultipleResponseItem>
</b:value>
</a:KeyValuePairOfstringanyType>
</a:Results>
</ExecuteResult>
</ExecuteResponse>
</s:Body>
</s:Envelope>
The ExecuteMultipleResponse function in Microsoft's Sdk.ExecuteMultiple.js taken from here: https://code.msdn.microsoft.com/SdkSoapjs-9b51b99a/sourcecode?fileId=113716&pathId=823928626 The parseResponse function is where I see the same guid get set but I don't know enough about parsing xml to know where this might be going wrong.
this.ExecuteMultipleResponse = function (responseXml) {
///<summary>
/// Response to ExecuteMultipleRequest
///</summary>
if (!(this instanceof Sdk.ExecuteMultipleResponse)) {
return new Sdk.ExecuteMultipleResponse(responseXml);
}
Sdk.OrganizationResponse.call(this)
// Internal properties
var _isFaulted = null;
var _responses = null;
// Internal property setter functions
function _setIsFaulted(xml) {
var valueNode = Sdk.Xml.selectSingleNode(xml, "//a:KeyValuePairOfstringanyType[b:key='IsFaulted']/b:value");
if (!Sdk.Xml.isNodeNull(valueNode)) {
_isFaulted = (Sdk.Xml.getNodeText(valueNode) == "true") ? true : false;
}
}
function _setResponses(xml) {
var valueNode = Sdk.Xml.selectSingleNode(xml, "//a:KeyValuePairOfstringanyType[b:key='Responses']/b:value");
if (!Sdk.Xml.isNodeNull(valueNode)) {
_responses = parseResponses(valueNode);
}
}
function parseResponses(xml) {
//Using Sdk.Collection rather than create a new class for Microsoft.Xrm.Sdk.ExecuteMultipleResponseItemCollection
var rv = new Sdk.Collection(Sdk.ExecuteMultipleResponseItem);
for (var i = 0; i < xml.childNodes.length; i++) {
var emri = new Sdk.ExecuteMultipleResponseItem();
emri.setRequestIndex(parseInt(Sdk.Xml.selectSingleNodeText(xml.childNodes[i], "l:RequestIndex"), 10));
var faultNode = Sdk.Xml.selectSingleNode(xml.childNodes[i], "l:Fault");
if (!Sdk.Xml.isNodeNull(faultNode)) {
emri.setFault(new Sdk.ExecuteMultipleFault(faultNode));
}
else {
var responseName = Sdk.Xml.selectSingleNodeText(xml.childNodes[i], "l:Response/a:ResponseName") + "Response";
var responseXml = Sdk.Xml.selectSingleNode(xml.childNodes[i], "l:Response/a:Results");
emri.setResponse(new Sdk[responseName](responseXml));
}
rv.add(emri);
}
return rv;
}
I am the author of the Sdk.Soap.js library and I can repro what you see.
You should be able to fix this by editing the parseResponses function in the Sdk.ExecuteMultiple.js file. Replace the commented line below so it includes .cloneNode(true).
//var responseXml = Sdk.Xml.selectSingleNode(xml.childNodes[i], "l:Response/a:Results");
var responseXml = Sdk.Xml.selectSingleNode(xml.childNodes[i].cloneNode(true), "l:Response/a:Results");
The problem is that when the node is passed through to the constructor of the Sdk.CreateResponse, the entire xml document was passed through and when it was evaluated using: Sdk.Xml.selectSingleNode(xml, "//a:KeyValuePairOfstringanyType[b:key='id']/b:value"); this found the first instance of the whole document rather than just the specified childNode.
Using cloneNode seems to address the issue, but I haven't done any testing on browsers other than IE. Please let me know if you find issues with other browsers.

Passing array from php to javascript through ajax response

This is my first post in stackoverflow. I have always got my answers from previously posted questions. This problem has been bugging me and all the solutions I tried have not worked.
I have a js function which makes an ajax request to get weather info of town passed:
var _getWeatherInfo = function(ntown){
var town = ntown;
var url = "PHP/weather.php?town=" + town;
request1.onreadystatechange = _refreshWeatherList();
request1.open("GET", url, true);
request1.send("");
}
I am using the following php code to return the sql results stored in array:
<?php
//Connection to the database
$mysql = mysql_connect("localhost","xuvaz","x");
//Selecting Database
$db = mysql_select_db("weather");
$town = $_GET['town'];
$tarray = array();
$sql1= mysql_query("SELECT * FROM weather WHERE town='$town'");
while($row = mysql_fetch_assoc($sql1)) {
$tarray = array('town' => $row['town'],'outlook' => $row['outlook']);
}
echo json_encode($tarray);
?>
Then I have a function that is called when the request is completed:
var _refreshWeatherList = function() {
var weather_info = request1.responseText;
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();
}
The problem is I cant access the array values.
I can see the values as {"town":"Christchurch","outlook":"fine"} in firebug under response.
Even when I use JSON parse it gives error in the firebug , JSON.parse: unexpected end of data. If
I can just access the data my whole project would be completed.
Your PHP code is returning an object (last row from your loop) rather than an array of objects, but your JavaScript is expecting an array.
Change your PHP to the following to appand to $tarray:
while($row = mysql_fetch_assoc($sql1)) {
$tarray[] = array('town' => $row['town'],'outlook' => $row['outlook']);
}
Your JavaScript needs to wait for readyState = Loaded and JSON-decode the responseText:
var _refreshWeatherList = function() {
if(request1.readyState == 4) {
var weather_info = JSON.parse(request1.responseText);
....
}
}
If the parse is failing, trying logging it to the console to make sure the PHP isn't returning extra characters.
var _refreshWeatherList = function() {
var weather_info = eval("("+request1.responseText+")");
for(var i = 0; i < weather_info.length; i++){
var wtown = weather_info[i].town;
var woutlook = weather_info[i].outlook;
var wmin = weather_info[i].min_temp;
var wmax = weather_info[i].max_temp;
}
var wLine = new WLine(wtown, woutlook, wmin, wmax);
_weather.push(wLine);
_refreshWeatherDisplay();}
'request1.responseText' must be 'object' use eval() --! my english not well
Thank you for all your help. I found the fault. I forgot to include these two lines.
if (request1.readyState == 4) {
if (request1.status == 200){

Ajax call to ASP.NET MVC Controller Returns 404 when Json Length is too Long

I have a simple ajax call which is passing a json string to a controller action and if the content portion of the json is too long, or the json string in general, the server returns a 404, if I shorten the content, it the request resolves and completes correctly.
I thought it was do to the 8k limit of Microsoft's JavaScriptSeralizer, but I have updated the MaxJsonLength, with no luck. Can somebody please tell me what's going on here?
Here is my ajax request (Note: This is using Knockout.js)
self.updatePost = function () {
var postToUpdate = ko.toJS(self.selectedPost);
postToUpdate.Content = $("#wmd-input").val();
console.log(postToUpdate);
$.getJSON('/blogs/posts/update', {post: ko.toJSON(postToUpdate)}, function(post) {
if (post) {
// remove the selected post and add the updated post
self.posts.remove(self.selectedPost());
var updatedPost = new Post(post);
self.posts.unshift(updatedPost);
self.selectedPost(updatedPost);
$("#ghost-list li:first").trigger('click');
// show alert
}
});
};
The C# Controller Action
public JsonResult Update(string post)
{
var seralizer = new JavaScriptSerializer();
seralizer.MaxJsonLength = int.MaxValue;
seralizer.RecursionLimit = 100;
var selectedPost = seralizer.Deserialize<Post>(post);
var student = students.GetStudentByEmail(User.Identity.Name);
var blog = db.Blogs.SingleOrDefault(b => b.StudentID == student.StudentID);
var postToUpdate = blog.BlogPosts.SingleOrDefault(p => p.ID == selectedPost.ID);
if (postToUpdate != null)
{
// update the post fields
postToUpdate.Title = selectedPost.Title;
postToUpdate.Slug = BlogHelper.Slugify(selectedPost.Title);
postToUpdate.Content = selectedPost.Content;
postToUpdate.Category = selectedPost.Category;
postToUpdate.Tags = selectedPost.Tags;
postToUpdate.LastUpdated = DateTime.Now;
if (selectedPost.Published)
{
postToUpdate.DatePublished = DateTime.Now;
}
// save changes
db.SaveChanges();
var jsonResult = Json(seralizer.Serialize(selectedPost), JsonRequestBehavior.AllowGet);
jsonResult.MaxJsonLength = int.MaxValue;
return jsonResult;
}
return Json(false, JsonRequestBehavior.AllowGet);
}
Have you tried using the post method:
$.post('/blogs/posts/update', {post: ko.toJSON(postToUpdate)}, function(post) {
if (post) {
// remove the selected post and add the updated post
self.posts.remove(self.selectedPost());
var updatedPost = new Post(post);
self.posts.unshift(updatedPost);
self.selectedPost(updatedPost);
$("#ghost-list li:first").trigger('click');
// show alert
}
}, 'json');
Try this at web config
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="500000000"/>
</webServices>
</scripting></system.web.extensions>

Categories

Resources