Sending Query String and Session information using Ajax - javascript

I am using Ajax to create comments and its not working , and i am not sure where the problem is. I am thinking it might be in the way i am reading UserID and VideoID
I have UserID saved in a session, and the videoID is saved in Query String.
am i reading them wrong?! if yes how can i read them?
here is my js code:
<script type="text/javascript">
$(document).ready(function () {
$('#btnPost').click(function (e) {
$.ajax({
url: "Ajax/ProcessAddComment.aspx",
data: {
commenttext: $('.txtcomment').val(),
videoid: Request.QueryString["d"],
userid: $.session.get('UserID')
},
success: function (data) {
alert(data);
},
error: function () {
}
});
});
$.ajax({
url: "Ajax/ProcessFindComment.aspx",
data: { videoid: Request.QueryString["id"] },
success: function (data) {
// Append to the bottom
// of list while prepend
// to the top of list
$('.postlist').html(data);
},
error: function () {
alert('Error');
}
});
});

I assume you're using this plugin to get and set your session.
I think your problem is: Request.QueryString
Try using the following JS function to get a value from the querystring rather than that:
function (key) {
if (!key) return '';
key = key.replace(/[*+?^$.\[\]{}()|\\\/]/g, "\\$&"); // escape RegEx meta chars
var match = location.search.match(new RegExp("[?&]" + key + "=([^&]+)(&|$)"));
return (match && decodeURIComponent(match[1].replace(/\+/g, " "))) || '';
};
Note: you can use the network tab in your developer window (F12 in most browsers) to see the Ajax data. The error console in there should tell you if there's a JavaScript error, and the network tab should tell you what was in the Ajax request and response.

Related

Google Maps Geocoding AJAX using a variable as the URL

$('form').submit(function(event){
event.preventDefault();
var userData = "https://maps.googleapis.com/maps/api/geocode/json?address="+$('input#city').val()+"&key=MY_API_KEY";
console.log(userData);
$.ajax({
type: "GET",
url : userData,
success: function(data){
$.each(data['results'][0]['address_components'], function(key, value) {
if(value["types"][0] == "postal_code"){
$('.alert-success').fadeIn(2000).html('Post/ZIP Code: '+value["long_name"]);
}
});
}
})
});
So, I have this code, above, which is currently returning no error nor any results as desired.
It works fine as long as I put the entire 'https://maps.googleapis.com/maps/api/geocode/json?address=""&key=""' string in the url: "", section of the ajax, but when trying to pass my variable in it doesn't want to do anything.
From what I've found variables should pass through easily enough into the ajax call so I'm kind of lost.
Your condition if (value["types"][0] == "postal_code") { is not working.
Check the returned data object via console.log.
Here is a working fiddle without it:
https://jsfiddle.net/1t82y0xa/
You need to URL encode the string returned by $('input#city').val()
related question: JavaScript URL encode
Note: Not all geocoder records return members of the response array with a postal_code type (like for example a query for "New York, NY", it has multiple zip codes).
var userData = "https://maps.googleapis.com/maps/api/geocode/json?address="
+ encodeURIComponent($('input#city').val())
+ "&key=MY_API_KEY";
console.log(userData);
$.ajax({
type: "GET",
url: userData,
success: function(data) {
console.log(data);
$.each(data['results'][0]['address_components'], function(key, value) {
if (value["types"][0] == "postal_code") {
$('.alert-success').fadeIn(2000).html('Post/ZIP Code: ' + value["long_name"]);
}
});
}
});

Trouble building FB.api query

OK so I'm working on a Facebook Group Feed that loads more results, but I'm having trouble building the initial query for it all to work.
In the first if statement below, you can see where I put the parts of the query into variables and then call the function, passing those variables. This all works fine...
if (response.status === 'connected') {
// Logged into your app and Facebook.
console.log('Welcome! Fetching your information.... ');
var path = '/',
method = 'POST',
params = {
batch: [
{method : 'GET', name : 'user', relative_url : '/me?fields=id,name,picture'},
{method: 'GET', name : 'post-ids', relative_url: '/group-id/feed?fields=fields{with field expansion}',omit_response_on_success : false}
]
};
loadFeed(path, method, params);
}
The funciton below is where I'm having trouble. The first time the function is called, I need to put those three variables together into one, and call it with FB.api. You can see the function here:
function loadFeed(path, method, params) {
console.log('------------------');
console.log(path + ', ' + method + ', ' + params);
if(path != 'undefined') {
if(method != 'undefined') {
if(params != 'undefined') { var query = '{\'' + path + '\', \'' + method + '\', ' + params + '}'; }
}
else { var query = path; }
}
$('#load-more').css('display', 'hidden');
FB.api(query, function (response) {
console.log(response);
// first time page loads, response[0] is the login, and response[1] is the feed
// each time after that, response[0] is the feed
if(response.length > 1) {
var membody = JSON.parse(response[0].body),
feed = JSON.parse(response[1].body);
} else {
var feed = JSON.parse(response);
}
if(feed.paging) {
if(feed.paging.next) {
var load_more = '<div id="load-more"><center>Load more</center></div>',
method = '',
params = '';
$('#feed').append(load_more);
$('#load-more').click( function() {
loadFeed(feed.paging.next);
});
}
}
});
}
On the first call of this function, I get this error:
error: Object
code: 2500
message: "Unknown path components: /', 'POST', [object Object]}"
type: "OAuthException"
This seems to tell me that I've basically put the query together wrong, but I've tried a few different things and none of it is working. You can see in the error message that there's a missing single quote at the beginning of the query, and I've not been able to figure out how to keep the single quote there.
Does anyone have any ideas on how I can fix this problem?
Also, if you know a better way to do all this then I'd appreciate that as well!
It seems you are building your Javascript API call with HTTP API parameters.
To query JS API for user:
FB.api(
"/me", // or "/99999999999" the user's id
function(response) {
if (response && !response.error) {
/* handle the result */
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/user
To query JS API for group:
FB.api(
"/{group-id}",
function(response) {
if (response && !response.error) {
/* handle the result */
}
}
);
Source: https://developers.facebook.com/docs/graph-api/reference/v2.2/group

JavaScript missing parametar

I am coding a block type plugin for Moodle and have this JS code that gives me problems. Since I'm not very familiar with JS and JSON I can't deduce what is the problem.
My code uses this function to add custom action to action link which issues ajax call to php file ...
This is the code:
function block_helpdesk_sendemail(e) {
e.preventDefault();
Y.log('Enetered method');
var sess = {'sesskey=':M.cfg.sesskey};
Y.log(sess);
var ioconfig = {
method: 'GET',
data: {'sesskey=':M.cfg.sesskey},
on: {
success: function (o, response) {
//OK
var data;
try {
data = Y.JSON.parse(response.responseText);
Y.log("RAW JSON DATA: " + data);
} catch (e) {
alert("JSON Parse failed!");
Y.log("JSON Parse failed!");
return;
}
if (data.result) {
alert('Result is OK!');
Y.log('Success');
}
},
failure: function (o, response) {
alert('Not OK!');
Y.log('Failure');
}
}
};
Y.io(M.cfg.wwwroot + '/blocks/helpdesk/sendmail.php', ioconfig);
}
The code pauses in debugger at return line:
Y.namespace('JSON').parse = function (obj, reviver, space) {
return _JSON.parse((typeof obj === 'string' ? obj : obj + ''), reviver, space);
};
I've put M.cfg.sesskey and data variables on watch. I can see sesskey data shown, but data variable shows like this:
data: Object
debuginfo: "Error code: missingparam"
error: "A required parameter (sesskey) was missing"
reproductionlink: "http://localhost:8888/moodle/"
stacktrace: "* line 463 of /lib/setuplib.php: moodle_exception thrown
* line 545 of /lib/moodlelib.php: call to print_error()
* line 70 of /lib/sessionlib.php: call to required_param()
* line 7 of /blocks/helpdesk/sendmail.php: call to confirm_sesskey()"
And this is what my logs show:
Enetered method
Object {sesskey=: "J5iSJS7G99"}
RAW JSON DATA: [object Object]
As #Collett89 said, the JSON definition is wrong. His tip might work, but if you need strict JSON data then code the key as string (with quotes):
var sess = {'sesskey': M.cfg.sesskey};
or
var sess = {"sesskey": M.cfg.sesskey};
See definition in Wikipedia
your declaring sesskey in a bizarre way.
try replacing data: {'sesskey=':M.cfg.sesskey},
with data: {sesskey: M.cfg.sesskey},
it might be worth you reading through this
mdn link for javascript objects.
You usually need to JSON.stringify() the objects sent via ajax.
which may be part of the problem.

Display search results from API

Hello there I'm trying to create an app to search for recipes. I've tried using the Yummly API and BigOven api, but I can't get either to work.
here is the code i have for bigOven. I can't get any search results to appear in the "results".
$(function() {
$('#searchform').submit(function() {
var searchterms = $("#searchterms").val();
// call our search twitter function
getResultsFromYouTube(searchterms);
return false;
});
});
function getResultsFromYouTube (searchterms) {
var apiKey = "dvxveCJB1QugC806d29k1cE6x23Nt64O";
var titleKeyword = "lasagna";
var url = "http://api.bigoven.com/recipes?pg=1&rpp=25&title_kw="+ searchterms + "&api_key="+apiKey;
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
alert('success');
console.log(data);
$("#results").html(data);
}
});
}
Can anyone give me instructions on how to do this?? Thank you very much.
The API is returning JSON data, not HTML. I checked the API docs, and JSONP isn't necessary.
However, when you run this code:
$('#results').html(data);
Your code is going to just put the JSON into your HTML, and that isn't going to get displayed properly. You didn't say whether console.log(data) outputs the data correctly, but I'll assume it is.
So, you'll need to transform your JSON into HTML. You can do that programmatically, or you can use a templating language. There are a number of options, including underscore, jquery, mustache and handlebars.
I recommend handlebars, but it's not a straightforward bit of code to add (the main difficulty will be loading your template, or including it in your build).
http://handlebarsjs.com/
It would depend on you which key and values you have to show to your user's and in which manner... For ex. there is even an image link, you could either show that image to your user's or could just show them the image link...
Simple <p> structure of all the key's with there value's
jQuery
$.each(data.Results, function (key, value) {
$.each(value, function (key, value) {
$("#result").append('<p>Key:-' + key + ' Value:-' + value + '</p>');
});
$("#result").append('<hr/>');
});
Your ajax is working, you just need to parse the results. To get you started:
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
// Parse the data:
var resultsString = "";
for (var i in data.Results){
console.log( data.Results[i] );
resultsString+= "<div>"+data.Results[i].Title+ " ("+data.Results[i].Cuisine+")</div>";
}
$("#results").html(resultsString);
// If you want to see the raw JSON displayed on the webpage, use this instead:
//$("#results").html( JSON.stringify(data) );
}
});
I had created a little recursive function that iterates through JSON and spits out all of the values (I subbed my output for yours in the else condition) -
function propertyTest(currentObject, key) {
for (var property in currentObject) {
if (typeof currentObject[property] === "object") {
propertyTest(currentObject[property], property);
} else {
$('#results').append(property + ' -- ' + currentObject[property] + '<br />');
}
}
}
Then I called it within your AJAX success -
$.ajax({
type: "GET",
dataType: 'json',
cache: false,
url: url,
success: function (data) {
console.log(data);
propertyTest(data); // called the function
}
});
It spits out all of the data in the JSON as seen here - http://jsfiddle.net/jayblanchard/2E9jb/3/

How to override Backbone.sync so it adds the apikey and username at the end?

I am using backbone-tastypie, but I am having the toughest time getting it to work properly. In Tastypie, I am using ApiKeyAuthentication for my resources, so every ajax request, I need to append the apikey and username to the end of a request or send additional headers that add on the username and api key.
I am trying to remove a view and its model using backbone with the following code:
// Remove the goal update view from the DOM
removeItem: function() {
this.model.destroy({wait: true, success: function() {
console.log("success");
}, error: function() {
console.log("error");
}});
},
After the function executes, the browser tries to do a GET request on the following URL:
:8000/api/v1/update/2/
It does not include the api_key or username at the end, and it has a trailing slash at the end of the url. I think it is trying to use Backbone.oldSync to do the GET request. How would I make it so the sync does include the username/api key at the end and removes the trailing slash?
In all of the other requests, I have made it so the api key and username is appended to the end of the http request by adding the following code to backbone-tastypie:
if ( !resp && ( xhr.status === 201 || xhr.status === 202 || xhr.status === 204 ) ) { // 201 CREATED, 202 ACCEPTED or 204 NO CONTENT; response null or empty.
var location = xhr.getResponseHeader( 'Location' ) || model.id;
return $.ajax( {
url: location + "?" + "username=" + window.app.settings.credentials.username + "&api_key=" + window.app.settings.credentials.api_key,
success: dfd.resolve,
error: dfd.reject,
});
}
Let's explore the possibilities
Using headers
Backbone.sync still just uses jQuery ajax so you can override ajaxSend and use headers to send information along.
$(document).ajaxSend(function(e, xhr, options)
{
xhr.setRequestHeader("username", window.app.settings.credentials.username);
xhr.setRequestHeader("api_key", window.app.settings.credentials.api_key);
});
Using Ajax Options
If you need to send the information in just one or two locations, remember that the destroy, fetch, update and save methods are just shortcuts to the ajax caller. So you can add all jQuery ajax parameters to these methods as such:
// Remove the goal update view from the DOM
removeItem: function ()
{
this.model.destroy({
wait: true,
success: function ()
{
console.log("success");
},
error: function ()
{
console.log("error");
},
data:
{
username: window.app.settings.credentials.username,
api_key: window.app.settings.credentials.api_key
}
});
}
Overriding jQuery's ajax method
Depending on your needs, this might be the better implementation (note that this is no production code, you may need to modify this to fit your needs and test this before using it)
(function ($) {
var _ajax = $.ajax;
$.extend(
{
ajax: function (options)
{
var data = options.data || {};
data = _.defaults(data, {
username: window.app.settings.credentials.username,
api_key: window.app.settings.credentials.api_key
});
options.data = data;
return _ajax.call(this, options);
}
});
})(jQuery);
Just for future readers of this post, when you do a model.destroy() you can't pass any data because the delete request doesn't have a body, see this issue for more info:
https://github.com/documentcloud/backbone/issues/789

Categories

Resources