Group the names when age are the same in javascript - javascript

I am getting a list of members using jQuery and iterating over each of them to get a name and age. What I want to do is store the names together if they have the same age. Something like:
{
31: { John, Mary },
24: { Paul, Peter }
}
I can't seem to store them correctly.
EDIT:
This is what I have so far:
$('span.members a').each(function () {
$.ajax({
url: $(this).attr('href'),
success: function (result) {
name = $(result).find('tr td:contains("Username:")').next().text().trim();
age = $(result).find('tr td:contains("Age:")').next().text().trim();
}
});
});
EDIT:
This is the source HTML:
<table cellpadding="0" cellspacing="0" border="0" width="96%" class="box" id="testProf" style="border-spacing:0;">
<tr>
<td class="top" colspan="4">
JohnRandall
</td>
</tr>
<tr>
<td style="padding:4px" width="100" height="1" align="left">
Username:
</td>
<td style="padding:4px" height="1">
JohnRandall
</td>
<td style="padding:4px" width="130" height="1">
Add as friend
</td>
<td width="300" style="padding:0px;margin:0;overflow:hidden;" rowspan="11" valign="top"><img src="//id.crimecdn.com/0gd74.jpg" width="300" style="display: block;max-height:2000px;"></td>
</tr>
<tr class="odd">
<td style="padding:4px" align="left" height="1">
Status:
</td>
<td style="padding:4px" height="1">
<span style="color:#00ff00;" title="Online Now">•</span> <span style="color:#00ff00;">Online</span>
</td>
<td style="padding:4px" height="1">
Add as enemy
</td>
</tr>
<tr>
<td style="padding:4px" align="left" height="1">
Crew: </td>
<td height="1">
<img src="//id.crimecdn.com/o7yft.jpg" width="59" height="33" style="border:0;display: block;">
</td>
<td style="padding:4px" height="1">
Send message
</td>
</tr>
<tr class="odd">
<td style="padding:4px" align="left" height="1">
Wealth:
</td>
<td style="padding:4px" height="1">
Dangerously Healthy (?)
</td>
<td style="padding:4px" height="1">
Send money
</td>
</tr>
<tr>
<td style="padding:4px" align="left" height="1">
Age:
</td>
<td style="padding:4px" height="1">
28
</td>
<td style="padding:4px" height="1">
Send escrow
</td>
</tr>
<tr class="odd">
<td style="padding:4px" align="left" height="1">
Gender:
</td>
<td style="padding:4px" height="1">
Male
</td>
<td style="padding:4px" height="1">
Kill search
</td>
</tr>
<tr>
<td style="padding:4px" align="left" height="1">
Last Active:
</td>
<td style="padding:4px" height="1">
Just now
</td>
<td style="padding:4px" height="1">
Compare
</td>
</tr>
<tr class="odd">
<td style="padding:4px" align="left" height="1">
Date Joined:
</td>
<td style="padding:4px" height="1">
2015-12-16
</td>
<td style="padding:4px" height="1">
!--overlord2.php?id=lookup&prefill=JohnRandall-->
</td>
</tr>
<tr>
<td style="padding:4px" align="left" height="1">
Messages:
</td>
<td style="padding:4px" height="1">
2
</td>
<td style="padding:4px" height="1">
</td>
</tr>
<tr>
<td class="backdrop" style="padding: 4px;" colspan="3" height="1">
<img src="//caviar.dtmcdn.com/render/45865/12"> Edit my profile<p class="royal">Player quote</p>
</td>
</tr>
<tr>
<td colspan="3" valign="top" style="background-color:#2a2a2a !important;padding: 0 !important;">
<div style="width:480px; overflow:hidden;">
92
</div>
</td>
</tr>

Step 1 : the target datastructure :
There are two issues with your data structure :
You're forgetting to put the names between quotes. John should be "John". Mary should be "Mary". etc.
You're trying to use an object for [ "John", "Mary" ] and [ "Paul", "Peter" ], where you should be using an array.
So, the data structure you're looking for, is this :
{
31 : [ "John", "Mary" ],
24 : [ "Paul", "Peter" ]
}
Step 2 : fetching the data from the HTML input :
I suggest you make this small adjustment to your JavaScript code :
var source = [];
$('span.members a').each(function () {
$.ajax({
url: $(this).attr('href'),
success: function (result) {
source.push({
name : $(result).find('tr td:contains("Username:")').next().text().trim(),
age : $(result).find('tr td:contains("Age:")').next().text().trim()
});
}
});
});
(see also this Fiddle)
This fetches the data from your HTML input and puts it into a data structure that looks like this :
var source = [{
name : "Paul",
age : 24
}, {
name : "Mary",
age : 31
}, {
name : "Peter",
age : 24
}, {
name : "John",
age : 31
}];
Step 3 : converting to the right data structure :
Once you fetched all the data, you only need to convert your data from the source data structure to the target data structure, which is as simple as this :
var convert = function(source) {
var output = {};
for(var i = 0; i < source.length; i++) {
if(output[source[i].age]) {
output[source[i].age].push(source[i].name);
} else {
output[source[i].age] = [source[i].name];
}
}
return output;
}
(see also this Fiddle)
Putting the pieces of the puzzle together :
You have to wait with executing your convert function until all of your Ajax calls have finished.
For example, you could do something like ...
if (source.length === numberOfMembers) {
target = convert(source);
}
... right behind the source.push(...) statement.
So if you put all the pieces of the puzzle together, you should get something like this :
var source = [];
var target;
var $members = $('span.members a');
var numberOfMembers = $members.size();
var convert = function(source) {
var output = {};
for(var i = 0; i < source.length; i++) {
if(output[source[i].age]) {
output[source[i].age].push(source[i].name);
} else {
output[source[i].age] = [source[i].name];
}
}
return output;
}
$members.each(function () {
$.ajax({
url: $(this).attr('href'),
success: function (result) {
source.push({
name : $(result).find('tr td:contains("Username:")').next().text().trim(),
age : $(result).find('tr td:contains("Age:")').next().text().trim()
});
if (source.length === numberOfMembers) {
target = convert(source);
}
}
});
});

This should give you some idea of what to do:
abcArr = [["Paul", 24], ["Mary", 31], ["Peter",24],["John",31]];
var items = {}, base, key;
$.each(abcArr, function(index, val) {
key = val[1];
users = [];
if (items[key]) {
items[key].push(val[0]);
}
else {
users.push(val[0])
items[key] = users;
}
});
var outputArr = [];
$.each(items, function(key, val) {
outputArr.push([key, val]);
});
// outputArr contains the result
document.body.innerHTML = JSON.stringify(outputArr);
https://jsfiddle.net/rennomarcus/7Lvy0w1t/
I got the idea from this topic: jquery array group by

Related

How do i iterate over array of json objects using ng-repeat in angular js?

i am trying to iterate over array of objects in angular js but i am getting error as cannot set property of undefined even though i had defined it.
Please find my code below :
var app = angular.module('myDemoApp', []);
app.service('MyTaskService', function($http) {
var services = {
userList: userList,
};
function userList(req) {
if (req == undefined)
req = {};
return $http({
url: "https://jsonplaceholder.typicode.com/posts",
method: "GET",
data: req
});
}
return services;
});
app.controller('MyTaskController', function($scope, MyTaskService) {
$scope.resp = {};
$scope.getPrjDetails = function() {
try {
var promise = MyTaskService.userList();
promise.then(function (sucResp) {
try {
$scope.resp = sucResp.data;
} catch (exception) {
console.log(exception);
return;
}
}
, function (errResp) {
console.log(errResp);
return;
});
} catch (exception) {
console.log(exception);
return;
}
}
});
Find my template :
<ul>
<li ng-repeat="myData in resp">{{myData.id}}</li>
</ul>
how can i iterate over all the json values and display in my textboxes in template or my list?
<div ng-app="myDemoApp">
<div ng-controller="MyTaskController">
<table tyle="float:right;">
<tr><h3>New Project Form</h3></tr>
<tr>
<td class='padding-to-controls'>Get Project Details</td>
<td class='padding-to-controls'>
<select ng-change="getPrjDetails()" ng-model="select_project" >
<option value=''>Select Project Details</option>
<option value='get-details'>Get Project Details</option>
</select>
</td>
</tr>
<tr>
<td class='padding-to-controls'>New Project Name <span>*</span></td>
<td class='padding-to-controls'> <input type = 'text' ng-model="project_name" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Assign location to project <span>*</span></td>
<td class='padding-to-controls'> <input type = 'text' ng-model="assign_location" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Area </td>
<td class='padding-to-controls'><input type = 'text' ng-model="area" ></td>
</tr>
<tr>
<td class='padding-to-controls'>City</td>
<td class='padding-to-controls'><input type = 'text' ng-model="city" ></td>
</tr>
<tr>
<td class='padding-to-controls'>State </td>
<td class='padding-to-controls'><input type = 'text' ng-model="state" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Cluster</td>
<td class='padding-to-controls'><input type = 'text' ng-model="cluster" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Region</td>
<td class='padding-to-controls'><input type = 'text' ng-model="region" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Type <span>*</span> </td>
<td class='padding-to-controls'><input type = 'text' ng-model="type" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Priority <span>*</span></td>
<td class='padding-to-controls'><input type = 'text' ng-model="priority" ></td>
</tr>
<tr>
<td class='padding-to-controls'>Name of approver<span>*</span></td>
<td class='padding-to-controls'><input type = 'text' ng-model="name_approver" ></td>
</tr>
<tr>
<td class='padding-to-controls'></td>
<td class='padding-to-controls'><button ng-click="getPrjDetails()">EDIT</button></td>
</tr>
</table>
</div>
</div>
please find link to my json i am trying to access :: https://jsonplaceholder.typicode.com/posts
When dom is first rendered, angular start searching for resp.data, which in your case is undefined and so angular will complain.
You don't need to pass $scope variables to any of the controller functions. They can access it directly.
In your whole code, you are never ever setting $scope.resp.
Your html context is way different from what you are trying to do. So I have modified it a bit. Try following code:
HTML:
<div ng-app="myDemoApp">
<div ng-controller="MyTaskController">
<h3>Feeds</h3>
<button ng-click="getPrjDetails()">Load</button>
<div ng-repeat="myData in resp.data">
<span> {{myData.id}}</span>
<input ng-model="myData.title" type="text" />
</div>
</div>
Angular
app.controller('MyTaskController', function($scope, MyTaskService) {
// Required
$scope.resp = {
data: []
}
$scope.getPrjDetails = function() {
try {
var promise = MyTaskService.userList();
promise.then(function(sucResp) {
try {
var resp = sucResp.data || [];
// You must update $scope.resp.data
$scope.resp.data = resp;
console.log($scope.resp.data);
} catch (exception) {
console.log(exception);
return;
}
}, function(errResp) {
console.log(errResp);
return;
});
} catch (exception) {
console.log(exception);
return;
}
}
})
fiddle working

How can get second item of array with x-ray

I want to get the second item in the game: ['.contenedor-numero'], array :
var site = 'http://www.laliga.es/en/';
var url = 'liga-bbva';
var address = site + url;
x(address, '#div_clasf_38_1_3 table tbody tr', [{
rank: ".posicion",
game: ['.contenedor-numero'],
score: ".contenedor-numero.puntos",
name: x(".contenedor-nombre a", {
Abbreviation: '.nombre-equipo-clasificacion-movil',
complete: '.nombre-equipo-clasificacion'
}),
}])(function(err, data) {
console.log(data);
});
the html code struct is this :
<tr class=" ">
<td class="posicion">1</td>
<td class="contenedor-flecha"></td>
<td class="contenedor-nombre">
<a href="http://www.laliga.es/en/liga-bbva/barcelona">
<span class="escudo-equipo-clasificacion">
<span class="sprite-escudos-xs barcelona"></span>
</span>
<span class="nombre-equipo-clasificacion">FC Barcelona</span>
<span class="nombre-equipo-clasificacion-movil">FCB</span>
</a>
</td>
<td class="contenedor-numero puntos">91</td>
<td class="contenedor-numero ">38</td>
<td class="contenedor-numero no-sidebar">29</td>
<td class="contenedor-numero no-sidebar">4</td>
<td class="contenedor-numero no-sidebar">5</td>
<td class="contenedor-numero no-sidebar">112</td>
<td class="contenedor-numero no-sidebar">29</td>
</tr>
I want to scraping <td> elements that has class="contenedor-numero " with value of 38. But when I use ['.contenedor-numero'][1] nothing give me!
How can I get second element of that array?
you could do this:
x(html2, 'tr', [{
rank: ".posicion",
game: ['.contenedor-numero'],
score: ".contenedor-numero.puntos",
name: x(".contenedor-nombre a", {
Abbreviation: '.nombre-equipo-clasificacion-movil',
complete: '.nombre-equipo-clasificacion'
}),
value38: 'td:nth-of-type(5)'
}])(function(err, data) {
console.log(data);
});

Grabbing data from an array using for loop to populate a table

Problem
I'm trying to iterate over an array of objects using a for loop, but instead of getting all the items in the array that I actually see when I console.log(arr[i].Sand) I get the same number eleven times in my HTML.
script.js
$(function(){
$.ajax({
url: "https://sheetsu.com/apis/fef35fba",
method: "GET",
dataType: "json",
}).then(function(spreadsheet){
// Array of objects
var arr = spreadsheet.result;
for (i = 1; i < arr.length; i++) {
console.log(arr[i].Sand); // Just the volume of sand in tonnes
var sand = arr[i].Sand // Volume of Sand in tonnes
var salt = arr[i].Salt // Volume of Salt in tonnes
var snow = arr[i].Snow // Snow Removal total in dollars
// Changes the numbers in the table
$(".sand").html(sand);
}
})
});
spreadsheet.result
index.html
<table>
<thead>
<tr>
<th class="year"></th>
<th>
<img src="img/sand-2.png" alt="" class="icons">
<p>Volume of Sand</p>
<p class="paren">(in tonnes)</p>
</th>
<th>
<img src="img/salt-3.png" alt="" class="icons">
<p>Volume of Salt</p>
<p class="paren">(in tonnes)</p>
</th>
<th>
<img src="img/snow-3.png" alt="" class="icons">
<p>Snow Removal</p>
<p class="paren">(total in dollars)</p>
</th>
</tr>
</thead>
<tbody>
<tr>
<td class="year">2016</th>
<td class="sand">-<span class="asterisk">*</span></td>
<td class="salt">-<span class="asterisk">*</span></td>
<td class="snow">-<span class="asterisk">*</span></td>
</tr>
<tr>
<td class="year">2015</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2014</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2013</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2012</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2011</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2010</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2009</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2008</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr>
<td class="year">2007</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
<tr class="last">
<td class="year">2006</th>
<td class="sand">-</td>
<td class="salt">-</td>
<td class="snow">-</td>
</tr>
</tbody>
</table>
while I was generating the code to answer this, someone changed your ajax call.
Here's the code reworked so it should help.
$(function(){
$.ajax({
url: "https://sheetsu.com/apis/fef35fba",
method: "GET",
dataType: "json",
}).then(function(spreadsheet){
// Array of objects
var arr = spreadsheet.result;
for (i =0; i < arr.length; i++) {
console.log(arr[i].Sand); // Just the volume of sand in tonnes
sand = arr[i].Sand // Volume of Sand in tonnes
salt = arr[i].Salt // Volume of Salt in tonnes
snow = arr[i].Snow // Snow Removal total in dollars
year = arr[i].Year; //We need the year to find the right row
// Changes the numbers in the table
$("tr").each(function(){
//We need to find the correct TR object.
//Remove Any spacing outside the html to make sure we don't get anything extra.
// We need to locate the ROW that has the right year so we can populate ONLY it's columns. an id or class based off year would have made this easier and less resource expensive.
if($(this).find(".year").html().trim() == year){
$(this).find(".sand").html(sand);
$(this).find(".salt").html(salt);
$(this).find(".snow").html(snow);
}
});
}
})
});
Here is a JSFiddle to show it:
https://jsfiddle.net/g6vn4Lf6/
This line:
$(".sand").html(sand);
Finds all elements with class="sand" and then sets the inner html of all of them to the value of sand. Instead you need to label each row of the table with html (eg <tr class="year-2015">), then you can select the right td element by using something like $(".year-2015 .sand").
First, you should change the key of the year in your json response to "year" instead of ""
Then you should associate that year with the tr's in some way, such as
<tr year='2016'>
Then in your for loop you can select just the .sand element that is a child of the correct tr.
$("tr[year='" + arr[i].year + "'] .sand").html(sand)
perhaps you should dynamically add a row for each of the results you receive from your ajax call like shown below:
$(document).ready(function() {
var arrayResults = [
{ Year: '2016', Sand: '123', Salt: '234', Snow: '345' },
{ Year: '2015', Sand: '222', Salt: '333', Snow: '444' },
{ Year: '2014', Sand: '555', Salt: '111', Snow: '888' },
{ Year: '2013', Sand: '121', Salt: '232', Snow: '343' },
{ Year: '2012', Sand: '454', Salt: '565', Snow: '676' }
];
for(var i = 0; i < arrayResults.length; i++) {
var newRow = '<tr>';
newRow += '<td class="year">' + arrayResults[i].Year + '</td>';
newRow += '<td class="sand">' + arrayResults[i].Sand + '</td>';
newRow += '<td class="salt">' + arrayResults[i].Salt + '</td>';
newRow += '<td class="snow">' + arrayResults[i].Snow + '</td>';
newRow += '</tr>';
$('tbody').append(newRow);
}
});
th, td {
border: 1px solid black;
padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr><th>year</th><th>sand</th><th>salt</th><th>snow</th></tr>
</thead>
<tbody>
</tbody>
</table>

Javascript in Ms CRM (with odata query) is not working?

I created a javaScript(by the way i learned it yesterday only )
this script is set to fire upon OnSave event of Accounts entity .
I build a odata query using query builder tool that i found on Internet which is supposed to retrive all the tasks ($select=ActivityId,CreatedOn ) and whcih are created before 2015-01-26T18:30:00.000Z ($filter=CreatedOn ge datetime'2015-01-26T18:30:00.000Z')
here is the actual query from query builder :
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/TaskSet?$select=ActivityId,CreatedOn&$filter=CreatedOn ge datetime'2015-01-26T18:30:00.000Z'",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
async: true,
success: function (data, textStatus, xhr) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var ActivityId = results[i].ActivityId;
var CreatedOn = results[i].CreatedOn;
}
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
in the query builder it returns result :
[
{
"CreatedOn": "/Date(1422342587000)/",
"ActivityId": "c23ba479-f3a5-e411-80dc-c4346bada6a4"
},
{
"CreatedOn": "/Date(1422342783000)/",
"ActivityId": "ba7754ee-f3a5-e411-80dc-c4346bada6a4"
},
{
"CreatedOn": "/Date(1422343425000)/",
"ActivityId": "12d40a6d-f5a5-e411-80dc-c4346bada6a4"
}
]
in the result i found that created on returns date as value "CreatedOn": "/Date(1422343425000)/", ..
I wanted to retrive all the tasks created 7 days prior to creating an new record in Accounts entity ..So i wrote logic got the current dat in terms of generic value var current_date = Date().valueOf() and subtracted 7 days in milisecs (7*24*60*60*1000=604800000)
var week_earlier = current_date - 604800000;
in the code below you can see what i did
function retrive()
{
//var date =2015-01-26T18:30:00.000Z;
var current_date = Date().valueOf();
var week_earlier = current_date - 604800000;
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
url: Xrm.Page.context.getClientUrl() + "/XRMServices/2011/OrganizationData.svc/TaskSet?$select=ActivityId,CreatedOn&$filter=CreatedOn ge datetime'"+week_earlier+"'",
beforeSend: function (XMLHttpRequest) {
XMLHttpRequest.setRequestHeader("Accept", "application/json");
},
async: true,
success: function (data, textStatus, xhr) {
var results = data.d.results;
for (var i = 0; i < results.length; i++) {
var ActivityId = results[i].ActivityId;
var CreatedOn = results[i].CreatedOn;
}
alert("number of records found :"+results.length);
},
error: function (xhr, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
}
but its not working....it shows
"error Bad Request"
and i also tried quering with the in the url of browser with
https://avikcompany.crm5.dynamics.com/XRMServices/2011/OrganizationData.svc/TaskSet?$select=CreatedOn,ActivityId&$filter=CreatedOn ge datetime'1422342587000'(this '1422342587000' is present in result of the previously fired query).
but it also threw an error
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link rel="stylesheet" type="text/css" href="ErrorPageTemplate.css" >
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTTP 400 Bad Request</title>
<script src="errorPageStrings.js" language="javascript" type="text/javascript">
</script>
<script src="httpErrorPagesScripts.js" language="javascript" type="text/javascript">
</script>
</head>
<body onLoad="javascript:initHomepage(); expandCollapse('infoBlockID', true); initGoBack(); initMoreInfo('infoBlockID');">
<table width="730" cellpadding="0" cellspacing="0" border="0">
<!-- Error title -->
<tr>
<td id="infoIconAlign" width="60" align="left" valign="top" rowspan="2">
<img src="info_48.png" id="infoIcon" alt="Info icon">
</td>
<td id="mainTitleAlign" valign="middle" align="left" width="*">
<h1 id="mainTitle">The webpage cannot be found</h1>
</td>
</tr>
<tr>
<!-- This row is for HTTP status code, as well as the divider-->
<td id="http400Align" class="errorCodeAndDivider" align="right"><ID id="http400"> HTTP 400</ID>
<div class="divider"></div>
</td>
</tr>
<!-- Error Body -->
<!-- What you can do -->
<tr>
<td>
</td>
<td id="likelyCausesAlign" valign="top" align="left">
<h3 id="likelyCauses">Most likely causes:</h3>
<ul>
<li id="causeErrorInAddress">There might be a typing error in the address.</li>
<li id="causeLinkOutOfDate">If you clicked on a link, it may be out of date.</li>
</ul>
</td>
</tr>
<tr>
<td>
</td>
<td id="whatToTryAlign" valign="top" align="left">
<h2 id="whatToTry">What you can try:</h2>
</td>
</tr>
<!-- retype address -->
<tr>
<td >
</td>
<td id="retypeAddressAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="bullet.png" border="0" alt="" class="actionIcon">
</td>
<td valign="top">
<ID id="retypeAddress">Retype the address.</ID>
</td>
<tr>
</table>
</h4>
</td>
</tr>
<!-- back to previous page -->
<tr>
<td >
</td>
<td id="goBackAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="bullet.png" border="0" alt="" class="actionIcon">
</td>
<td valign="top">
<span id="goBackContainer"></span><noscript id="goBack">Go back to the previous page.</noscript>
</td>
</tr>
</table>
</h4>
</td>
</tr>
<!-- top level domain-->
<tr>
<td >
</td>
<td id="mainSiteAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="bullet.png" border="0" alt="" class="actionIcon">
</td>
<td valign="top">
<ID id="mainSite1">Go to </ID><span id="homepageContainer"><noscript id="mainSite2">the main site</noscript></span><ID id="mainSite3"> and look for the information you want.</ID>
</td>
</tr>
</table>
</h4>
</td>
</tr>
<!-- InfoBlock -->
<tr>
<td id="infoBlockAlign" align="right" valign="top">
</td>
<td id="moreInfoAlign" align="left" valign="middle">
<h4>
<table>
<tr>
<td valign="top">
<img src="down.png" id="infoBlockIDImage" border="0" class="actionIcon" alt="More information">
</td>
<td valign="top">
<span id="moreInfoContainer"></span>
<noscript><ID id="moreInformation">More information</ID></noscript>
</td>
</tr>
</table>
</h4>
<div id="infoBlockID" class="infoBlock">
<p id="errorExplanation">This error (HTTP 400 Bad Request) means that Internet Explorer was able to connect to the web server, but the webpage could not be found because of a problem with the address.</p>
<p id="moreInfoSeeHelp">For more information about HTTP errors, see Help.</p>
</div>
</td>
</tr>
</table>
</body>
</html>
Can any body tell me where i went wrong ?
(I am asuming the date value i mentioned is not accepeted by the crm odata service )
Or how to convert date to this format "yyyy-mm-ddThh:mm:ss.uuuZ"
You can easily get the date in that format by using toISOString();
http://jsfiddle.net/j5m97nfv/3/
var current_date = new Date().valueOf();
var week_earlier = new Date(current_date - 604800000);
var n = week_earlier.toISOString();
One problem you have in your code above is you are not constructing a new Date object. Your current_date is actually returning a date string that is not the date's representation in milliseconds. You need new Date();

$.ajax not working in chrome and firefox but is working in IE

I have the following code. It works fine in IE but not in Chrome and Firefox. There is no error displayed. It just doesn't get the value entered. Can someone help me fix the problem. Thanks in advance.
File 'main.php'
---------------
<tr>
<td width="11%" class="style171"></td>
<td width="55%" bgcolor="#A8D3FF" class="style171"><strong>APPROVE</strong></td>
<td width="16%" bgcolor="#A8D3FF" align="center"><input type="radio" name="approve" id="approve" value="1" <?php if ($approve== '1') echo "checked"; ?> /></td>
<td width="18%"></td>
</tr>
<tr>
<td width="11%" class="style171"></td>
<td class="style171" bgcolor="#A8D3FF"><strong>NOT APPROVE</strong></td>
<td bgcolor="#A8D3FF" align="center"><input type="radio" name="approve" id="approve" value="2" onClick="processForm()" <?php if ($approve== '2') echo "checked"; ?> /></td>
<td width="18%"></td>
</tr>
<tr>
<td width="11%" class="style171"></td>
<td colspan="2" align="left"><div id="div_data"></div></td>
<td width="18%"></td>
</tr>
<script type="text/javascript">
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: "value="+val,
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
File 'not_approved.php'
-----------------------
<form id="formt" name="formt" method="post" action="">
<table width="100%" border="0" align="left" cellpadding="1" cellspacing="0" bgcolor="#D8EEFE">
<tbody>
<tr>
<td colspan="3"><table width="100%" border="1" bordercolor="#33CCFF" cellspacing="0" cellpadding="1">
<tbody>
<tr class="style2">
<td align="left"><font color="#FF0000">*</font> Enter your comments here.
<table width="430" border="0">
<tr class="style2">
<td width="10" align="left" valign="top"></td>
<td width="410" colspan="2" align="left" valign="top"><textarea name="comment" id="comment" cols="45" rows="5"><?php echo $comment; ?></textarea></td>
</tr>
</table></td>
</tr>
</tbody>
</table></td>
</tr>
</tbody>
</table>
</form>
Try this
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: {value:val},
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
** The data filed is changed **
You are passing data in wrong way do as below
data: "{'value':"+val+"}",
and if the value is in string then
data: "{'value':'"+val+"'}",
or
data: JSON.stringify({value:val})
Your data variable must not be in string format because its a variable name. You should do it like this:
<script type="text/javascript">
function processForm()
{
var val = 0;
if(window.document.getElementById('approve').checked)
var val = 1;
$.ajax( {
type: 'POST',
url: 'not_approved.php',
data: {
value: val,
}
cache: false,
success: function(html){
$("#div_data").html(html);
}
} );
}
</script>
Here your script variable val value assigned to value variable and for assigning we use colon here ':' instead of = in AJAX. In server side the catching variable must also be of same name i.e value.

Categories

Resources