Why does the following:
$("a").sortable( {
update:function() {
var urls = "";
$.map($("a"), function(elt) {
urls += "url=" + elt.href + "&";
});
$.ajax( {
url: 'server_side_process_one.aspx',
type: 'POST',
data: { urls.substr(0,urls.length - 1) },
success: function() { alert(urls.substr(0,urls.length - 1)); }
});
}
});
return paths in the following format:
file:///C:/Program%20Office/OFFICE11/WINWORD.EXE
but the following:
$("input:checkbox").live('change', function() {
var that = this;
$.ajax({
url: 'server_side_process_two.aspx',
type: 'POST',
data: { $(that).attr("id") },
success: function() { alert($(that).attr("id")); }
});
});
returns path in the following format:?
C:\Program Files\Microsoft
Office\OFFICE11\WINWORD.EXE
Any idea how to get both functions to return in the same format? Preferably both should return in the basic format without all the extra characters, i.e.
C:\Program Files\Microsoft
Office\OFFICE11\WINWORD.EXE
but not
file:///C:/Program%20Office/OFFICE11/WINWORD.EXE
When you asks for an element's href, you'll get a version of this attribute, processed and cleaned by the browser. So, it really depends on what your aspx script does, but be sure that the URL you're passing to you script through strURLs is something with the appropiate URI, like file:///C:/Program%20Office/OFFICE11/WINWORD.EXE, and not an incorrect and malformed URL like C:\Program Files\Microsoft Office\OFFICE11\WINWORD.EXE.
Don't forget that you can see what you're sending to your script using tools like FireBug in Firefox.
Good luck!
This may just "patch" your problem, but you might just let the upper C# function return "file:///C:/Program%20Office/OFFICE11/WINWORD.EXE"... and then correct the formatting.
string sRtn = "file:///C:/Program%20Office/OFFICE11/WINWORD.EXE";
sRtn = sRtn.Replace("file:///", "");
sRtn = sRtn.Replace("/", "\");
sRtn = sRtn.Replace("%20", " ");
Related
How to stop debugging my js code from browser
function ViewSeatInfo(busNo, scheduleId, seatFare, tripType, dDate, time, numberOfSeat, seatUpdate, seatId) {
totalPrice = 0;
schedule_Id = scheduleId;
bus_No = busNo;
trip_Type = tripType;
d_date = dDate;
_time = time;
mainSeatId = seatId;
window.numberOfSeat = numberOfSeat;
window.seatUpdate = seatUpdate;
currentSell = 0;
var seats = "";
var data;
$.ajax({
type: 'post',
contentType: 'application/json; charset=utf-8',
url: "SellTicketOnline.aspx/ShowBusAndSeatInfo",
data: "{'busNo':'" + busNo + "'," + "'scheduleId':'" + scheduleId + "'}",
async: false,
success: function(response) {
data = response;
},
error: function() {
alert("error");
}
});
seatFare = data.d.BusMainFare;
seat_Fare = seatFare;
baseFare = seatFare;
ShowBusSeatAllocation(data, seatFare);
LoadStationByRouteId();
LoadBoardingPoint();
}
JavaScript for webpages runs in the browser (client-side), means the browser needs to download the file and executing so it must have access to the "original" JS file. So you cannot really stop another developer to look at your code.
What you can do is to make more difficult for peoples to understand and debug your application.
Some possibilities available are:
Various techniques for code obfuscation.
Code hiding using web-socket or similar.
Disable debugger tools like console.log() by overwrite them, example:
(function() {
// disables the use of `console.log`, `console.info`, `console.error`, `console.warn` and others by replacing them with empty functions,
// this makes the use of the debugger harder.
var empty = function() {};
Object.keys(window.console).forEach(function(prop) {
window.console[prop] = empty;
});
console.log('log');
console.info('info');
console.error('error');
console.warn('warn');
})(window);
Some interesting projects and articles:
https://github.com/javascript-obfuscator/javascript-obfuscator
http://www.jsfuck.com/
How to prevent your JavaScript code from being stolen, copied, and viewed?
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.
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/
Is it possible to put a function into a parameter for Jquery Ajax like below. dataType and data are given as functions. dataType returns a value of JSON if the returntype is JSON and text if isJson is false.
dataVal and dataVar are arrays containing the parameter names and values used to construct the data paramater. The result of the data: function would be a string as:
{dataVar[0]:dataVal[0],dataVar[1]:dataVal[1],.....,}
I'm getting an error when I try this, so, just wanted to know if this method was possible.
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
},
data: function () {
var dataString = '{';
for (var i = 0; i < dataVar.length; i++) {
dataString = dataString + dataVar[i] + ':' + dataVal[i] + ',';
}
console.log(dataString);
return dataString + '}';
},
success: function (res) {
dfd.resolve(res);
}
});
}
Edit
As per answers and comments, made the changes. The updated function is as below. This works:
function getAjaxResponse(page, isJson, dataVar, dataVal, dfd) {
$.ajax(page, {
type: 'POST',
dataType: isJson ? "JSON" : "text",
data: function () {
var dataString ="";
for (var i = 0; i < dataVar.length; i++) {
if (i == dataVar.length - 1) {
dataString = dataString + dataVar[i] + '=' + dataVal[i];
} else {
dataString = dataString + dataVar[i] + '=' + dataVal[i] + ',';
}
}
return dataString;
}(),
success: function (res) {
dfd.resolve(res);
}
});
}
And my original question is answered. But apparently, data is not getting accepted.
The return value of the data function is just treated as the parameter name and jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
So, my server is unable to pick up on the proper paramater name.
From the manual:
data
Type: PlainObject or String
So no.
Call the function. Use the return value.
data: function () { ... }();
// ^^ call the function
Not that way. But it will work with a little change:
(function () {
if (isJson == true) {
return "JSON";
} else {
return "text";
}
})()
That should work. You just call the function immidiately after you created it. This way, dataType is a String and the script will work.
Same with data. Also use the (function(){})()-notation here
jquery just adds a : to the end of the request like so:
{dataVar[0]:dataVal[0]}:
No, your devtools display does. However, as you're data string does not contain a = sign, and you send the content as application/x-www-form-urlencoded, the whole body is interpreted as if it was a parameter name.
For sending JSON, you should:
use contentType: "application/json"
use data: JSON.stringify(_.object(dataVar, dataVal))1
to ensure valid JSON is sent with the correct header (and correctly recognised as such at the server).
1: _.object is the object function from Underscore.js which does exactly what you want, but you can use an IEFE as well:
JSON.stringify(function(p,v){var d={};for(var i=0;i<p.length;i++)d[p[i]]=v[i];return d;}(dataVar, dataVal))
You need to call the function with parenthesis like below:
function func1(){
//func1 code in here
}
function func2(func1){
//func2 code in here
//call func1 like this:
func1();
}
So, you can use like this:
data: function () {
//your stuff her
}(); // which mean you are having data()
i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}