I have tried to find a solution to this problem, I'm currently at a loss. I'm trying to gather info on streams using the twitch API.
I am able to get a .getJSON request to work when I pass in an array of usernames, null is returned if the user is offline or invalid.
$(document).ready(function() {
var streamers = ["ESL_SC2","OgamingSC2","cretetion","freecodecamp","storbeck","habathcx","RobotCaleb","noobs2ninjas","meteos","c9sneaky","JoshOG"];
var url = "https://api.twitch.tv/kraken/streams/";
var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";
getInitialStreams(streamers, url, cb); //load hard-coded streams
});
function getInitialStreams(streamers, url, cb) {
//loop through the streamers array to add the initial streams
for (var i = 0; i < streamers.length; i++) {
(function(i) {
$.getJSON(url + streamers[i] + cb, function(data) {
//If data is returned, the streamer is online
if (data.stream != null) {
console.log("online");
} else {
console.log("offline");
}
});
})(i);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
<input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
<button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>
However, when I try to call the API through a click function (eventually pulling any input through the form) .getJSON fails. As seen below.
$(document).ready(function() {
var url = "https://api.twitch.tv/kraken/streams/";
var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";
$("#addStreamerBtn").click(function(e) {
addStreamer("Ben", url, cb);
});
});
function addStreamer(streamer, url, cb) {
console.log("I'm inside the function");
$.getJSON(url + streamer + cb, function(data) {
console.log("WE DID IT");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
<input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
<button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>
I don't understand why the code won't work for the 2nd snippet. Any guidance would be greatly appreciated.
The issue is because you've hooked to the click event of the submit button. This means that the form is being submit as your AJAX request happens, so the page is immediately unloaded and the AJAX cancelled.
To fix this, hook to the submit event of the form, and call preventDefault() on the event. Try this:
$(document).ready(function() {
var url = "https://api.twitch.tv/kraken/streams/";
var cb = "?client_id=5j0r5b7qb7kro03fvka3o8kbq262wwm&callback=?";
$(".form-inline").submit(function(e) {
e.preventDefault();
addStreamer("Ben", url, cb);
});
});
function addStreamer(streamer, url, cb) {
console.log("I'm inside the function");
$.getJSON(url + streamer + cb, function(data) {
console.log("WE DID IT");
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-inline">
<input id="addStreamerForm" class="form-control" type="text" placeholder="Add a Streamer">
<button id="addStreamerBtn" class="btn" type="submit">Add</button>
</form>
Related
<script>
window.onload = function() {
document.getElementById("Save").onclick = function fun() {
var x = document.forms["myForm"]["machine_id": "TNTEST004"].value;
var y = document.forms["myForm"]["wifi_mac_address": "80:56:f2:18:12:11"].value;
var Url = "http://192.168.1.9:8080/machine_reg/";
var xhr = new XMLHttpRequest();
xhr.open('POST', Url, true);
xhr.send(x);
xhr.send(y);
xhr.onreadystatechange = processRequest;
function processRequest(e) {
if (xhr.readyState == 4 && xhr.status == 200) {
alert(xhr.responseText.headers.Host);
var response1 = JSON.parse(xhr.responseText);
document.getElementById("updated_time").innerHTML = response1.updated_time;
document.getElementById("id").innerHTML = response1.id;
}
}
}
}
</script>
</head>
<!DOCTYPE html>
<html>
<head>
<body>
<center>
Javascript Post Request Test
<br><br>
<form name="myForm">
<input type="text" placeholder= "machine id" name="machine_id"/>
<input type="text" placeholder= "wifi mac address" name="wifi_mac_address"/>
<input type="button" id="Save" onclick="function fun()" value="get_values"/>
</form>
<br><br>
<table>
<tr><td>id :</td><td id="id"></td></tr>
<tr><td>updated_time :</td><td id="updated_time"></td></tr>
</table>
</center>
</body>
</html>
http://192.168.1.9:8080/machine_reg/ this is my URL. And its a POST method. Now in this URL, if I POST ("machine_id": "TNTEST004","wifi_mac_address":"80:56:f2:18:12:11") these two JSON datas, it will generate an ID (eg:"id: 3"). I have to pass this two json datas in the text boxes with the submit button and on the button click, I should have the id returned in a alert window. I am bit confused getting an error. resolve this for me using ajax in javascript.
I will pass as like this.
{
"machine_id": "TNTEST009",
"wifi_mac_address": "80:56:f2:18:12:11"
}
This is the ID generated if I pass the machine ID and the wifi mac address.
{
"id": 5,
"machine_id": "TNTEST009",
"wifi_mac_address": "80:56:f2:18:12:11",
"auth_token": "",
"updated_time": "2018-05-01T13:14:42.372174Z"
}
Note:(Use Advanced Rest Client app for referrence if you wanna see how this actually works on the post request.)
I'm not sure I understand your question... But this is how you do an ajax request with jquery.
$.ajax({
url: '/User/PrevalidateLevelThree',
type: 'POST',
data: {
machine_id: 'TNTEST009',
wifi_mac_address: '80:56:f2:18:12:11'
},
success: function (result) {
alert(result);
},
});
Again, i'm not sure I understand your question but I think this will give you a good start...
I guess I'm a little confused here. I have my home page and I click the search button, which calls a jquery post (tried with .get too) to my controller. The controller gets some info and then, at that point, I want to display a new page/view called "Events". BUT, the page isn't loading in the browser, the HTML for the view is being sent back in the jquery post results. FYI - I'm only using a form to get validation results, I'm not submitting it with any button click.
Question - Do I have to submit a form for this to work the way I expect it too?
Here is my controller code.
[HttpPost]
[AllowAnonymous]
public ActionResult JumbotronSearch(SearchCriteria searchCriteria)
{
try
{
var viewModel = new EventsViewModel();
DbGeography location = Geocoding.GetDbGeography(searchCriteria.latitude.ToString(), searchCriteria.longitude.ToString());
viewModel.Events = _Repository.AllWithinDistance(location,
searchCriteria.date.Add(searchCriteria.date == DateTime.Now.Date
? DateTime.Now.TimeOfDay
: new TimeSpan(12, 0, 0, 0)), 1);
viewModel.SearchCriteria = searchCriteria;
return View("Events",viewModel);
}
catch (Exception ex)
{
// log exception in file or db or both
return Json(new { error = "true", message = "Oh No! Something happened trying to submit your search. Please contact YogaBandy Help Desk." });
}
}
Here is the /home/index view form
<form id="jumbotronForm" class="form-group form-inline" style="position: relative">
<input id="jumbotronSearch" type="text" class="form-control input-lg" placeholder="Location" required maxlength="50" minlength="4" />
<label id="location-error" for="jumbotronSearch" style="display: none;">The location was not found.</label>
<input id="jumbotronDate" type="text" class="form-control input-lg" value="#DateTime.Now.Date.ToShortDateString()" readonly/>
<input id="jumbotronSubmit" type="button" class="btn btn-default btn-lg" value="Search" />
</form>
Here is the javascript to my controller to get the results and load the new view
$("#jumbotronSubmit").off('click').on('click', function() {
model.date = $('#jumbotronDate').val();
var form = $('#jumbotronForm');
form.validate();
if (form.valid()) {
if (model.formatted_address == location.value) {
submitSearchCriteria(model);
} else {
var navbarGeocoder = new google.maps.Geocoder();
navbarGeocoder.geocode({
'address': location.value
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
model.formattedAddress = results[0].formatted_address;
model.latitude = results[0].geometry.location.lat();
model.longitude = results[0].geometry.location.lng();
model.mapType = results[0].types[0];
submitSearchCriteria(model);
} else {
$('#location-error').show();
setTimeout(function() {
$('#location-error').fadeOut('fast');
}, 2000);
yb.base.displayNotification("Couldn't find location. Check your spelling", 'danger');
}
});
}
function submitSearchCriteria(model) {
$.post(scope.enumControllers.jumbotronSearch, model, function(result) {
if (result.error == true) {
yb.base.displayNotification(result.message, 'danger');
}
}).fail(function(jqXHR, textStatus) {
yb.base.displayNotification("Oh no! Something went wrong sending your request. Please contact the help desk.", 'danger');
});
}
}
});
Just use the following to get the data.
var info;
$("#div").load("URL",function(response, status, xhr){info = response;});
I'm using a small library called liveValidation.js.
I'm using this to validate a couple of inputs in a form.
It should automatically disable the form button if there's some invalid inputs, but it doesn't seam to work.
Here's my HTML code:
<form method="POST" id="contactForm">
<label for="name">Name</label>
<input type="text" name="name" id="contactFormName" value=""/>
<label for="email">E-Mail</label>
<input type="text" name="email" id="contactFormEmail" value=""/>
<label for="message">Your message here</label>
<textarea name="message" id="contactFormMessage"></textarea>
<input type="submit" id="submit" value="submit"/>
</form>
Here's how I initialize liveValidation.js:
function liveValidation() {
var name = new LiveValidation('contactFormName');
name.add(Validate.Presence);
var email = new LiveValidation('contactFormEmail');
email.add(Validate.Presence);
email.add(Validate.Email);
var message = new LiveValidation('contactFormMessage');
message.add(Validate.Presence);
};
$(document).ready(function ($) {
$("#loadingDiv").hide(400);
liveValidation();
sendEmail();
});
and this is the AJAX request code:
function sendEmail() {
var form = $("#contactForm");
var resultDiv = $(".formResult");
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "sendEmail.php",
data: form.serialize()
}).done (function (){
resultDiv.addClass('success').html('Message sent successfully')
}).fail(function () {
resultDiv.addClass('fail').html("Message not sent. Try again")
});
}
});
};
Any thought why this is not working properly?
Here's the livevalidation website if it could help -> http://livevalidation.com/
You need to check manually if the form is valid. To do that you need one (any one) of the LiveValidation objects
Try this
$(document).ready(function ($) {
var obj = liveValidation();
sendEmail(obj);
});
function liveValidation() {
var name = new LiveValidation('contactFormName');
name.add(Validate.Presence);
var email = new LiveValidation('contactFormEmail');
email.add(Validate.Presence);
email.add(Validate.Email);
var message = new LiveValidation('contactFormMessage');
message.add(Validate.Presence);
return name;
};
function sendEmail(obj)
{
var automaticOnSubmit = obj.form.onsubmit;
$("#submit").click(function () {
var valid = automaticOnSubmit();
if(!valid)
{
alert('The form is not valid!');
event.preventDefault();
}
else
{
//submi form
}
});
}
An alternate and better way, you can use any LiveValidation object to attach the event
$(document).ready(function ($) {
liveValidation();
sendEmail();
});
function liveValidation() {
var name = new LiveValidation('contactFormName');
name.add(Validate.Presence);
var email = new LiveValidation('contactFormEmail');
email.add(Validate.Presence);
email.add(Validate.Email);
var message = new LiveValidation('contactFormMessage');
message.add(Validate.Presence);
var automaticOnSubmit = name.form.onsubmit;
name.form.onsubmit = function(){
var valid = automaticOnSubmit();
if(valid)
alert('The form is valid!');
else
alert('The form is not valid!');
return false;
}
};
function sendEmail()
{
$("#submit").click(function () {
//submit form here
});
}
I am trying to make an offline HTML5 application that submits a form containing a image and a text input for a email address, when a internet connection is avaiable
This is what I have tried:
<body>
<script type='text/javascript'>
window.onload = function () {
function submit() {
setInterval(function () {
if (navigator.onLine) {
//if internet is avaiable do:
document.getElementById("upload").submit();
}else {
//if no internet
var theDiv = document.getElementById("message");
var content = document.createTextNode("No internet");
theDiv.appendChild(content);
}
}, 1000);
}
}
</script>
<form action="post.php" method="post" enctype="multipart/form-data" id="upload">
<input type="file" name="uploaded" accept="image/*" capture><br>
<p>Skriv inn din epost: <input type="text" name="email"></p>
<input type="submit" value="Send ditt bilde!" name="sendimg" onclick="this.value='Submitting ..';this.disabled='disabled'; submit();">
<div class="message"></div>
Does someone have any suggestions? Thanks :)
Thee two ways to check this
This solution requires jQuery
$.ajaxSetup({
timeout: 1, // Microseconds, for the laughs. Guaranteed timeout.
error: function(request, status, maybe_an_exception_object) {
if(status == 'timeout')
alert("Internet connection is down!");
}
});
And
window.navigator.onLine -- it will be false if the user is offline.
You need to use above in your code with some tweaking as per requirement.
Sorry, but i cant comment yet. Will this work?
<script type='text/javascript'>
window.onload = function () {
function submit() {
setInterval(function () {
if (window.navigator.onLine == "true") {
//if internet is avaiable do:
document.getElementById("upload").submit();
}else {
//if no internet
var theDiv = document.getElementById("message");
var content = document.createTextNode("No internet");
theDiv.appendChild(content);
}
}, 1000);
}
}
</script>
Instead of continuous checking for Internet connection, you can use online and offline events. For reference see this https://developer.mozilla.org/en/docs/Online_and_offline_events. If the user is offline, save the data in local storage and then resend the data once the online event is again detected.
I have a form with a css submit button. When a the submit button is clicked, i call a function that executes:
document.forms["request"].onsubmit();
What should happen, then, is that the onsubmit method ought to be triggered. This works properly in Chrome/FF, but for some reason IE/Safari will bypass the onsubmit function and simply add the parameter "address=" onto the url as if it were submitting the form and ignoring the onsubmit function. Heres the code for the form:
<form id="request" method="get" onsubmit="addLocation(this.address.value); return false;">
<br>
<label style="position:relative;left:5px;" for="address">Enter an intersection or address:
</label>
<br>
<br>
<input style="height:35px; width:300px;position:relative;bottom:1px;left:10px;" id="address" name="address" class="required address"/>
<a style="float:right;right:120px;position:relative;" class="button" onclick="submit();">
<span>Submit Request
</span>
</a>
</form>
and what follows are some relevant js functions:
function addLocation(address) {
if (geocoder) {
geocoder.getLocations(address, function (point) {
if (!point) {
alert(address + " not found");
} else {
if (point.Placemark[0].address != submittedString) {
submittedString = point.Placemark[0].address;
addRow(point.Placemark[0].address);
req = "addrequest?truck=" + "coolhaus&address=" + point.Placemark[0].address;
alert(req);
addRequest(req);
request.onreadystatechange = function () {}
}
}
});
}
}
function addRequest(req) {
try {
request = new XMLHttpRequest();
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
alert("XMLHttpRequest error: " + e);
}
}
request.open("GET", req, true);
request.send(null);
return request;
}
You can test the form here:
http://la.truxmap.com/request?id=grillmastersla
Thanks so much!
Don't name your function "submit", there is already a method in the form with that name, so it can conflict with that.
It's the submit method that you can call to submit the form, not the onsubmit event. So, your code to post the form should be:
document.forms["request"].submit();