parse name from user input when using jquery serialize - javascript

I am trying to grab user input from a dynamic form using jquery serialize. My form looks like this
<form id="lookUpForm">
<input name="q" id="websterInput" />
<button onclick="webster(); return false;">Search</button>
</form>
I want to take the input, and attach it to the end of websters dictionary URL to search for a word.
http://www.merriam-webster.com/dictionary/ + (user input)
When you run an alert to see what the value of 'q' is, you get
q=input
so for example if I put 'cats'
the alert would say q=cats.
I want the the string to just be what the user entered. However, you need to give the input a name to use seralize. So how can I take the user input, and strip out the 'q=' part.
EDIT
as requested here is the function I'm calling. Note. I HAVE to use serialize(); This isnt an option.
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
type: 'GET',
crossDomain: 'true',
url: "http://www.merriam-webster.com/" + stringHolder,
success: function (data) {
console.log(data);
console.log("http://www.merriam-webster.com/" + stringHolder);
},
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" + stringHolder);
}
});
};

You can just access it using val method of jQuery
function webster() {
var stringHolder = $("#lookUpForm").serialize();
alert(stringHolder);
$.ajax({
// (...) removed some code for brevity
error: function () {
alert("Failed to get dictionary data");
console.log("http://www.merriam-webster.com/dictionary/" +
$('#websterInput').val()); // I suppose you want the user-input here
}
});
};

You could use serializeArray().
And then do something like this and put your string together like you want to
var array = $("#lookUpForm").serializeArray();
$(array ).each(function(){
alert(this.value);
});

Related

Javascript function (with variable information in URL) for a simple GET request

The situation is as follows:
A webpage with two inputs; input_1 and input_2
input_1 is a code to be entered by the user
input_2 is more like a token string, pre-filled or to be filled by user
The URL format for the GET request is like this: https://www.apiserver.com/api/v1/static_param_1/input_1/tokens/redeem?token=input_2
The webpage has a form, which includes a button with an element_id of button_1, two text elements with element id's elem_input_1 and elem_input_2.
I need to use javascript to create the GET request which gets fired when the user has input the values and clicked the button.
I tried the following so far. Any help is highly appreciated:
var button = document.getElementById('button_1');
function executeGetReq() {
var input_1 = document.getElementById('elem_input_1').value;
var input_2 = document.getElementById('elem_input_2').value;
var url = "https://www.apiserver.com/api/v1/static_param_1/" + input_1 + "/tokens/redeem"
var data = {
token: input_2,
};
$.get(url, data, function (result) {
if (result == 'ok')
alert('Success!');
else
alert('Failure');
});
}
button.onclick = executeGetReq;
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="elem_input_1" value="input_1"/>
<input id="elem_input_2" value="input_2"/>
<button id="button_1">Go</button>
EDIT:
Well, it seems the problem is with CORS. Still digging.
Try to set the dataType to jsonp (But before set it to json).
$.get(url, data, function (result) {
//...
}, 'jsonp');
If it doesn't work search for ajax cors on the web.
Or take a look at https://www.codegrepper.com/code-examples/javascript/ajax+cors+error

Adding to JSON array by HTML button

I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.

How to fill AJAX with values from multiple inputs?

So i have an AJAX function and I want to search every element with particular class, take its value and add it into the AJAX in the right format. Is that possible?
I have this AJAX function:
function sendOrders(button) {
$.ajax({
url: "external_file.php",
method: "POST",
data: {
/*Here I need to add the data*/
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
}
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
and I need to collect data from hidden-type inputs on the page with class="order".
I know that I can acces each element by class with jquery, but I have no idea how to add the properties to my AJAX, when it's already written. Number of those elements is variable and they have non-repeating ids, class is the same. Inputs look like this:
<input class="order" type="hidden" name="some_name" id="some_id" value="some_value">
Can anyone help?
From what I understand, you want to make that ajax call with several different values that you get from the inputs with class order?
Assuming you want to just add the value from those fields, you can do something pretty simple:
First, update your ajax function with an additional input variable,
function sendOrders(button, val) {
$.ajax({
url: "external_file.php",
method: "POST",
data: {
value : val,
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
}
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
Then, to get data from all of your 'order' class inputs, you can use Jquery's 'each' function. For example, if you want the value from each of those inputs, you can use your new sendOrder function in the each function:
$('.order').each(function(){
sendOrder(buttonId, $(this).val())
});
Not quite sure how you are using 'button' in your ajax function, but I assume it's associated with your save or submit button, so buttonId would be whatever the id is of that button. This will iterate over all inputs with class order and make the ajax call with those values.
If you're using the button as a submit you can probably take it out all together from the ajax function, and have something like this:
function sendOrders(val) {
$.ajax({
url: "external_file.php",
method: "POST",
data: {
value : val,
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
}
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};
$('#buttonId').click(function(){
$('.order').each(function(){
sendOrder(buttonId, $(this).val())
});
});
Create the data object, loop over all the inputs, and add the values to the object.
function sendOrders(button) {
var data = {
GameID: "'.$_SESSION['GameID'].'",
Round: "'.$round.'",
UserID: "'.$_SESSION['UserID'].'",
};
$(button).closest("form").find("input[type=hidden]").each(function() {
data[this.name] = this.value;
});
$.ajax({
url: "external_file.php",
method: "POST",
data: data
}).done(function( msg ) {
$("#DEBUG").html(msg);
});
};

jQuery / ajax data container + organization

My dad and I are working on a project where we'd like to create a script that calls in data when a number is submitted into a form. For example, when you type in your ID number then press ENTER or SUBMIT, the form will print/display information. This is a project for school, so when a student submits their ID number it will read their first period class, for example.
I have the following script code to set up the form:
<form id="firstPeriod" action="firstPeriod.html">
<p>Find your first period.</p>
<p><label>Student no.: <input type="text" name="studentNo"></label></p>
<p><input type="submit" value="Find it"></p>
<p id="result"></p>
</form>
<script type="text/javascript">
$(function() {
$('#firstPeriod').submit(function() {
$.ajax({ // Send the request behind the scenes
url: $(this).attr('action'), // Send it here
data: $(this).serialize(), // With this student no.
success: function(data) {
$('#result').html(data); // Display the resulting HTML
},
error: function(jqxhr, status, error) {
console.log(error);
$('#result').html('No results found. Please check your number and reenter'); // Notify an error
}
});
return false; // Prevent the normal form submission
});
});
My question is, what would be the best way to organize the data? An array, HTML, etc.? There are quite a lot of ID numbers and are currently set up in an HTML table, but that doesn't seem to work in calling the information. And I'd like for the data to be specific. So when a specific ID number is typed in, it reads a specific answer. Right now my problem is when I type in a number it reads several classes.
If there are any suggestions/advice/other posts that could help me, I'd be grateful. I have solid HTML, CSS experience but I'm still learning JS and jQuery so this is a little new for me. Thanks!
Edit, Updated
Note, added value attribute to input type="text" element
<input type="text" name="studentNo" value="" />
substituted .submit() for .on("click") at input type="submit" element
Two possible approaches could be 1) using HTML to store data, .load() to retrieve fragment identifier within html file; or 2) storing data using JSON, retrieving file using php
html at firstPeriod.html
<div id="0">data 0</div><div id="1">data 1</div>
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$("#result").load(form.attr("action") +" #"+ id)
})
})
plnkr http://plnkr.co/edit/4onHf9jlJTyDei1zo9IC?p=preview
JSON
0.json
{
"0":"<div id='0'>data 0</div>"
}
1.json
{
"1":"<div id='1'>data 1</div>"
}
javascript
$(function() {
var form = $("#firstPeriod");
$("input[type=submit]").on("click", function(event) {
event.preventDefault();
event.stopPropagation();
var data = form.serializeArray();
// where `data[0].value` is `id`; e.g.; `0`
var id = data[0].value;
$.post("data.php", {id:id}, function(result) {
$("#result").html(result[id])
}, "json")
})
})
php
<?php
if (isset($_POST["id"])) {
$id = $_POST["id"];
$file = $id . ".json";
if (file_exists($file)) {
$jsondata = file_get_contents($file);
$id_data = json_decode($jsondata, true);
echo json_encode($id_data);
};
}

submit a form with jQuery function

i have a html page, which contains a form and i want when the form is successfully submited, show the below div:
<div class="response" style="display: none;">
<p>you can download ithere</p>
</div>
i also have a jquery function:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
$(".response").show();
}
});
});
});
</script>
and in my views.py (code behind) i create a link and pass it to html page. i have:
def backup(request):
if request.is_ajax():
if request.method=='POST':
//create a link that user can download a file from it. (link)
variables = RequestContext(request,{'link':link})
return render_to_response('backup.html',variables)
else:
return render_to_response('backup.html')
else:
return render_to_response("show.html", {
'str': "bad Request! :(",
}, context_instance=RequestContext(request))
backup = login_required(backup)
my problem: it seems that my view doesn't execute. it doesn't show me the link that i send to this page. it seems that only jQuery function is executed. i'm confused. how can i make both of them to execute(i mean jQuery function and then the url i set in this function which make my view to be executed.)
i don't know how to use serialize function. whenever i searched, they wrote that:
The .serialize() method creates a text string in standard URL-encoded notation and produces query string like "a=1&b=2&c=3&d=4&e=5.
i don't know when i have to use it, while i can access to my form field in request.Post["field name"]. and i don't know what should be the data which is in success: function(data) in my situation.
thank very much for your help.
You have to get and display the data from your ajax post function, where data is the response you render through your DJango server, for example:
t = Template("{{ link }}")
c = Context({"link": link})
t.render(c):
Your JS / jQuery should become something like this:
<script type="text/javascript">
$(function() {
$('#sendButton').click(function(e) {
e.preventDefault();
var temp = $("#backupSubmit").serialize();
validateForm();
$.ajax({
type: "POST",
data: temp,
url: 'backup/',
success: function(data) {
// 'data' is the response from your server
// (=the link you want to generate from the server)
// Append the resulting link 'data' to your DIV '.response'
$(".response").html('<p>you can download ithere</p>');
$(".response").show();
}
});
});
});
</script>
Hope this helps.

Categories