Getting data from another page using XMLHttpRequest - xmlhttprequest

Good morning everyone. I tried creating a site that could get information from another page and feed the response into a div tag, but it didnt work. I checked with a very similar one i learnt from. Here is the HTML code.
<html>
<head>
<script>
function checkit(){
var samxml; var username;
if (window.XMLHttpRequest){
samxml = new XMLHttpRequest();}
else {
samxml = new ActiveXObject("Microsoft.XMLHTTP");
}
samxml.onreadystatechange = function() {
if (samxml.readyState == 4 && samxml.status == 200){
document.getElementById("check").innerHTML = samxml.responseText;}
}
username = document.getElementById("username").value;
samxml.open("POST", "check.php",true);
samxml.send( "username" );
}
}
</script>
</head>
<body>
<form>
<label for ="username">User ID:</label>
<input type = "text" name = "username" id = "username"/>
<div id = "check"></div>
<button type = "button" onclick = "checkit()">Check</button>
</form>
</body>
</html>
Here is the PHP page:
//php file
<?php
$user = $_POST["username"];
if ($user == "samuel") {
echo "Hmm. Chosen! Choose another one";}
else {
echo "Nice one";}
?>
Thanks so much.

Related

File upload using dropzon.js

I'm trying to upload files using dropzone.js
View:
#using (Html.BeginForm("SaveMethod", "ControllerName", FormMethod.Post, new { enctype = "multipart/form-data", #class = "dropzone", id = "js-upload-form" }))
........................
<div class="form-inline">
<div class="form-group">
<input type="file" name="MainFile" id="js-upload-files"/>
</div>
<div class="upload-drop-zone" id="drop-zone">
Just drag and drop files here
</div>
<div class="dropzone-previews"></div>
</div>
JS:
var formData = null;
formData = new FormData($form[0]);
dropZone.ondrop = function (e) {
e.preventDefault();
this.className = 'upload-drop-zone';
startUpload(e.dataTransfer.files)
}
dropZone.ondragover = function () {
this.className = 'upload-drop-zone drop';
return false;
}
dropZone.ondragleave = function () {
this.className = 'upload-drop-zone';
return false;
}
var startUpload = function (files) {
for (var i = 0; i < files.length; i++) {
formData.append(files[i].name, files[i]);
}
}
Controller:
[HttpPost]
public JsonResult SaveMethod(TaskManage objTaskManage, HttpPostedFileBase files)
{
}
Now, after submit, i want to have files that was dropped on drop area along with the files attached in upload control. Here, what happens is files giving me null and when i use Request.Files["MainFile"] i get only the files dropped on dropzone area, it doesn't show me the file i have upload to control.
I'm not able to find out the issue. Any help is really appreciated.
File upload in ASP.NET MVC using Dropzone JS and HTML5
You can download the latest version from the official site here http://www.dropzonejs.com/ and also we can install using the nuget package manage console by the following command Package Manager Console
PM> Install-Package dropzone
Now create a bundle for your script file in BundleConfig.cs
bundles.Add(new ScriptBundle("~/bundles/dropzonescripts").Include(
"~/Scripts/dropzone/dropzone.js"));
Similarly add the dropzone stylesheet in the BundleConfig.cs
bundles.Add(new StyleBundle("~/Content/dropzonescss").Include(
"~/Scripts/dropzone/css/basic.css",
"~/Scripts/dropzone/css/dropzone.css"));
Now add the bundle reference in your _Layout page
View Page:
<div class="jumbotron">
<form action="~/Home/SaveUploadedFile" method="post" enctype="multipart/form-data" class="dropzone" id="dropzoneForm" style="width: 50px; background: none; border: none;">
<div class="fallback">
<input name="file" type="file" multiple />
<input type="submit" value="Upload" />
</div>
</form>
</div>
Controller:
public ActionResult SaveUploadedFile()
{
bool isSavedSuccessfully = true;
string fName = "";
try{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
//Save file content goes here
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\WallImages", Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), "imagepath");
var fileName1 = Path.GetFileName(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists)
System.IO.Directory.CreateDirectory(pathString);
var path = string.Format("{0}\\{1}", pathString, file.FileName);
file.SaveAs(path);
}
}
}
catch(Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
return Json(new { Message = fName });
}
else
{
return Json(new { Message = "Error in saving file" });
}
}
Now add the following script to your view page at the and in script tag.
//File Upload response from the server
Dropzone.options.dropzoneForm = {
init: function () {
this.on("complete", function (data) {
//var res = eval('(' + data.xhr.responseText + ')');
var res = JSON.parse(data.xhr.responseText);
});
}
};
Here you can see the response from server.

conn.authenticate is undefined during new registration using strophe.register.js

Hi everyone i am trying to register new account on my local openfire server using strophe.js and strophe.register.js plugin by following the steps for registration provide on many websites.But i get error in my strophe.register.js file at line var auth_old = conn.authenticate.bind(conn); that conn.authenticate is undefined
below is the my code
code of my js file
$(document).ready(function () {
var conn = new Strophe.Connection(
"http://jabber.local/http-bind");
console.log(conn);
var callback = function (status) {
if ( status === Strophe.Status.REGISTERING ) {
console.log('REGISTERING')
conn.authenticate();
}
else if ( status === Strophe.Status.REGIFAIL ) {
console.log('REGIFAIL')
}
else if ( status === Strophe.Status.REGISTER ) {
console.log('REGISTER')
conn.register.fields.username = "joe"
conn.register.fields.password = "doe"
conn.register.submit();
}
else if ( status === Strophe.Status.SUBMITTING ) {
console.log('SUBMITTING')
}
else if ( status === Strophe.Status.SBMTFAIL ) {
console.log('SBMTFAIL')
console.log('Something went wrong...');
}
else if ( status === Strophe.Status.REGISTERED ) {
console.log('REGISTERED')
console.log('Your account has been created successfully and is ready to use!');
}
}
conn.register.connect("example.com", callback);
});
and the html file code is
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js'></script>
<script src='../scripts/strophe.js'></script>
<script type="text/javascript" src="../scripts/strophe.register.js"></script>
<script src='../scripts/flXHR.js'></script>
<script src='../scripts/strophe.flxhr.js'></script>
<link rel='stylesheet' href='hello.css'>
<script src='hello.js'></script>
</head>
<body>
<h1>Hello</h1>
<div id='log'>
</div>
<!-- login dialog -->
<div id='login_dialog' class='hidden'>
<label>JID:</label><input type='text' id='jid'>
<label>Password:</label><input type='password' id='password'>
</div>
</body>
</html>
can enyone tell my why this happend and how to solve this.One more thing i also comment the lines that most site said to do.
/* if (register.length === 0) {
conn._changeConnectStatus(Strophe.Status.REGIFAIL, null);
return true;
}*/
this.enabled = true;
Just noticed that you are using the older version of the plugin. Please update the strophe.register.js from https://github.com/metajack/strophejs-plugins/blob/master/register/strophe.register.js
I have checked the latest version it does not have below line
var auth_old = conn.authenticate.bind(conn);

change operation of the controler

My default action code:
public ViewResult Act(int? id)
{
if (id == null)
ViewData["p"] = GetDefaultView();
else
ViewData["p"] = GetEditView((int)id);
return View("Index");
}
My Index view code:
<!DOCTYPE html><html><head></head><body>
<div id="content">#Html.Raw(ViewData["p"])</div></body></html>
How it is possible to use instead of ViewData a string ? How I can update #content only by means of $.ajax?
Before being able to use the $.ajax function you will first need to render a view which includes the jquery.js script:
<!DOCTYPE html>
#{ Layout = null; }
<html>
<head>
</head>
<body>
<div id="content"></div>
<!-- TODO: Adjust your proper jquery version here: -->
<script type="text/javascript" src="~/scripts/jquery.js"></script>
<script type="text/javascript">
$.ajax({
url: '#Url.Action("act")',
data: { id: 123 },
success: function(result) {
$('#content').html(result);
}
});
</script>
</body>
</html>
then you should adapt your Act controller action so that it returns some partial view or a Content result:
public ActionResult Act(int? id)
{
if (id == null)
{
return Content("<div>id was null</div>");
}
return Content("<div>id value is " + id.Value.ToString() + "</div>");
}
If you want to return a string, you could change your controller to return a ContentResult.
public ContentResult Act(int? id)
{
string html = "";
if (id == null)
html = GetDefaultView();
else
html = GetEditView((int)id);
var content = new ContentResult();
content.Content = html;
return content;
}

Google CSE - multiple search forms on the same page

i'm aiming to put 2 search forms on the same wordpress page. i'm using the iframe form code and have already sorted out how to direct that to a search element.
but the form includes the following script:
www.google.com/cse/brand?form=cse-search-box&lang=en
which starts by defining the search box by ID
var f = document.getElementById('cse-search-box');
but if you use multiple forms then you (incorrectly i know) end up with elements that have the same ID.. and the branding+ focus/blur events don't work across both forms.
the form basically looks like:
<form action="/search.php" class="cse-search-box">
<div>
<input type="hidden" name="cx" value="" />
<input type="hidden" name="cof" value="FORID:10" />
<input type="hidden" name="ie" value="UTF-8" />
<input type="text" name="q" size="32" />
<input type="submit" name="sa" value="Search" />
</div>
</form>
<script type="text/javascript" src="//www.google.com/cse/brand?form=cse-search-box&lang=en"></script>
if this were a jquery script i think it'd be easy to change the ID to a class name and do an .each() iteration. but google's code is pure javascript and i'm not familiar with that, though
i read getElementbyClass isn't super reliable.
so is this fixable or not worth worrying over?
eventually i commented out that script from google.com and replaced it w/ my own custom version:
`
if (window.history.navigationMode) {
window.history.navigationMode = 'compatible';
}
jQuery.noConflict();
jQuery(document).ready(function($) { //tells WP to recognize the $ variable
//from google's original code- gets the URL of the current page
var v = document.location.toString();
var existingSiteurl = /(?:[?&]siteurl=)([^&#]*)/.exec(v);
if (existingSiteurl) {
v = decodeURI(existingSiteurl[1]);
}
var delimIndex = v.indexOf('://');
if (delimIndex >= 0) {
v = v.substring(delimIndex + '://'.length, v.length);
}
$(".cse-search-box").each( function() {
var q = $(this).find("input[name=q]");
var bg = "#fff url(http:\x2F\x2Fwww.google.com\x2Fcse\x2Fintl\x2Fen\x2Fimages\x2Fgoogle_custom_search_watermark.gif) left no-repeat";
var b = "#fff";
if (q.val()==""){
q.css("background",bg);
} else {
q.css("background",b);
}
q.focus(function() {
$(this).css("background", b);
});
q.blur(function() {
if($(this).val()==""){
$(this).css("background", bg);
}
});
//adds hidden input with site url
hidden = '<input name="siteurl" type="hidden" value="'+ v +'">'
$(this).append(hidden);
});
}); //end document ready functions
`
and on the search.php page that you are directing the results to (so this is a 2-page search form, i found a tutorial on that online somewhere) you will need:
`
google.load('search', '1', {language : 'en', style : google.loader.themes.MINIMALIST});
/**
* Extracts the users query from the URL.
*/
function getQuery() {
var url = '' + window.location;
var queryStart = url.indexOf('?') + 1;
if (queryStart > 0) {
var parts = url.substr(queryStart).split('&');
for (var i = 0; i < parts.length; i++) {
if (parts[i].length > 2 && parts[i].substr(0, 2) == 'q=') {
return decodeURIComponent(
parts[i].split('=')[1].replace(/\+/g, ' '));
}
}
}
return '';
}
function onLoad() {
// Create a custom search control that uses a CSE restricted to
// code.google.com
var customSearchControl = new google.search.CustomSearchControl)('google_search_id');
var drawOptions = new google.search.DrawOptions();
drawOptions.setAutoComplete(true);
// Draw the control in content div
customSearchControl.draw('results', drawOptions);
// Run a query
customSearchControl.execute(getQuery());
}
google.setOnLoadCallback(onLoad);
`

Getting storageVolume to work in JavaScript

In his blog post, Christian Cantrell shows how to use STORAGE_VOLUME_MOUNT in ActionScript.
He has written a Flex app called FileTile.
I would like to see a JavaScript alert box that says “You have inserted “ + e.storageVolume.name, and “You have removed a storage volume”.
<html>
<head>
<title>New Adobe AIR Project</title>
<script type="text/javascript" src="lib/air/AIRAliases.js"></script>
<script type="text/javascript" src="lib/air/AIRIntrospector.js"></script>
<script type="text/javascript" src="lib/jQuery/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
var msg = '<h1>Please insert your SwatchDog (SD) card.</h1>';
function trace() {
var message = 'Hello Max';
air.Introspector.Console.log(message);
}
function readFile(v) {
var myFile = air.File.desktopDirectory.resolvePath("MyFile.txt");
var fileStream = new air.FileStream();
fileStream.open(myFile, air.FileMode.READ);
$('#app').append('<p>' + fileStream.readUTFBytes(fileStream.bytesAvailable) + '</p>');
fileStream.close();
}
function onVolumeMount(e) {
$('#app').html('<h1>Thank you</h1><p>I can see you have multiple devices:</p>');
var volumes = air.StorageVolumeInfo.storageVolumeInfo.getStorageVolumes();
for (var i = 0; i < volumes.length; i++) {
$('#app').append(volumes[i].rootDirectory.nativePath);
}
if (e.storageVolume.isRemovable) {
if (e.storageVolume.name == 'SWATCHDOG') {
$('#app').append('<p>And SwatchDog is drive: ' + e.storageVolume.rootDirectory.nativePath + '</p>');
readFile(e.storageVolume)
} else {
$('#app').append('<p>But the one you just plugged in is not SwatchDog.</p>');
}
}
}
function onVolumeUnmount(e) {
$('#app').html('<h1>Goodbye!</h1>' + msg);
}
jQuery(function($){
var PluggedIn = false;
var volumes = air.StorageVolumeInfo.storageVolumeInfo.getStorageVolumes();
for (var i = 0; i < volumes.length; i++) {
if (volumes[i].isRemovable) {
PluggedIn = true;
if (volumes[i].name == 'SWATCHDOG') {
$('#app').append('I see you already have SwatchDog plugged in!');
readFile(volumes[i])
} else {
$('#app').append('What you have plugged in is not SwatchDog.');
}
}
}
if (!PluggedIn){
$('#app').append(msg);
}
air.StorageVolumeInfo.storageVolumeInfo.addEventListener(air.StorageVolumeChangeEvent.STORAGE_VOLUME_MOUNT, onVolumeMount);
air.StorageVolumeInfo.storageVolumeInfo.addEventListener(air.StorageVolumeChangeEvent.STORAGE_VOLUME_UNMOUNT, onVolumeUnmount);
})
</script>
</head>
<body>
<div id="app">
</div>
<button onclick="trace();">Say Hello Max!</button>
</body>
</html>