Passing jquery variable to ajax data - javascript

I am trying to pass these variables from 3 hidden fields to the data of the the ajax.
I am getting the correct variables. I verified via console.log. I tried to parse json but it didnt for me.
The error i am getting uncaught exception: [Exception... "Could not convert JavaScript argument" nsresult: "0x80570009 (NS_ERROR_XPC_BAD_CONVERT_JS)" location: "JS frame :: http://code.jquery.com/jquery-latest.js :: :: line 7740" data: no]
Line 2
I am trying to pass these variables using the ajax request to my controller. The other variables in the datastring I have no issues at all. When a user clicks on a star rating the values are posted and inserted to a db.
Here are the variables:
var TweetUserId = $(this).parents().prevAll('input[type=hidden:first]') ;
var TweetScreenName = $(this).parents().prevAll('input[type=hidden:second]') ;
var TweetPostText = $(this).parents().prevAll('input[type=hidden:third]') ;
// making it an object didnt work
// TweetUserId = new Object; TweetUserId = (TweetUserId);
// TweetScreenName = new Object; TweetScreenName = (TweetScreenName);
// TweetPostText = new Object; TweetPostText = (TweetPostText);
Here is the request
$.ajax({
url: '/Home/GetRating', //your server side script
dataType: "json",
data: { id: ratingid, value: value, TweetUserId: TweetUserId, TweetScreenName: TweetScreenName, TweetPostText: TweetPostText, tweetday: dateoftweet, tweettime: timeoftweet }, //our data
type: 'POST',
success: function (data) {
//$('#ratemsg').html(data);
msg.html(" The TweetId is " + ratingid + " the vote value is " + value + " " + dateoftweet + " " + timeoftweet );
// console.log(hiddenValue);
},
error: function (jxhr, msg, err) {
// $('#response').append('<li style="color:red">' + msg + '</li>');
msg.html(data);
}
});
});
});

your are using selectors the wrong way and some are invalid :first :second :third
(they should go outside the [type=hidden] and there are no :second :third .. use the :eq() selector instead
You are passing elements instead of their value to the ajax request..
Use this when populating the variables..
var TweetUserId = $(this).parents().prevAll('input[type="hidden"]:eq(0)').val();
var TweetScreenName = $(this).parents().prevAll('input[type="hidden"]:eq(1)').val();
var TweetPostText = $(this).parents().prevAll('input[type="hidden"]:eq(2)').val();
As a general pattern, it is better to cache a jQuery object when you intend to use it multiple times, instead of re-selecting it ..
so you could improve your code with
var hiddenElements = $(this).parents().prevAll('input[type="hidden"]'),
TweetUserId = hiddenElements.eq(0).val(),
TweetScreenName = hiddenElements.eq(1).val(),
TweetPostText = hiddenElements.eq(2).val();

Related

how to store array of objects using localstorage fron one file to other file

I am new to localstorage.I am trying to store json data in one file and retrieving the data in other file.Below is my json data which i have fetched from an url.I have tried storing feeds data using using localstorage now i am tring to fetch the data in other html file.But i am getting only the final object from the feeds.How can i get all the feed objects in other file.
{
"channel":{
"id":9,
"name":"my_house",
"description":"Netduino Plus connected to sensors around the house",
"latitude":"40.44",
"longitude":"-79.9965",
"field1":"Light",
"field2":"Outside Temperature",
"created_at":"2010-12-14T01:20:06Z",
"updated_at":"2017-02-13T09:09:31Z",
"last_entry_id":11664376
},
"feeds":[{
"created_at":"2017-02-13T09:07:16Z",
"entry_id":11664367,
"field1":"196",
"field2":"31.507430997876856"
},{
"created_at":"2017-02-13T09:07:31Z",
"entry_id":11664368,
"field1":"192",
"field2":"30.743099787685775"
},{
"created_at":"2017-02-13T09:07:46Z",
"entry_id":11664369,
"field1":"208",
"field2":"28.280254777070063"
}]}
One.html:-(here i am storing all the feeds data)
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
localStorage.setItem('Created_at', feed.created_at);
var create = localStorage.getItem('Created_at');
console.log(create);
localStorage.setItem('Entry_id', feed.entry_id);
var entry = localStorage.getItem('Entry_id');
console.log(entry);
localStorage.setItem('Field1', feed.field1);
var fd1 = localStorage.getItem('Field1');
console.log(fd1);
localStorage.setItem('Field2', feed.field2);
var fd2 = localStorage.getItem('Field2');
console.log(fd2);
});
other.html:(here i am trying to fetch the localstorage data)
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var create = localStorage.getItem('Created_at');
console.log(create);
document.writeln("<br>Created_at = "+create);
var entry = localStorage.getItem('Entry_id');
document.writeln("<br>Entry_id = "+entry);
var fd1 = localStorage.getItem('Field1');
document.writeln("<br>Field1 = "+fd1);
var fd2 = localStorage.getItem('Field2');
document.writeln("<br>Field2 = "+fd2);
}
</script>
Because you are over-riding the localStorage item in your for Loop.
The required for loop when simplified looks like:
json1.feeds.forEach(function(feed, i) {
localStorage.setItem('Created_at', feed.created_at); //Gets over-riden on every iteration
localStorage.setItem('Field1', feed.field1);});
That's why after the loop is completed. The Created_at field would only have the value of the most recently processed item in the array i.e. the last element. What you need to is create a corresponding array where each element would correspond to a feed item that you are reading from the API response.
Now, localStorage can simply store key value pairs. It doesn't have support for types like array. What you can do is something on these lines (Untested Code):
json1.feeds.forEach(function(feed, i) {
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
});
Yes, You will have to check if feedsArray key exists or not and set it as an empty array the first time. I have deliberately not put in the entire code as it is quite simple and should be good exercise for you.
So, once you are done and you want to read all the feeds from localStorage. Just get the feedsArray key and parse it and then iterate over it. Put simply, the basic idea is to have a JSON array of feeds and store it as a string with key feedsArray in localStorage.
The code snippet I have given above can get you started toward the solution I propose.
Relevant SO Post
The answer for the above issue is below.through which i got the solution.But not too sure if der is any wrong.
one.html:
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are :\nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]')
}
});
other.html:
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]');
//feedsArray.push(savedArr);
}
console.log(savedArr);
document.writeln("<br>FEEDS = "+savedArr);
}
</script

How to construct and invoke method or function in generic jquery ajax call

I'm trying to construct a generic Ajax function by passing the few properties required by a jQuery Ajax object as object parameters. I'm stuck on one piece of the puzzle, that is the proper way to pass the callback function within "done". The idea is to replace about 10 ajax functions in my .js file with just one ajax function.
Here's my code:
// The generic ajax function, which will be called by various functions
// and passing variable parameters, different controller urls, different
// GET or POST types, different POST data sets, and finally, different
// callback functions.
function generalAjax(params){
$.ajax({
url: params.url,
type: params.type,
data : params.formData,
dataType : 'json'
}).done(function( data ) {
params.callback; // <-- Trying to get this line to work.
}).fail(function(jqXHR, textStatus){
var string = "Ajax request failed : " + textStatus + " - " + jqXHR.responseText;
$("#diag").html(string);
});
}
// Create the prototype
function ajaxParams(url, type, data, callback) {
this.url = url;
this.type = type;
this.formData = data;
this.callback = callback;
}
// A button in my php file will call this function.
function nameSearch(){
var url = "/ajax/name_search/";
var type = "POST";
var formData = { 'q' : document.getElementsByName("searchname")[0].value };
var callback = nameSearchCallback; // Specific method for this event
var params = new ajaxParams(url, type, formData, callback);
generalAjax(params);
}
// One specific callback function for one specific event trigger.
function nameSearchCallback(e){
var string = "";
$.each(e,function(k,v){
string += k + " = " + v + "\n";
if(v instanceof Object == true){
string += "<ul>\n";
$.each(v,function(kk,vv){
string += "<li>" + kk + " = " + vv + "</li>\n";
});
string += "</ul>\n";
}
});
$("#form-panel").html(string);
}
15 lines down, you can see where I've substituted parameters.callback for a hard coded script or direct call to a specific function. What I want is for that line to call different functions or methods, depending on the needs of the instantiated object calling the genericAjax function.
Depending upon whether I try params.callback or params.callback(), at best, nothing happens, or at worst, the page refreshes and in my javascript console I get a TypeError : a is undefined in the jquery library file.
I have also tried var callback = nameSearchCallback; and var callback = nameSearchCallback(); I have also skipping the reference to the nameSearchCallback() function, and just writing the function into params.callback as
params.callback = function(){
var string = "";
$.each(e,function(k,v){
string += k + " = " + v + "\n";
if(v instanceof Object == true){
string += "<ul>\n";
$.each(v,function(kk,vv){
string += "<li>" + kk + " = " + vv + "</li>\n";
});
string += "</ul>\n";
}
});
$("#diag").html(string);
}
I have a working solution to my problem, but it isn't a specific answer to my question. Since nobody is answering the question, I guess I'll post the general solution.
I came across a question with an answer on how to make dynamic functions using arrays. I applied this answer to the above question.
I declare an array:
var dyn_functions = [];
Every time I want to define a callback function, I write something like this:
// Where data is an object and data['string'] is a property returned in jsson format from a php controller.
dyn_functions['nameSearchCallback'] = function (data){
var string = "<h3>Search results:</h3>\n";
string += "<blockquote>" + data['string'] + "</blockquote>";
$("#form-panel").html(string);
}
Every callback function will have its own name.
Your event trigger will call its own function, something like
var n = "Mark";
<button onClick='nameSearch(n);return false;'>Search</button>
In your script file, the event function nameSearch looks like this:
function nameSearch(n){
var url = "/ajax/name_search/"; //This is the name of a php file or a function in an MVC controller
var type = "POST"; //This can also be GET
var formData = { 'q' : n }; //If your type is "GET", then this should be empty, like "", and you could pass `n` as a url query string or a uri segment.
var callback = "nameSearchCallback"; //Remember the dynFunction callback above? This is the name of it.
var params = new ajaxParams(url, type, formData, callback);//Make a params object to pass our params to the generic ajax function.
generalAjax(params); //Calling the generic ajax function.
}
You need to prototype the params property constructor:
// The prototype constructor for the general Ajax parameters.
function ajaxParams(url, type, data, callback) {
this.url = url;
this.type = type;
this.formData = data;
this.callback = callback;
}
...and finally, we have one single ajax function that serves infinite n of calls:
// The general Ajax function.
function generalAjax(params){
$.ajax({
url: params.url,
type: params.type,
data : params.formData,
dataType : 'json'
}).done(function( data ) {
var callback = dyn_functions[params.callback](data);
}).fail(function(jqXHR, textStatus){
var string = "Ajax request failed : " + textStatus + " - " + jqXHR.responseText;
$("#diag").html(string);
});
}
So, the whole thing all together will look like this:
// The prototype constructor for the general Ajax parameters.
function ajaxParams(url, type, data, callback) {
this.url = url;
this.type = type;
this.formData = data;
this.callback = callback;
}
// The general Ajax function.
function generalAjax(params){
$.ajax({
url: params.url,
type: params.type,
data : params.formData,
dataType : 'json'
}).done(function( data ) {
var callback = dyn_functions[params.callback](data);
}).fail(function(jqXHR, textStatus){
var string = "Ajax request failed : " + textStatus + " - " + jqXHR.responseText;
$("#diag").html(string);
});
}
//The global dyn_functions object, to be used for all scripts.
var dyn_functions = [];
dyn_functions['nameSearchCallback'] = function (data){
var string = "<h3>Search results:</h3>\n";
string += "<blockquote>" + data['string'] + "</blockquote>";
$("#form-panel").html(string);
}
function nameSearch(n){
var url = "/ajax/name_search/";
var type = "POST";
var formData = { 'q' : n }; //If your type is "GET", then this should be empty, like "", and you could pass `n` as a url query string or a uri segment.
var callback = "nameSearchCallback";
var params = new ajaxParams(url, type, formData, callback);
generalAjax(params);
}

Javascript Variables Not Globally Returning / Adding Together

I'm trying to add both Facebook and Twitter share counters together, however all my efforts have failed.
<script>
tweets = 0;
function getTwitterCount(url){
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data){
tweets = data.count;
$('#twitterCount').html(tweets);
return true;
});
}
var urlBase='http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: function(data) {
showCount(data);
}
});
var fbshares = 0;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
}
var TotalShares = tweets + fbshares;
$('#total-share-count').html(TotalShares);
</script>
I could really do with some outside insight as I've been working crazy to get this website up and running ASAP and I'm probably overlooking the most obvious of things...
Console Log Reads:
Uncaught ReferenceError: fbshares is not defined
sdk.js:64 Invalid App Id: Must be a number or numeric string representing the application id.
card.html?v=2:79 Uncaught ReferenceError: I18n is not defined
sdk.js:64 FB.getLoginStatus() called before calling FB.init().
However despite this message, the Facebook and Twitter counters are working 100%, I just cannot get them to add together.
Best Regards,
Tim
Here's a solution:
var tweets;
function getTwitterCount(url) {
$.getJSON('http://urls.api.twitter.com/1/urls/count.json?url=' + url + '&callback=?', function(data) {
tweets = data.count;
$('#twitterCount').html(tweets);
showTotal();
});
}
var urlBase = 'http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html';
getTwitterCount(urlBase);
$.ajax({
type: 'GET',
url: 'https://graph.facebook.com/http://abcdfav4.com/About/KickStarterCampaign/Rewards/ThePeaceSensation.html',
success: showCount
});
var fbshares;
function showCount(responseText) {
// Save the parsed JSON
var json = responseText;
// Check if the response contains a 'shares' property
// If it doesn't, we can just exit this function
if (!json.hasOwnProperty('shares'))
return;
// A shares property and value must exist, update
// the span element with the share count
fbshares = json.shares;
$('#fb-share-count').html(fbshares);
showTotal();
}
function showTotal() {
if (tweets !== undefined && fbshares !== undefined)
$('#total-share-count').html(tweets + fbshares);
}
Basically showTotal attempts to sum the two values after each callback. When both values are defined, it will place the sum into the HTML.

How to call server side function from json?

this is my code
<script type="text/JavaScript">
var myarray = new array();
function getsvg1() {
$.ajax({
alert("hello");
type: "post",
url: "WebForm1.aspx/getsvg1",
alert("abc");
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var cars = response.d;
alert(cars);
alert("hi");
},
failure: function (msg) {
$('#output').text(msg);
}
});
}
</SCRIPT>
webservices
[System.Web.Services.WebMethod]
public static ArrayList getsvg1()
{
XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/NewFolder1/10000.svg"));
//XDocument doc = XDocument.Load(System.Web.HttpContext.Current.Server.MapPath("~/Uploads/Orders/100001_PRO/2/svg0.svg"));
//XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
//var g = doc.Descendants(ns1 + "image").FirstOrDefault();
// XDocument doc = XDocument.Load(Server.MapPath("~/excelfiles/svg0.svg"));
XNamespace ns1 = "http://www.w3.org/2000/svg";
//Namespace of a root element can also be retrieved like this:
//XNamespace ns1 = doc.Root.GetDefaultNamespace();
var retrieveimage = doc.Descendants(ns1 + "image").FirstOrDefault();
var retrivetext = doc.Descendants(ns1 + "g").FirstOrDefault();
ArrayList arlelem = new ArrayList();
foreach (XElement element in doc.Descendants(ns1 + "g"))
{
//string[] parts = element.Split(',');
Console.WriteLine(element);
arlelem.Add(element);
}
// var retrivetext1 = doc.Descendants(ns1 + "text").SelectMany(i => i.ElementExtensions.Select(e => e.GetObject<XElement>().Attribute("url").Value)).ToArray();
//var retrivetext = doc.Descendants(ns1 + "text").All();
string v = arlelem[1].ToString();
string values = retrieveimage.ToString();
string values1 = retrivetext.ToString();
char[] delimiterChars1 = { ' ', ',', '"', '\\', '\t', '=' };
//string text = "one\ttwo three:four,five six seven";
//System.Console.WriteLine("Original text: '{0}'", text);
string[] words = values.Split(delimiterChars1);
string[] words2 = values1.Split(delimiterChars1);
string[] newword = v.Split(delimiterChars1);
//Session["newimgwidth"] = words[15];
return arlelem;
}
alert is not coming for cars values and breakpoint not going for success and failure. in this example i m calling server side function from
json that function result
To start with your ajax request is filled with syntax errors.
The $.ajax({ }) block cannot have a alert("hello"); inside it
Remove alert("abc"); too
use console.log() instead of alerts in your success method, this is not one of the error but a suggestion/advice.
What is your method returning in case of error ? In your ajax error method it seems to be expecting a string value.
Why are you using type: "post" when you are not posting any data to your method. Use a 'get' instead.
To debug your server side code, try opening the WebForm1.aspx/getsvg1 url in your browser window and see if you get the expected response. If all is well next try sending an ajax request using a client like postman rest client to check the response again.
Hope this helps.
you can use jQuery for this:
$.getJSON( "http://server.com/webservice", function( data ) {
console.log(JSON.stringify(data));
}
See more details at: http://api.jquery.com/jquery.getJSON/
{key,value } it allow json data.means already availble options or new define json value only. you can enter,if you try to alert("hello") it doest allow.so it stopped.so,try without alert message use inside brackets {}.

$.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