Hashchange html submit - javascript

There's a problem with my script. If I was to type something in with a spacebar, ie: google map it would change in input box: google+map what I don't like.
Also... When I submit again, it messes up more badly
<form name="input" action="" method="get">
Search: <input type="text" name="search">
<input type="submit" value="Submit">
<div id="result"></div>
</form>
--
$('form').submit(function() {
var form_data = ($(this).serialize());
window.location.hash = form_data.replace('=','/');
return false;
});
$(window).on('hashchange', function () {
var values = window.location.hash.slice(1).split('/');
$("[name=" + values[0] + "]").val(values[1]);
});
var values = window.location.hash.slice(1).split('/');
$("[name=" + values[0] + "]").val(values[1]);

You need to use decodeURIComponent to escape the value from the hash:
$('form').submit(function() {
var form_data = ($(this).serialize());
window.location.hash = form_data.replace('=','/');
return false;
});
$(window).on('hashchange', updateVal);
updateVal();
function updateVal() {
var values = window.location.hash.slice(1).split('/');
$("[name=" + values[0] + "]").val(decodeURIComponent(values[1]));
}

In this case FORM method 'GET' at <form name="input" action="" method="get"> should not be used.
According to W3 recommendation here
1.3 Quick Checklist for Choosing HTTP GET or POST
Use GET if: The interaction is more like a question (i.e., it is a
safe operation such as a query, read operation, or lookup). Use POST
if: The interaction is more like an order, or The interaction changes
the state of the resource in a way that the user would perceive (e.g.,
a subscription to a service), or The user be held accountable for the
results of the interaction.
In the GET the data is sent in URI and there is no spaces in URI and hence the problem.
However, if you need to use GET request for this then use decodeURIComponent to decodeURIComponent(values[1]) to escape the value

Related

How to call an URL based on search field input in ajax?

I have a search form on my index page.
<form method="post" action="search.php?go" id="searchform">
<input type="text" name="name">
<input type="submit" name="submit" value="Search">
</form>
This is part of the code on the search.php
var url = "https://externalwebsite.com/search?term=" + searchterms + "&variable2=something";
$.getJSON(url,function(data) {
var somevariable = Object.keys(data).length;
var div_data = '';
$.each(data, function(i,data) {
if ($("#some_div").html() == '');
......
I want to call an external search engine that gives back data in json.
How do I get the search terms into the ajax variable "searchterms" so I can add the search terms to the URL of an external search engine?
I can't figure it out.
You can't necessarily read from another website, this is to prevent XSS (Cross Site Scripting) attacks.
If you were able to read from other websites, you could potentially steal information from users. The only way to make requests to another website is through "JSONP".
JSONP bypasses the security requirements by acting as an external script. Instead of loading raw JSON data {"type":"JSON"}, it calls a function using the raw data. jsonpFunction({"type":"JSONP"});
You have to provide the callback function in order to handle it.
Assuming your input field called name is the field you want to pull terms from, give it an ID:
<input type="text" name="name" id="searchbox">
Then get the value using jQuery:
var searchterms = $('#searchbox').val();
Try the below code,
Replace url with your own
var searchterms = '';
function getTerm(term) {
console.log(term);
$('.term').text(term);
}
$("#submit").on("click", function() {
searchterms = $("#searchbox").val();
console.log(searchterms);
var url = "https://externalwebsite.com/search?term=" + searchterms + "&variable2=something";
console.log(url);
$.getJSON(url, function(data) {
console.log(data);
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" name="name" id="searchbox" onkeydown="getTerm(this.value);">
<input type="button" id="submit" value="search">
<p class='term'></p>

AJAX Form, passing return message

I have my AJAX form it works great.
Every time I submit the form It returns the result inside the <div id="message"></div>, but it gets complicated when I have multiple forms. So I was wondering if their is a way to indicate inside the form what <div> to return the message to.
Here is my AJAX.js
$("form#ajaxForm").on("submit", function() {
var form = $(this),
url = form.attr("action"),
type = form.attr("method");
data = {};
form.find("[name]").each(function(index, value){
var input = $(this),
name = input.attr("name"),
value = input.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
$("#message").html(response); //I would like to interactively switch the return div, from #message to like #message2
$("body, html").animate({
scrollTop: $( $("#message") ).offset().top - 5000
}, 600);
}
});
return false;
});
In the form I would like to indicate where the return div is, like
<form action="../forms/add_event_form.php" method="post" id="ajaxForm">
//Can I add an input somewhere here? To indicate where I want the return to go too? Like <input type="hidden" value="message2" name="return">
<input type="text" class="formI" name="date" id="dateI" placeholder="Date">
<input type="submit" name="submit" class="btn btn-primary" value="Add">
</form>
Thank you for reading this. Have a good day! And Thank you in advance for your responses.
Yes, it will not work automatically, but you can add some information to the form and then use it to decide where to put returned HTML. Doing that with additional inputs may not be the best way though, as it can be achieved with far less impact on the DOM: with an attribute on the form itself.
Here's an example of how you may do that.
$(".ajaxForm").on("submit", function(e) {
e.preventDefault();
var form = $(this);
// using jQuery's `data()` to get an ID of response element from the 'data-response' attribute
var responseElementId = form.data("response");
var response = $(responseElementId);
response.html(produceResponse(form));
// function that produces some html response
// you'll use AJAX request to the server for that
// so don't mind its complexity or bugs
function produceResponse(form) {
var data = form.find("input").map(function(i, el) {
return "'" + el.name + "': " + el.value;
});
return "<p>You've submitted:\n<pre>" + Array.prototype.join.call(data, ",\n") + "</pre></p>";
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<h2>Form #1</h2>
<form action="#" class="ajaxForm" data-response="#response1">
<input name="first-name" type="text">
<button>Submit</button>
</form>
<div id="response1"></div>
<h2>Form #2</h2>
<form action="#" class="ajaxForm" data-response="#response2">
<input name="last-name" type="text">
<button>Submit</button>
</form>
<div id="response2"></div>
Here I use a data attribute because it was designed for cases like this: to store arbitrary data related to the element, but which doesn't have any defined meaning for the browser. Accessing data stored in such way is really convenient with its HTML5 API, but because of pretty low support from IE (it has it only starting from the version 11), one may use jQuery's method data() to do the same.

JavaScript - How to assign user input value to variable inside script

Using widget script--http://socialmention.com/tools/-- from Social Mention. Tried to modify by adding input box to allow user to change social media topic (var smSearchPhrase). I created a function [smSearch()] to retrieve user data (smTopic), assign it to a new variable (var newTopic) and then assign that value to var smSearchPhrase. The assignment does not work.
The function appears to work based on values observed via alerts, however, I cannot figure out how to assign the value from var newTopic to var smSearchPhrase inside the script. I experimented by placing script inside the function, but that didn't work either. Any assistance is appreciated.
If I failed to include all necessary information, please advise. Thanks for any assistance.
HTML:
<form>
<label for="smTopic">Enter topic:</label>
<input type="text" id="smTopic">
<button onclick="smSearch()">Submit</button>
<input type="reset">
</form>
Function: (includes alerts to check values)
function smSearch(){
var newTopic=document.getElementById("smTopic").value;
if(newTopic === ""){
alert("Please enter new social media topic.");
}else{
alert("New topic: " + newTopic);
smSearchPhrase = newTopic;
alert("Value of smSearchPhrase: " + smSearchPhrase);
}
Script: var smSearchPhrase in original has value assigned, e.g. var smSearchPhrase = 'social mention';
<script type="text/javascript">
// search phrase (replace this)
var smSearchPhrase;
// title (optional)
var smTitle = 'Realtime Buzz';
// items per page
var smItemsPerPage = 7;
// show or hide user profile images
var smShowUserImages = true;
// widget font size in pixels
var smFontSize = 11;
// height of the widget
var smWidgetHeight = 800;
// sources (optional, comment out for "all")
//var smSources = ['twitter', 'facebook', 'googleblog', 'identica'];
</script>
<script type="text/javascript" language="javascript" src="http://socialmention.s3.amazonaws.com/buzz_widget/buzz.js"></script>
I think your form is submitting back to the backend, you need to stop the form from doing that by returning false from onsubmit or canceling the event.
So this should work:
<form onsubmit="return smSearch();">
<label for="smTopic">Enter topic:</label>
<input type="text" id="smTopic">
<button>Submit</button>
<input type="reset">
</form>
And return false in your JavaScript:
function smSearch(){
var newTopic=document.getElementById("smTopic").value;
if(newTopic === ""){
alert("Please enter new social media topic.");
}else{
alert("New topic: " + newTopic);
smSearchPhrase = newTopic;
alert("Value of smSearchPhrase: " + smSearchPhrase);
}
return false;
}
Personally I'd use preventDefault() on the event argument (not shown here), but that only works across all browsers when you also include a JavaScript library like jQuery as some versions of IE use a bubble property on the event or something.

How to read <input type="hidden"...> in JavaScript on subsequent page?

One first page:
A form SUBMIT goes to a subsequent page.
VBscript can see the hidden value with ... Request("myName") ...
How do I do the same thing in JavaScript.
alert(window.location.search);
or
alert(window.top.location.search.substring(1));
return nothing.
Well, you dont. When you submit a form it sends the values to a server, and the "server-side" reads that in vbscript as Request (Requested). If you want to let the requested value accessible to the Javascript, your server-side (subsequent) page must write that Request data back to the client-side, in other worlds, you have to write the requested value directily in the HTML that will be send back to the client browser.
Ex: In your ASP (Server-Side Subsequent VBScript file) you should write
Response.Write ("<script type=""text/javascript"">alert('" & Request("Data") & "')</script>")
<input type='hidden' id='hiddenId'/>
jQuery:
var value = $('#hiddenId').val();
alert(value);
Or
var value = document.getElementById('hiddenId').value;
alert(value);
In your form, you have to have the method set to GET.
<form method="GET" action="somepage">
<input type=hidden name=myHiddenValue />
</form>
Then on the next page, you can parse the search part of the url with a function like this.
function parseSearch(search, key) {
search = search.substring(1), items=search.split("&");
for (var i=0; i<items.length; i++) {
var item = items[i], parts = item.split("=");
if (parts[0] === key) {
return parts[1] || true;
}
}
}
parseSearch(location.search, "myHiddenValue"); // returns the hidden value
live demo

Get the original url in this case with jquery

In the form below, I change the action attribute and submit the form. That works fine. What goes on is: if the current location is http://localhost/search/?mod=all and the search term is 14, the action will be changed to http://localhost/search/?mod=all&handle=14 and so will the url in the browser.
But the next time I try to search, since the url now is http://localhost/search/?mod=all&handle=14, I get http://localhost/search/?mod=all&handle=14&handle=15. It'll keep going on and on with each search term.
Any idea how I can retain the orginal url http://localhost/search/?mod=all through this all.
Here's the form:
<form method="GET" class="modForm" action="">
<input type="text" placeholder="Search" class="modSearchValue">
<input type="radio" name="text" value="text" class="text" title="Search">
</form>
Here's the jquery:
$('.modForm').submit(function(event) {
var $this = $(this);
var query = $this.find('.modSearchValue').val(); // Use val() instead of attr('value').
var locale = window.location;
if ($('.text').is(':checked')) {
query = '&text=' + query;
} else {
query = '&handle=' + query;
}
route = locale + query;
console.log(route);
if (query.length >= 1) {
// Use URI encoding
var newAction = (route);
console.log(newAction); // DEBUG
// Change action attribute
$this.attr('action', newAction);
//event.preventDefault();
} else {
console.log('Invalid search terms'); // DEBUG
// Do not submit the form
event.preventDefault();
}
});
There are few ways to do it. I would rather not mess with window.location and do something simpler:
<form method="GET" class="modForm" action="">
<input type="hidden" name="mod" value="all"> <!-- mod is a hidden variable -->
<input type="text" id="modSearchValue"> <!-- name not defined yet -->
<input type="checkbox" id="textOrHandle"> <!-- name not required -->
</form>
$(".modForm").submit(function() {
$("#modSearchValue").attr("name", $("#textOrHandle").is(":checked") ? "text" : "handle");
// let the form submit!
});
You have multiple ways to do it. Why can't you store original URL in a global variable (kept outside your functions like form submit etc.)
If you do not want that you can use window.location.hash which will return all the GET params you are sending. Using split you will be able to get exact parameter that you want. If you still need help, I will post the code.
Quickest solution: If, for this code, window.location should always be http://localhost/search/?mod=all, then you don't even need to say var locale = window.location. Just say var locale = "http://localhost/search/?mod=all" and you avoid the problem.
​var s = window.location.hostname; // gets the hostname
var d = window.location.protocol; // gets the protocol
var g = window.location.search; // gets all the params
var x = g.split("&"); // split each parameter
var url = d+"//"+s+x[0]; // makes url you want
alert(url);​​​​ // just for chill

Categories

Resources