I need to pass data filled in a form, so it would be sent in a POST request using the Ajax code.
Here is my HTML form:
<!DOCTYPE html>
<html>
<head>
<title>Alteon Cluster Management</title>
<script src="jquery-1.11.2.min.js"></script>
<script src="alteon1.js"></script>
</head>
<body>
<button id="configR1btn">Configure Server 1</button> <button id="configR2btn">Configure Server 2</button>
<form>
<section>
<header>
<h1>R Servers</h1>
</header>
Server 1 IP Address: <input type ="text" name="firstRServerIP"><br><br>
Server 1 Name: <input type ="text" name="firstRServerName"><br><br>
Server 2 IP Address: <input type ="text" name="secondRServerIP"><br><br>
Server 2 Name: <input type ="text" name="secondRServerName"><br><br>
</section>
</form>
</body>
</html>
And here is my Ajax code:
$(document).ready(function(){
$('#configR1btn').click(function (){
var t = $(this);
//var t.closest(".form").find(".firstRServerIP").val();
var firstRServerIP = t.prev(".firstRServerIP").val();
var dataString = '{\n"State":"2"\n"IpAddr":" + firstRServerIP"\n}';
$.ajax({
method: 'POST',
url: 'https://Default_Generated_Alteon_BBI_Cert/config/SlbNewCfgEnhRealServerTable/R1',
//crossDomain: true,
data: dataString,
dataType: 'json',
success: function(responseData, textStatus, jqXHR) {
var value = responseData.someKey;
},
error: function (responseData, textStatus, errorThrown) {
alert('POST failed.');
}
});
});
});
For example, I fill the data '1.2.3.4' in the "firstRServerIP" part of the HTML form, and click the "Configure" button.
The POST request data should look like this:
{
"State":"2"
"IpAddr":"1.2.3.4"
}
Instead, I get:
{
"State":"2"
"IpAddr": " firstRServerIP"
}
What is wrong with my code?
A help will be appreciated.
Thanks.
You can correct it like that:
var dataString = '{\n"State":"2"\n"IpAddr":"' + firstRServerIP + '"\n}';
But I would suggest you to do that instead:
var dataString = JSON.stringify({
State: '2'
IpAddr: t.prev(".firstRServerIP").val()
})
;
You can also do the following if you want all the values of your form:
var dataString = $('#my-form').serialize();
in this case set the good name attributes in your inputs (ie. State and IpAddr) and use <form id="my-form">
I changed the format of your dataString object so that it's more readable and also used a different jQuery selector to get the value from the proper input field.
$('#configR1btn').click(function () {
var firstRServerIP = $("[name='firstRServerIP']").val();
var dataString = {
"State":"2",
"IpAddr": firstRServerIP
};
console.log(dataString);
This will output:
You can play with this JSFiddle. Open your console to see the result of the click.
Here is what you need. Please bear in mind that you do not have an element with class="firstRServerIP"; therefore $('.firstRServerIP').val() will always return undefined.
$('#configR1btn').click(function (){
var f = $('form').first(),
firstRServerIP = f.find(':text[name=firstRServerIP]').val(),
dataString = JSON.stringify({
State: "2",
IpAddr: firstRServerIP
});
dataString = dataString.replace(/([\{,])/g,'$1\n').replace('}','\n}');
$.ajax(...........
PROOF OF CONCEPT
$('#configR1btn').on('click',function() {
var f = $('form').first(),
firstRServerIP = f.find(':text[name=firstRServerIP]').val(),
dataString = JSON.stringify({
State: "2",
IpAddr: firstRServerIP
});
dataString = dataString.replace(/([\{,])/g,'$1\n').replace('}','\n}');
alert( dataString );
//ajax call here
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button id="configR1btn">Configure Server 1</button> <button id="configR2btn">Configure Server 2</button>
<form>
<section>
<header>
<h1>R Servers</h1>
</header>
Server 1 IP Address: <input type ="text" name="firstRServerIP"><br><br>
Server 1 Name: <input type ="text" name="firstRServerName"><br><br>
Server 2 IP Address: <input type ="text" name="secondRServerIP"><br><br>
Server 2 Name: <input type ="text" name="secondRServerName"><br><br>
</section>
</form>
Related
multiple similar questions out there but I cannot figure out this iTunes api call.
here is part of my server.js
app.post('/look', function(req,res){
var encoded = encodeURIComponent(req.body.search);var itunesURL = 'https://itunes.apple.com/search?';
var apiURL = itunesURL + 'term=' + encoded + '&country=US&media=music&limit=5';
console.log("inside it!");
var search_value = req.body.search.body;
$.ajax({
type: 'POST',
url: 'https://itunes.apple.com/search?',
data: { term: search_value },
// kind:'song', trackName: "Upside Down",
dataType:"json", //nodejs knows its trying to send me json
data:JSON.stringify({ // puts into a json obj
"search": $("#search").val(),
}),
success:(function(result){ // result is json from node
console.log("YESASASAS")
$.each(result[5].trackName, function(key,value){
$('#search_results').innerHTML += "<div> Track Name: </div><div> "+ result.trackName + "</div> <div> Artist Name: </div> <div> "+ result.artistName + "</div>"
});
}),
error:function(e)
{
console.log("EROROROROR")
},
});
});
And some of my ejs file where I just have an input box and submit button to call the ajax api call
<form action="/look" id = "doit" method="post">
<!-- search box -->
<input type="text" placeholder="Search.." id="search"><br>
<!-- search button -->
<input type="button" action="/look" onclick="myFunction()" id="search_button" value="search">
<!-- the div that will contain our search results -->
<div id="search_results" style="padding:5px;"> Search Results: </div>
</form>
<p id="demo"></p>
Would love another method to do this other than the button calling the /look endpoint
I am following some online ajax tutorials, the example is about calling a webapi using GET method, here is the script section on the page
<script type="text/javascript">
$(document).ready(function () {
var ulEmployees = $('#ulEmployees');
$('#btn').click(function () {
$.ajax({
type: 'GET',
url: "http://localhost:35468/api/employee",
dataType: 'json',
async: true,
success: function (data) {
ulEmployees.empty();
$.each(data, function (index, value) {
var fullName = value.FirstName + ' ' + value.LastName;
ulEmployees.append('<li>' + fullName + '</li>');
});
}
});
});
$('#btnClear').click(function () {
ulEmployees.empty();
});
});
</script>
It should render the emoloyee first and last name within a list item in the .
<div>
<input id="btn" type="button" value="Get All Employees" />
<input id="btnClear" type="button" value="Clear" />
<ul id="ulEmployees">
</ul>
</div>
the each function iterates the on the object but it displays undefined in the html
does anyone know a solution to this ?
Solved
the problem was because the field names FirstName and LastName was incorrect,
correct field names are firstName and lastName thats why the object was not populating them in a correct manner.
The code below sends the id of item to more.php to load more content. It works fine. Now to add some more features I need to send one more id to more.php through the same code.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.show_more',function(){
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type:'POST',
url:'more.php',
data:'id='+ID,
success:function(html){
$('#show_more_main'+ID).remove();
$('.display').append(html);
}
});
});
});
</script>
Suppose second id is var catid = '<?php echo $cat ?>'; how to send this catid through the same ajax code. data : {id : id, catid : catid} is something I should do but can't get how to deal in current situation when my data carries data:'id='+ID,.
your should look like. specify your data as an object:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.show_more', function () {
var ID = $(this).attr('id');
$('.show_more').hide();
$('.loding').show();
$.ajax({
type: 'POST',
url: 'more.php',
data: { id:ID, userid: userid },
success: function (html) {
$('#show_more_main' + ID).remove();
$('.display').append(html);
}
});
});
});
To retrieve multiple input's I suggest combining them in a Form:
first embed your inputs in an form with a submit button, you should also not use the same name twice because it won't work now, create unique names
<form action="GET" id="myForm">
<input id="string" type="text" name="string" />
<input id="string2" type="text" name="string" />
<input type="submit" value="Go" />
</form>
and write code to submit the ajax way
$('#myForm').submit(function(event) {
// Stop form from submitting normally
event.preventDefault();
var $form = $(this);
$.ajax({
type: "GET",
url: "retrieve.php",
data: $form.serialize(), //make it JSON
success: function() {
console.log("it worked");
}
});
});
I'm using xampp-control to emulate a local server. I have a html file and i'm trying with ajax to post some data into a json file. I can get the data from the json, but when I'm trying to post doesn't work.
here is the html
<!doctype html>
<html class="no-js" lang="">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="js/main.js"></script>
</head>
<body>
<h1> Family Perez</h1>
<form>
<label>Name</label><input type="input" id="name" name="name"></input>
<label>Last Name</label><input type="input" id="lastName" name="lastName"></input>
<input type="submit" id="submitBtn" value="Add family Member" name="submit"></input>
</form>
<div></div>
</body>
</html>
and here is the js
$(function(){
$('#submitBtn').click(function(e){
e.preventDefault();
var firtsName = $('#name').val();
var lastName = $('#lastName').val();
$.ajax({
type: 'post',
url:'http://localhost/angel/Jquery_advanced/ajax/family.json',
dataType: 'json',
async: false,
data: {name: firtsName, last: lastName},
success: function(newMember){
alert(newMember.name + ' ' + newMember.last + ' ' + 'has benn added');
}
})
});
$.ajax({
type: 'GET',
dataType: 'json',
url: 'http://localhost/angel/Jquery_advanced/ajax/family.json',
success: function(data) {
$.each(data, function(i, member){
$('div').append('<p>'+ member.name + ' ' + member.last +'</p>');
})
}
});
});
the file containing JSON data (http://localhost/angel/Jquery_advanced/ajax/family.json) looks like:
[{"name":"Juliseth","last":"Hernandez"},{"name":"Angel","last":"Perez"}]
The alert show undefined undefined has been added
Open debugging tool like Inspect Element or Firebug (Shortcut F12) in your preferred browser => Network => check ajax response,
If response is null or status code is 204 that means no data returned from the server, so that response data object would be undefined.
Another way,
$.ajax({
type: 'post',
url:'http://localhost/angel/Jquery_advanced/ajax/family.json',
dataType: 'json',
async: false,
data: {name: firtsName, last: lastName},
success: function(newMember){
alert("Response data : "+newMember);//check your response here
alert(newMember.name + ' ' + newMember.last + ' ' + 'has benn added');
//If newMember is array then your have to access it via index as Anik Islam Abhi suggested
}
})
Note : If you are directly requesting on json file then your idea behind post request to json file is wrong. For that you need to use server side language like Java, PHP, etc.
I believe that is because well... the POST data is undefined. Both of these are not actually getting any data:
var firtsName = $('#name').val();
var lastName = $('#lastName').val();
There is nothing in the .val()'s.
Your two input's have no values, and therefore nothing is being posted. Your get is adding content to the div, and it looks like you may be wanting to actually add the content to the inputs values?
I want to add comment using ajax. But i faced a problem, that ajax doesn't work. I put alert into success:, but it doesn't go into success function.
$(document).ready(function()
{
$("#comment_form").submit(function(e){
e.preventDefault();
var url_ = "http://127.0.0.1:8000/articles/addcomment/" + "1" + '/';
$.ajax({
url: url_,
type: "post",
success: function(result){
alert(result);
}
});
});
});
Here is my form:
<form action="/articles/addcomment/1/" method="post" id = "comment_form">
<input type = "text" name="commentText" id = "commentText">
<input type="submit" class="button" value="Добавить комментарий" id = "add_comment">
</form>
Console error:
jquery.min.js:5 POST 127.0.0.1:8000/articles/addcomment/1 403 (FORBIDDEN)