Static html page created the WebSocket connection golang server directly - sockets

I'm writing an html page that needs to create a websocket to the server
On the server, I used the example in "code.google.com/p/go.net/websocket" just accept the connection.
However, in Chrome26 the response is
WebSocket connection to 'ws://127.0.0.1:1234/' failed: Unexpected response code: 400
Is there something is missed (like a handshake)?
This is my html and server is using go
<html>
<head></head>
<body>
<script type="text/javascript">
var sock = null;
var wsuri = "ws://127.0.0.1:1234";
window.onload = function() {
console.log("onload");
sock = new WebSocket(wsuri);
sock.onopen = function() {
console.log("connected to " + wsuri);
}
sock.onclose = function(e) {
console.log("connection closed (" + e.code + ")");
}
sock.onmessage = function(e) {
console.log("message received: " + e.data);
}
};
function send() {
var msg = document.getElementById('message').value;
sock.send(msg);
};
</script>
<h1>WebSocket Echo Test</h1>
<form>
<p>
Message: <input id="message" type="text" value="Hello, world!">
</p>
</form>
<button onclick="send();">Send Message</button>
</body>
</html>
//------------------------------
package main
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
)
func Echo(ws *websocket.Conn) {
var err error
for {
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil {
fmt.Println("Can't receive")
break
}
fmt.Println("Received back from client: " + reply)
msg := "Received: " + reply
fmt.Println("Sending to client: " + msg)
if err = websocket.Message.Send(ws, msg); err != nil {
fmt.Println("Can't send")
break
}
}
}
func main() {
http.Handle("/", websocket.Handler(Echo))
if err := http.ListenAndServe(":1234", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}

Chrome is likely throwing error 400 because it thinks you are trying to do a cross-domain request to the websocket server and thinks it is unlikely you have permission.
To solve the issue you simply have to server your html from your go-server too.
So change your sock.go code to:
package main
import (
"code.google.com/p/go.net/websocket"
"fmt"
"log"
"net/http"
)
func Echo(ws *websocket.Conn) {
var err error
for {
var reply string
if err = websocket.Message.Receive(ws, &reply); err != nil {
fmt.Println("Can't receive")
break
}
fmt.Println("Received back from client: " + reply)
msg := "Received: " + reply
fmt.Println("Sending to client: " + msg)
if err = websocket.Message.Send(ws, msg); err != nil {
fmt.Println("Can't send")
break
}
}
}
func main() {
http.Handle("/", http.FileServer(http.Dir("."))) // <-- note this line
http.Handle("/socket", websocket.Handler(Echo))
log.Println("serving")
if err := http.ListenAndServe(":1234", nil); err != nil {
log.Fatal("ListenAndServe:", err)
}
}
and add your index.html file to the same directory as your sock.go file:
<html>
<head></head>
<body>
<script type="text/javascript">
var sock = null;
var wsuri = "ws://127.0.0.1:1234/socket"; // <-- note new path
window.onload = function() {
console.log("onload");
sock = new WebSocket(wsuri);
sock.onopen = function() {
console.log("connected to " + wsuri);
}
sock.onclose = function(e) {
console.log("connection closed (" + e.code + ")");
}
sock.onmessage = function(e) {
console.log("message received: " + e.data);
}
};
function send() {
var msg = document.getElementById('message').value;
sock.send(msg);
};
</script>
<h1>WebSocket Echo Test</h1>
<form>
<p>
Message: <input id="message" type="text" value="Hello, world!">
</p>
</form>
<button onclick="send();">Send Message</button>
</body>
</html>
Now you will be able to connect from within chrome.

Related

Trying to post data via html-form and JavaScript to RESTapi – gets 404 Cannot Post?

I have googled a lot, gone through a lot of questions but can't find an answer.
I have built a simple RESTapi with node and mongoDB, using express and mongoose. The database is hosted on Atlas. The RESTapi works fine when accessing with postman, no problem there.
To access and use the RESTapi via the site I get the GET and DELETE method to work, but when trying to post data with a form I get the error “Cannot Post/ 404”. I have tried a lot of things but can´t get it to work. (I don't know it it is related, but the content-security policies which makes some scripts don't load, I have tried to allow everything in the head meta-info in index.html, but it doesn't make a change)
Request headers
Accept
text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding
gzip, deflate
Accept-Language
en-US,en;q=0.5
Cache-Control
no-cache
Connection
keep-alive
Content-Length
530
Content-Type
multipart/form-data; boundary=---------------------------52045656921129358052645853016
Host
localhost:3000
Origin
http://localhost:3000
Pragma
no-cache
Referer
http://localhost:3000/
Upgrade-Insecure-Requests
1
The RESTapi and the site accessing is in the same folder, here is the project structure:
Here is the code:
js/main.js
window.onload = loadCourses();
// Variebles from the form
let formCreate = document.getElementById("formCreate");
let courseIdIn = document.getElementById("courseId");
let courseNameIn = document.getElementById("courseName");
let coursePeriodIn = document.getElementById("coursePeriod");
let message_form = document.getElementById("message_form");
const myForm = document.getElementById('formCreate');
myForm.addEventListener('submit', (e) => {
console.log('Hello from eventlistner');
e.preventDefault();
addCourse();
})
// GET courses
function loadCourses() {
$.getJSON("http://localhost:3000/courses", function(data) {
//rensa listan
console.log(data);
$("#tbody").html("");
for(let i = 0; i<data.length; i++) {
$("tbody").append("<tr><td>" + data[i]._id + "</td>" + "<td>"+ data[i].courseId + "</td>" + "<td>" + data[i].courseName +
"</td>" + "<td>" + data[i].coursePeriod + "</td>" + "<td><img class='deleteSize' onclick='deleteCourse(\""+data[i]._id+"\")' src='images/delete-photo.svg'alt='ikon radare'></td></tr>");
}
});
}
// DELETE course
function deleteCourse(id) {
console.log(id)
$.ajax({
type: "DELETE",
url: "http://localhost:3000/courses/" + id
}).done(function(response) {
console.log(response);
//ladda om listan
loadCourses();
});
}
// add course
function addCourse() {
console.log("Hi from add Course");
let courseIdEl = courseIdIn .value;
let courseNameEl = courseNameIn.value;
let coursePeriodEl = coursePeriodIn.value;
let courseObj =
{
"courseId": courseIdEl.value,
"courseName": courseNameEl.value,
"coursePeriod": coursePeriodEl.value
}
console.log(courseObj);
//Skapar fetch-anrop
fetch('http://localhost:3000/courses', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Accept': '*/*',
},
body: JSON.stringify(courseObj)
})
.then(response => response.json())
.then(data => {
// message
let message = data.message;
message_form.innerHTML = message;
//document.getElementById("message_form").innerHTML = message;
loadCourses();
formCreate.reset();
})
.catch(error => {
console.log('Error: ', error);
})
}
the index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="Content-Security-policy" content="default-src *;
script-src *;
connect-src *;">
<link rel="stylesheet" href="css/style.css">
<script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
<script src="js/main.js"></script>
<script src="main2.js"></script>
<title>Moment 3 - mongoose.js</title>
</head>
<body>
<h1>Moment 3 - mongoose.js</h1>
<table>
<thead>
<tr>
<th>ID</th>
<th>Kurs</th>
<th>Kursnamn</th>
<th>Period</th>
<th>Radera</th>
</tr>
</thead>
<tbody id="tbody">
<tr>
<td>1</td>
<td>DT162G</td>
<td>JavaScript-basar webbutveckling</td>
<td>1</td>
<td><img class="deleteSize" onclick="deleteCourse()" src="images/delete-photo.svg" alt="ikon radare">
</td>
</tr>
</tbody>
</table>
<h3>Create course:</h3>
<form class="forms" action="" id="formCreate" method="POST" enctype="multipart/form-data">
<!--fält för formulär, hela den grå delen-->
<fieldset id="field">
<p class="pfield" id="message_form"></p>
<label for="courseId">Kurskod:</label><br>
<input type="text" name="courseId" id="courseId" class="input">
<br>
<label for="courseName">Kursnamn:</label><br>
<input type="text" name="courseName" id="courseName" class="input">
<br>
<label for="coursePeriod">Kursperiod:</label><br>
<input type="number" id="coursePeriod" name="coursePeriod" min="1" max="2">
<div class="btn-wrapper">
<button type="submit" name="submitPost" id="btn-create" class="btn btn2">Publish</button>
<button type="reset" name="deletePost" id="btn-reset" class="btn btn2 btn-reset">Delete
field</button>
</div>
</fieldset>
</form>
</body>
</html>
RESTapi code
routes/courses.js
const express = require('express');
const router = express.Router();
// Hämtar schemamodel
const Courses = require('../models/CourseModel');
// Get all courses
router.get('/', async (req, res) => {
try {
const allCourses = await Courses.find();
if(!allCourses) {
throw Error('No items found');
} else {
res.status(200).json(allCourses);
}
} catch(err) {
res.status(500).json( {msg: err})
}
})
// GET one course
router.get('/:id', getCourse, (req, res) => {
res.json(res.course)
})
// Create course
router.post('/', async (req, res) => {
const newCourse = new Courses({
courseName: req.body.courseName,
courseId: req.body.courseId,
coursePeriod: req.body.coursePeriod
});
try {
const course = await newCourse.save();
if(!course) {
throw Error('Something went wrong while saving the post =( ');
} else {
// It worked ok, post is created
res.status(201).json(course);
}
} catch (err) {
// bad input from user = 400
res.status(400).json( {msg: err})
}
});
// UPDATE one course
router.patch('/:id', getCourse, async (req, res) => {
// options new = true makes mangoose send back updated data and not old
let options = { new: true };
try {
const course = await Courses.findByIdAndUpdate(req.params.id, req.body, options);
if(!course) {
throw Error ('Something went wrong while updating the post =( ');
} else {
// It worked ok, post is created
res.json(course).status(201).json( {success: true});
}
} catch {
res.status(400).json( {message: err.message})
}
})
// DELETE one course
router.delete('/:id', getCourse, async (req, res) => {
try {
await res.course.deleteOne();
res.status(200).json( {message: 'Success: Course is deleted!'})
} catch (err){
res.status(503).json( {message: err.message})
}
})
// Creating middlewhere function to re-use, findbyid. Middlewhere idé = webdev simplified
async function getCourse(req, res, next) {
let course;
try {
course = await Courses.findById(req.params.id)
if (course == null) {
return res.status(404).json( {message: 'Cant find any course with that ID'})
}
} catch (err) {
return res.status(500).json( {message: err.message})
}
res.course = course;
next();
}
module.exports = router;
models/CourseModel.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CourseSchema = new Schema( {
courseName: {
type: String,
required: true
},
courseId: {
type: String,
required: true
},
coursePeriod: {
type: Number,
required: true
}
});
module.exports = mongoose.model('Courses', CourseSchema );
server.js
require('dotenv').config();
const express = require('express');
const app = express();
const path = require("path");
const mongoose = require('mongoose');
//const { MONGO_URI } = require('./config');
// Connect to MongoDB
mongoose.connect(process.env.MONGO_URI,{ useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false })
.then(() => console.log('Connected to Mongo Database.'))
.catch(err => console.log(err));
//BodyParser Middleware, for use of JSON in body
app.use(express.json());
// skapa statisk sökväg
app.use(express.static(path.join(__dirname, 'public')));
// Routes
const courseRoutes = require('./routes/courses.js')
app.use('/courses', courseRoutes)
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => console.log (`Server run at port ${PORT}`));
well, it was a stupid mistake in HTML, the script source tag for the javascript-file main.js was in the head section. Of course, it must be in the bottom just before the body-tag. So stupid of me.

Handling rest post response in Angular 6 as a Client and Spring boot as a server API

I have an issue in my project. I've searched every related posts but couldn't find where is the problem. I would be grateful if anyone can help me.
I'm trying to receive the response in my client side and handle it but when I get response it shows the Server Side URL with the raw text in the browser.
Here is my Angular (app.component.ts) code:
import {Component, OnInit} from '#angular/core';
import {HttpClient, HttpHeaders} from '#angular/common/http';
import { GetSipIdService } from './app.service';
const URL = 'http://localhost:8990/getId';
#Component({
selector: 'app-root',
providers: [ GetSipIdService ],
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(private getSipIdService: GetSipIdService,
private http: HttpClient
) { }
onSubmit(id: string, file: File) {
const frmData = new FormData();
frmData.append('id', id);
frmData.append('inputPackage', file);
this.http.post(URL, frmData ).subscribe( res => alert(res.toString()
));
}
}
and this is the HTML file :
<section class="login-block">
<div class="container">
<div class="row">
<div class="col-md-4 login-sec">
<form >
<!--<form action="http://localhost:8990/getId" method="POST" enctype="multipart/form-data">-->
<label for="id">Id:</label>
<input #id type="text" name="id" id="id" (change)="insertId($event)" /><br/><br/>
<div class="form-group files color">
<label>Upload Your File </label>
<input #inputPackage type="file" name="inputPackage" (change)="insertFile($event)" required class="file-controller" multiple="">
</div>
<div class="align-center">
<input type="submit" class="btn btn-lg btn-info " value="Send the request" (click)="onSubmit(id.value, inputPackage)"/>
</div>
</form>
</div>
<div class="col-md-8 banner-sec">
<div id="carouselExampleIndicators" class="carousel slide" data-ride="carousel">
<div class="carousel-inner" role="listbox">
<div class="carousel-item">
<img class="d-block img-fluid" src="../images/test.jpg" alt="Test photo">
</div>
</div>
</div>
</div>
</div>
</div>
</section>
On server Side I have this section :
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.IOException;
#Controller
public class GetSipIdController {
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#RequestMapping(method = RequestMethod.POST, value = "/getId", headers = {"content-type=multipart/mixed","content-type=multipart/form-data"})
#ResponseBody
String Response(#RequestParam("inputPackage") MultipartFile[] inputPackages, #RequestParam("id") String id) {
String response = null;
try {
if (inputPackages != null && id != null && inputPackages.length > 0 && id.length() > 1) {
if (inputPackages[0].getOriginalFilename() != null ) {
if( inputPackages[0].getOriginalFilename().contains(".zip")) {
System.out.println("Input Package Name : " + inputPackages[0].getOriginalFilename());
System.out.println("Input Package Size : " + inputPackages[0].getSize());
// save file
userId = GetUserId.runProcess(recvPackage, id);
response = userId ;
}else{
System.out.println("==============>>>>>>>> The input file : "+ (inputPackages[0].getOriginalFilename())+" is invalid!!\n It should be a zip file!");
response = "The input file : "+ (inputPackages[0].getOriginalFilename())+" is invalid!!\n It should be a zip file!";
}
}
}else{
System.out.println("==============>>>>>>>> The ID and valid zip file should be provide!");
response = "The ID and valid zip file should be provide!";
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
}
And this is the image from response, it redirect to server url with raw response:
enter image description here
Please make below changes in controller method to work.You are sending response multipart/mixed type..
#CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
#PostMapping(value = "/getId")
public String Response(#RequestParam("inputPackage") MultipartFile[] inputPackages, #RequestParam("id") String id) {
String response = null;
try {
if (inputPackages != null && id != null && inputPackages.length > 0 && id.length() > 1) {
if (inputPackages[0].getOriginalFilename() != null ) {
if( inputPackages[0].getOriginalFilename().contains(".zip")) {
System.out.println("Input Package Name : " + inputPackages[0].getOriginalFilename());
System.out.println("Input Package Size : " + inputPackages[0].getSize());
// save file
userId = GetUserId.runProcess(recvPackage, id);
response = userId ;
}else{
System.out.println("==============>>>>>>>> The input file : "+ (inputPackages[0].getOriginalFilename())+" is invalid!!\n It should be a zip file!");
response = "The input file : "+ (inputPackages[0].getOriginalFilename())+" is invalid!!\n It should be a zip file!";
}
}
}else{
System.out.println("==============>>>>>>>> The ID and valid zip file should be provide!");
response = "The ID and valid zip file should be provide!";
}
} catch (IOException e) {
e.printStackTrace();
}
return response;
}
I finally got the point.
First remove the <form> from HTML, then changed my Angular into this :
import {Component, OnInit} from '#angular/core';
import {HttpClient, HttpHeaders} from '#angular/common/http';
const URL = 'http://localhost:8990/getUserId';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
constructor(
private http: HttpClient
) { }
fileToUpload: File = null;
id: String = '0';
inputId(event) {
this.id= event.target.value;
console.log('id is -- > ' + event.target.value );
}
inputFile(event) {
this.fileToUpload = event.target.files[0];
console.log('File path -- > ' + event.target.files[0].name );
}
onSubmit(id: string, file: File) {
event.preventDefault();
const frmData = new FormData();
console.log('POST');
// #ts-ignore
frmData.append('id', this.id);
frmData.append('inputPackage', this.fileToUpload);
console.log('id --> ' + this.id);
console.log('File name --> ' + this.fileToUpload.name);
this.http.post(URL, frmData ).subscribe( res => console.log('--==>> ' + JSON.stringify(res )));
}
}
and change my Spring response to JSON format which make easier to receive from Angular.
used this as a convert class.

Query multiple SharePoint lists Using REST API and angular JS

I have a scenario of fetching data from multiple SharePoint 2013 lists using REST API and Angularjs. I am able to fetch the data successfully from one of the SharePoint list but my requirements is to fetch the data from multiple lists on the page load. I am using a provider hosted app to fetch the data from host web. I have 2 methods for calling 2 separate lists. I am getting the results from first method successfully but when the second method is called after the execution of 1st method. I am getting a time out error. It seems like i cannot call the 2 methods one after the other. Below is my code, could anyone please help me if i am missing something or if there is any other way to fetch the data from multiple SharePoint lists.
Method 1: fetch Data from List 1
var query = listEndPoint + "/getbytitle('CandidateList')/items?$select=ID,FirstName,MiddleInitial,LastName,EmailAddress,PrimaryPhoneNo,ProfileImage,Address,State,Country,CurrentTitle,CurrentCompany,LastActivityModifiedBy,LastActivityModifiedDate,DeletedStatus&#target='" + hostweburl + "'";
var getCandidates = function (query, queryCandidateNotes)
{
alert('getRequest');
var scriptbase = hostweburl + "/_layouts/15/";
var deferred = $q.defer();
// Load 15hives js files and continue to the successHandler
$.getScript(scriptbase + "SP.Runtime.js",
function () {`enter code here`
$.getScript(scriptbase + "SP.js",
function () {
$.getScript(scriptbase +"SP.RequestExecutor.js",
function () {
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: query,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
});
//deferred.resolve();
});
});
});
function successHandler(data) {
var jsonObject1 = JSON.parse(data.body);
deferred.resolve(jsonObject1);
}
function errorHandler(data, errorCode, errorMessage) {
alert('Error1:' + errorMessage + data.body);
}
// Get
return deferred.promise;
//Candidate Details Ends
};
Method 2: fetch Data from List 2
var queryCandidateNotes = listEndPoint + "/getbytitle('CandidateNotes')/items?$select=Title,CandidateId&#target='" + hostweburl + "'";
// Get All Candidate Notes
var getCandidateNotes = function (queryCandidateNotes) {
alert('getCandidateNotesRequest');
var scriptbase = hostweburl + "/_layouts/15/";
var deferred2 = $q.defer();
// Load 15hives js files and continue to the successHandler
$.getScript(scriptbase + "SP.Runtime.js",
function () {
$.getScript(scriptbase + "SP.js",
function () {
$.getScript(scriptbase + "SP.RequestExecutor.js",
function () {
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: queryCandidateNotes,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: successHandler,
error: errorHandler
});
//deferred.resolve();
});
});
});
function successHandler(data) {
var jsonObject2 = JSON.parse(data.body);
//var results2 = jsonObject2.d.results;
deferred2.resolve(jsonObject2);
//alert('2nd success:' + jsonObject2);
//return jsonObject2;
}
function errorHandler(data, errorCode, errorMessage) {
alert('Error2 :' + errorMessage + data.body);
}
// Get
return deferred2.promise;
};
Method 3: Calling method 2 after method 1
var getRequest = function (query, queryCandidateNotes) {
var deferred = $q.defer();
$.when(getCandidates(query, queryCandidateNotes)).then(function (data) {
alert('Success1:' + data);
$.when(getCandidateNotes(queryCandidateNotes)).then(function (data1) {
deferred.resolve(data);
alert('Success2:' + data1);
});
})
return deferred.promise;
};
return {
getRequest: getRequest
};
}]);
})();
$.when is not appropriate here, utilize $q.all that combines multiple promises into a single promise that is resolved when all of the input promises are resolved.
Example
app.controller('listController', function ($scope, $q, listService) {
SP.SOD.executeFunc('SP.RequestExecutor.js', 'SP.RequestExecutor', function () {
$q.all([listService.getListItems('Documents'), listService.getListItems('Site Pages')]).then(function (data) {
$scope.documentsItems = data[0].d.results;
$scope.sitePagesItems = data[1].d.results;
});
});
});
where listService is a service for getting list items:
app.factory('listService', ['$q', function ($q) {
var getListItems = function (listTitle) {
var d = $q.defer();
JSRequest.EnsureSetup();
var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
var appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]);
var queryUrl = appweburl + "/_api/SP.AppContextSite(#target)/web/lists/getByTitle('" + listTitle + "')/items?#target='" + hostweburl + "'";
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function(data, textStatus, xhr) {
d.resolve(JSON.parse(data.body));
},
error: function(xhr, textStatus, errorThrown) {
d.reject(JSON.parse(xhr.body).error);
}
});
return d.promise;
};
return {
getListItems: getListItems
};
}]);
Solution description
Default.aspx
<asp:Content ContentPlaceHolderID="PlaceHolderAdditionalPageHead" runat="server">
<script type="text/javascript" src="../Scripts/jquery-1.9.1.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
<SharePoint:ScriptLink Name="sp.js" runat="server" OnDemand="true" LoadAfterUI="true" Localizable="false" />
<meta name="WebPartPageExpansion" content="full" />
<!-- Add your CSS styles to the following file -->
<link rel="Stylesheet" type="text/css" href="../Content/App.css" />
<!-- Add your JavaScript to the following file -->
<script type="text/javascript" src="../Scripts/listService.js"></script>
<script type="text/javascript" src="../Scripts/App.js"></script>
</asp:Content>
and
<asp:Content ContentPlaceHolderID="PlaceHolderMain" runat="server">
<div ng-app="SPApp" ng-controller="listController">
</div>
</asp:Content>
App.js
'use strict';
(function() {
var app = angular.module('SPApp', ['SPApp.services']);
app.controller('listController', function ($scope, $q, listService) {
executeOnSPLoaded(function () {
$q.all([listService.getListItems('Documents'), listService.getListItems('Site Pages')]).then(function (data) {
$scope.documentsItems = data[0].d.results;
$scope.sitePagesItems = data[1].d.results;
});
});
});
})();
function executeOnSPLoaded(loaded) {
JSRequest.EnsureSetup();
var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
var scriptbase = hostweburl + "/_layouts/15/";
$.when(
//$.getScript(scriptbase + "SP.Runtime.js"),
$.getScript(scriptbase + "SP.js"),
$.getScript(scriptbase + "SP.RequestExecutor.js"),
$.Deferred(function (deferred) {
$(deferred.resolve);
})
).done(function () {
loaded();
});
}
listService.js
'use strict';
angular.module('SPApp.services',[])
.factory('listService', ['$q', function ($q) {
var getListItems = function (listTitle) {
var d = $q.defer();
JSRequest.EnsureSetup();
var hostweburl = decodeURIComponent(JSRequest.QueryString["SPHostUrl"]);
var appweburl = decodeURIComponent(JSRequest.QueryString["SPAppWebUrl"]);
var queryUrl = appweburl + "/_api/SP.AppContextSite(#target)/web/lists/getByTitle('" + listTitle + "')/items?#target='" + hostweburl + "'";
var executor = new SP.RequestExecutor(appweburl);
executor.executeAsync({
url: queryUrl,
method: "GET",
headers: { "Accept": "application/json; odata=verbose" },
success: function(data, textStatus, xhr) {
d.resolve(JSON.parse(data.body));
},
error: function(xhr, textStatus, errorThrown) {
d.reject(JSON.parse(xhr.body).error);
}
});
return d.promise;
};
return {
getListItems: getListItems
};
}]);

how to use strophe with XMPP or Pujab

I have successfully installed following items as i want to Integrate Facebook Chat Into my web page
Python
Punjab
Twisted
on my windows XP , but now i want to use strophe library , to connect with Punjab.
Does anyone know how do i use strophe library , as i tried one example listed below supplied in
strophe library. The problem is i don't know what to specify in JID and Password field which is being asked by basic.html page.
Note:
as punjab is successfully installed on my windows xp and i am getting XEP-0124 - BOSH response too
Environment is localhost
basic.js
var BOSH_SERVICE = 'http://bosh.metajack.im:5280/xmpp-httpbind'
var connection = null;
function log(msg)
{
$('#log').append('<div></div>').append(document.createTextNode(msg));
}
function rawInput(data)
{
log('RECV: ' + data);
}
function rawOutput(data)
{
log('SENT: ' + data);
}
function onConnect(status)
{
if (status == Strophe.Status.CONNECTING) {
log('Strophe is connecting.');
} else if (status == Strophe.Status.CONNFAIL) {
log('Strophe failed to connect.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.DISCONNECTING) {
log('Strophe is disconnecting.');
} else if (status == Strophe.Status.DISCONNECTED) {
log('Strophe is disconnected.');
$('#connect').get(0).value = 'connect';
} else if (status == Strophe.Status.CONNECTED) {
log('Strophe is connected.');
connection.disconnect();
}
}
$(document).ready(function () {
connection = new Strophe.Connection(BOSH_SERVICE);
connection.rawInput = rawInput;
connection.rawOutput = rawOutput;
$('#connect').bind('click', function () {
var button = $('#connect').get(0);
if (button.value == 'connect') {
button.value = 'disconnect';
connection.connect($('#jid').get(0).value,
$('#pass').get(0).value,
onConnect);
} else {
button.value = 'connect';
connection.disconnect();
}
});
});
basic.html
<!DOCTYPE html>
<html>
<head>
<title>Strophe.js Basic Example</title>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js'></script>
<script src='../strophe.js'></script>
<script src='basic.js'></script>
</head>
<body>
<div id='login' style='text-align: center'>
<form name='cred'>
<label for='jid'>JID:</label>
<input type='text' id='jid'>
<label for='pass'>Password:</label>
<input type='password' id='pass'>
<input type='button' id='connect' value='connect'>
</form>
</div>
<hr>
<div id='log'></div>
</body>
</html>
I have create an account over here and get JID and Password for free
and for localhost , use JID as 'localhost' only and you can leave password blank.

How to read the values returned by the Json?

I have the following code in my view:
<% using (Ajax.BeginForm("JsonCreate", new AjaxOptions { OnComplete = "createCategoryComplete" }))
{ %><div id="createCategory">
<fieldset>
<legend>Add new category</legend>
<p>
<%=Html.TextBox("CategoryId")%>
<%=Html.TextBox("Test")%>
<label for="name">Name:</label>
<%= Html.TextBox("Name")%>
<%= Html.ValidationMessage("Name")%>
</p>
<p>
<input type="submit" value="Create" />
</p>
</fieldset>
</div>
In the controller the code is as follows:
[AcceptVerbs(HttpVerbs.Post)]
public JsonResult JsonCreate(string Name)
{
if (ModelState.IsValid)
{
try
{
//Return a json object to the javascript
return Json(new { CategoryId = 123, Test= "test successful" });
}
catch
{
#region Log errors about the exception
//Log error to administrator here
#endregion
}
}
//If we got this far, something failed, return an empty json object
return Json(new { /* Empty object */ });
}
What should be the code in the view for the following function to read the values returned by the Json and update the textboxes for CategoryId and Test?
function createCategoryComplete() {....???}
function createCategoryComplete(e) {
var obj = e.get_object();
alert(obj.CategoryId + ' ' + obj.Test);
}
Try this,
success: function(data) {
alert(data.CategoryId + " " + data.Test);
EDIT:
function createCategoryComplete(data)
{
document.getElementById("UrTxtBoxID").value = data.Test;
}