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.
Related
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>
Yesterday I made my first successful AJAX call using this function which was linked to a button click event.
function function1(){
$.get("ajax/calendar.php", function(data){
$('#ajaxResponse').html(data);
});
};
Now I would like to use the $.post method so that I can pass in 2 values that I had simply hard coded when I used the $.get method.
Here are my inputs and submit button:
<div ... >
<div ... >
<div ... >
<span ... >From:</span>
<input ... name="strDte">
</div>
<div ...>
<span ... >To: </span>
<input ... name="endDte">
</div>
</div>
<div ... >
<button type="submit" onclick="dateRange(strDte, endDte)">OK</button>
</div>
</div>
I created a similar function to my $.get method:
function dateRange(startD, endD){
$.post("ajax/calendar.php", {startDate : strDte, endDate : endDte}, function(data){
$('#ajaxResponse').html(data);
});
};
and I updated "ajax/calendar.php" to accept the value that were hard coded before:
$formStartDate = $_POST['startDate'];
$formEndDate = $_POST['endDate'];
EDIT: my console is telling me that the parameters are not being recognized by function call in the event handler.
Does anyone see what my issue is? I'd also love some design suggestions if you think there is a better way of achieving this function.
You are passing up form elements, not the values of the elements. You have wrong variable names.
Give the inputs ids
<input ... name="strDte" id="strDte">
<input ... name="endDte" id="endDte">
Update the JavaScript to reference the value.
function dateRange(startD, endD){
$.post("ajax/calendar.php", {startDate : startD.value, endDate : endD.value}, function(data){
$('#ajaxResponse').html(data);
});
};
You are using bad practice by referencing elements directly by their name/id and inline events are not the greatest thing to use. You should use getElementById or querySelector to reference the elements.
The variable names used in your function definition should match the names you use within your function. That is
{startDate : strDte, endDate : endDte}
should be
{startDate : startD, endDate : endD}
I suggest you play around with this fiddle: http://jsfiddle.net/Uwcuz/3657/
It is using a service from JSFiddle to echo back what you send to it. I changed the AJAX call to use $.post() instead of $.ajax() since this is the function you are playing with! :)
Some additional tips when learning such technologies. Always check with your browsers developers' tools. There you can follow the request being sent to your backend and catch any errors. The "Network" and "Console" (on Chrome dev tools, but Firefox has similar, too) tabs are your friends in this case!
Enjoy and happy learning!
Since you are not using a form, you should be declaring your button to be a button type to show that you are not submitting a form.
<button id="submitBtn" type="button">OK</button>
Your problem is that you are not supplying an id attribute for your <input> tags. name is only used in forms. Change your <input> tags to be
<input id="strDte">
<input id="endDte">
Then in your script, you can use
$("#submitBtn").click(function () {
var start = $("#strDte").val();
var end = $("#endDte").val();
$.post("ajax/calendar.php", { startDate: start, endDate: end }, function (data) {
$("#ajaxResponse").html(data);
}
});
The variable names you pass into the function must pass those you use in the data parameter of $.post(). You're passing:
startD but trying to use strDte .. and
endD but trying to use endDte .... strDte and endDte are not defined anywhere.
Try this instead:
function dateRange(startDate, endDate){
$.post("ajax/calendar.php", {startDate : startDate, endDate : endDate}, function(data){
$('#ajaxResponse').html(data);
});
};
UPDATE
Now that I know where the confusion was coming from the best approach is one that allows you to separate, clearly, your JS from your HTML.
Per your request for suggestions, here's how:
$(function() {
$('#my_form').on('submit', function(event) {
//stop the form from submitting via default submission
event.preventDefault();
//get form data
var formData = $(this).serialize();
//see what the data looks like
console.log( formData );
//make ajax call
$.post('ajax/calendar.php', formData, function(data){
$('#ajaxResponse').html(data);
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="my_form">
<div><label for="strDte">Start Date:</label>
<input type="text" name="startDate" id="strDte"/>
</div>
<div><label for="endDte">End Date:</label>
<input type="text" name="endDate" id="endDte"/>
</div>
<div>
<input type="submit" value="OK" />
</div>
</form>
here is a simple ajax post you can play around with...
<input id="start_date" name="startDate" />
<input id="end_date" name="endDate" />
<button type="submit" id="submit_dates">Submit</button>
$(document).ready(function(){
$("button#submit_dates").click(function(){
var startDate = $("#start_date").val();
var endDate = $("#end_date").val();
$.ajax({
type:'POST',
url:'ajax/calendar.php',
data:"startDate=" + startDate + "&endDate=" + endDate,
success:function(data) {
if(data) {
$("#ajaxResponse").html(data);
} else {
// no response
}
}
});
});
});
I have the following form. Each time the users clicks add_accommodation I want to add to an array that I will return to the end point (http://server/end/point).
<form action="http://localhost:3000/a/b/c" method="post">
<div>
<input type="hidden" id="Accommodation" name="accommodation"><div>
</div>
</form>
<div id="accommodation_component">
<div>
<label for="AccommodationType">Type:</label>
<input type="number" step="1" id="accommodationType" name="accommodation_type" value="0">
</div>
<div>
<button type="button" id="add_accommodation">Add Accommodation</button>
</div>
</div>
<script>
$( document ).ready(function() {
$('#add_accommodation').click(function() {
make_accommodation(this);
});
});
function make_accommodation(input) {
var value = {
type : $("#AccommodationType").val(),
};
var accommodation = $('#Accommodation').attr('id', 'accommodation');
accommodation.push(value);
console.log(accommodation);
}
</script>
At my end point I want the result to be and array (accommodation = [{1},{2},{3},{4}]). How can I do this?
Give the form an id, and just append a new hidden(?) input that has a name that has [] at the end of it, it will send the values as an array to the server.
HTML
<form id="myform" ...>
Javascript
function make_accommodation(){
var newInput = $("<input>",{
type:"hidden",
name:"accommodation[]",
value: {
type: $("#AccommodationType").val()
}
});
$("#myform").append(newInput);
}
Also you list the output as [1,2,3,4] but your code shows you setting the value as an object with a property type and setting it to the value of the accommodation input, i am going to assume that was a mistake. If I am mistaken just modify the value property in the code above.
Also in your code you change the id of the input, not sure why you were doing that as it serves no purpose and would have made your code error out so i removed it.
EDIT
Since you are wanting to send an array of objects, you will have to JSON.stringify the array on the client end and decode it on the server end. In this one you do not need multiple inputs, but a single one to contain the stringified data.
var accommodationData = [];
function make_accommodation(){
accommodationData.push({
type: $("#AccommodationType").val()
});
$("#accommodation").val( JSON.stringify(accommodationData) );
}
Then on the server you have to decode, not sure what server language you are using so i am showing example in PHP
$data = json_decode( $_POST['accommodation'] );
If you are using jQuery's ajax method you could simplify this by sending the array data
jQuery.ajax({
url:"yourURLhere",
type:"post"
data:{
accomodation:accommodationData
},
success:function(response){
//whatever here
}
});
Add antorher hidden field in form
<input type="hidden" name="accommodation[]"> // click1
<input type="hidden" name="accommodation[]"> // click2
...
<input type="hidden" name="accommodation[]"> // clickn
Then when you submit form on server you will have array of accommodation.
JS part :
function make_accommodation() {
$(document.createElement('input'))
.attr('type', 'hidden')
.attr('name', 'accommodation[]')
.val($("#AccommodationType").val())
.appendTo('form');
}
on server(PHP) :
print_r($_POST['accommodation']);
Since you're using jQuery you can create a function which creates another hidden field, after clicking on the button
<div id='acommodation-wrapper'></div>
<button type="button" id="add_accommodation" onclick="addAnother()">Add Accommodation</button>
<script type="text/javascript">
function addAnother(){
var accWrapper = $('#accommodation-wrapper');
var count = accWrapper.children().length;
var div = "<input type=\"hidden\" class=\"accommodation-"+count+"\" name=\"accommodation["+count+"]\"></div>";
accWrapper.append(div);
}
</script>
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
This is the fragment of code inserted with ajax:
<form>
<label for = "task-name">Name</label>
<input type = "text" id = "task-name" />
<label for = "task-description">Description</label>
<input type = "text" id = "task-description" />
<input type = "hidden" id = "task-col" />
<input type = "hidden" id = "task-row" />
<input type = "submit" id = "add-task" onclick="return false" value="Add" />
</form>
This is the JS code which insert the previous element in the DOM:
$('html').on('click', '.task-pop', function(){
var pos = $(this).parent().parent().attr('class').split("-");
ajaxObj = getXmlHttpObject();
ajaxObj.onreadystatechange = function(){
if(ajaxObj.readyState == 4 && ajaxObj.status == 200){
$('#pop-hold').html(ajaxObj.responseText);
$('#task-col').val(pos[0]);
$('#task-row').val(pos[1]);
}
};
ajaxObj.open("GET","resources/component/newTask.jsp");
ajaxObj.send(null);
$('#pop-blk').css('display','block');
$('#pop').show("fast");
});
As you can see I'm trying to add some values to the hidden inputs #task-row and #task-col from the content added dynamically.
The page is properly displayed and no error is thrown but those two fields are never accessed. How can I solve this?
change
$('#pop-hold').html(ajaxObj.responseText);
$('#task-col').val(pos[0]);
$('#task-row').val(pos[1]);
with
var html = $(ajaxObj.responseText);
html.find('#task-col').val(pos[0]);
html.find('#task-row').val(pos[1]);
$('#pop-hold').html('').append(html);
You should use jQuery ajax(), would be much easier for you to handle the whole Ajax thing :
$('html').on('click', '.task-pop', function(){
var pos = $(this).parent().parent().attr('class').split("-");
$.ajax({
url: 'resources/component/newTask.jsp',
type: 'GET', // Default value is GET but I included it for you
success: function(data) {
$('#pop-hold').empty().append(data);
$('#task-col').val(pos[0]);
$('#task-row').val(pos[1]);
}
});
$('#pop-blk').css('display','block');
$('#pop').show("fast");
});
Just a part of the solution, hope it will help ^^
The fact that the inputs are hidden don't prevent you from setting their value with val().
When you call the val function like this $('#task-col').val(pos[0]);, make sure that:
The #task-col element exists
pos[0] is not undefined (you can test by replacing pos[0] with "test")
you are actually executing this line (you can test by putting an altet("test") the line before)
And when you use jQuery, don't mess around with the getXmlHttpObject as #Ethenyl said. Use $.ajax instead.