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

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>

Related

form input reload page with appended url

I have the following form posted on a wordpress page.
I´d like to catch users without referrers to set the referrer on their own (that referrer part is all handled by a plugin... does not matter here).
The registration form Url is like:
http://myurl.com/register/
The code below just works fine. Inserted directly into the wp page editor (text).
Except it creates a Url like follows:
http://myurl.com/register/?id=testinput
How do i get the resulting Url to be formatted this way?:
http://myurl.com/register/sp/testinput
<h3>Your ID</h3>
<p>Please input your ID</p>
<form id = "submit_id_form" onsubmit="myIDFunction()">
<input type="text" name="id">
<input type="submit" value="Confirm">
</form>
<?php
function myIDFunction(){
var action_src = "http://myurl.com/register/" + document.getElementsByName("id")[0].value;
var submit_id_form = document.getElementById('submit_id_form');
submit_id_form.action = action_src ;
} ?>
</script>
This is the original form code (reference below) i`m trying to modify:
<form id = "your_form" onsubmit="yourFunction()">
<input type="text" name="keywords">
<input type="submit" value="Search">
function yourFunction(){
var action_src = "http://localhost/test/" +
document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
}
</script>
I tried to append the /sp/ part and remove the appended question mark "?" in the code above.. but i´m totally stuck with coding. (I´m a "clicker" not a coder so to speak)
Thank you very much guys and gals :)
Original Code is from here
You have to return true from method called on onsubmit as
function yourFunction(){
var action_src = "http://localhost/test/" + document.getElementsByName("keywords")[0].value;
var your_form = document.getElementById('your_form');
your_form.action = action_src ;
return true;
}

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.

Input from the form is not passed to the controller and keeps being "undefined"

I have the hardest time dealing with forms and passing values from them to the controller. I have the same story every time: the ng-model and everything is set up but the controller is not accepting what I'm trying to pass it and thus gives me that the var is not defined. Would anyone suggest how to deal with this and how to properly setup forms with Angular? Their documentation is darn awful!
Here's the markup of the form:
<div>
<form name="thisForm" ng-submit="submit()" class="wa-id-submit-form">
<label>Submit your number</label>
<input name="wa_id" ng-model="submission" type="text" class="form-control" required />
<input type="submit" class="form-control" name="submit" value="Submit" />
</form>
</div>
Here's the function and the var I'm trying to pass it to:
$scope.submit = function() {
var data = {
"wa_id": $scope.wa_id
};
console.log($scope.wa_id);
var hookphp = submitIdService.submitId();
hookphp.save(data,
function(result){
console.log(result);
};
The php side of this all works just fine and doesn't need to be looked at. I just need to pass that one line from the input to the data variable and it's not. Am I not making the ng-model and such talk properly to each other?
},
function(result){
console.log('NO GO');
}
);
};
You should use corresponding ngModel to access data in controller, not input name:
var data = {
wa_id: $scope.submission
};
I have been reminded of something very important when dealing with ng-models here
The ng-model has to have a .notation in it to function properly. It's possible that it would function without it as well, but even people who help develop Angular strongly recommend using it with a "."
Here's what had to be done with my code:
<form ng-submit="submit()" class="wa-id-submit-form">
<label>Submit your number</label>
<input name="waid" ng-model="waid.submission" type="text" class="form-control" required />
<input type="submit" class="form-control" name="submit" value="Submit" />
</form>
an ng:
$scope.waid = {};
$scope.submit = function() {
var data = {
"wa_id": $scope.submission
};
var hookphp = submitIdService.submitId();
hookphp.save(data,
function(result){
console.log(result);
},
function(result){
console.log('NO GO');
}
);
};
An object had to be declared "empty" prior to being able to use it in the function as well.

Hashchange html submit

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

Pass variable to HTML form Javascript

Please excuse my inexperience as I am not a programmer just someone who dabbles at trying to make something work. I'm not sure of the correct terminology and complicated explanations will go straight over my head!
In essence I am trying to get part of the URL of a web page passed to a simple Form that is linked to a shopping cart. i.e. how do I get the filename into the form where I have xxxxxxx. Is it possible in Javascript?
<script type="text/javascript">
var url = window.location.pathname;
var filename = url.substring(url.lastIndexOf('/')+1);
document.write (filename);
</script>
<form action="http://www.mywebspace.com/cf/add.cfm" method="post">
<input type="hidden" name="userid" value="12345678">
<input type="hidden" name="product" value="xxxxxxx">
<input type="hidden" name="price" value="5.00">
<input type="Submit" value="Buy now!">
</form>
I've provided a snippet code that will work with your current HTML structure. Though I do suggest you give the product field an id to prevent the necessity to loop and search elements:
var url = window.location.pathname,
filename = url.substring(url.lastIndexOf('/')+1);
fields = document.getElementsByTagName('input');
for(var i = 0; i < fields.length; i++){
if(fields[i].name == 'product') {
fields[i].value = filename;
break;
}
}
If the form only exists once on a given page, this is an easy solution:
Change it to be:
<input type="hidden" id="productField" name="product" value="xxxxxxx">
In your javascript,
document.getElementById('productField').value = filename;
Yes this is possible.
Instead of doing document.write you need to update the form. Assuming your filename value is currently correct:
//js
document.getElementById( "name-of-file").value = filename;
<!- html -->
...
...

Categories

Resources