This jquery code is displaying json data inside span html input elements. But i failed to implement for loop to display array objects of movie genres.
Right now it's just 0 index of array but i wanna display all..
$("#txt-movie-genres").val(json.genres[0].name)
$(document).ready(function() {
var url = 'http://api.themoviedb.org/3/',
mode = 'movie/',
movie_id,
key = '?api_key=e9dfeccf734a61b9a52d9d7660f0d0a1';
$('button').click(function() {
var input = $('#movie').val(),
movie_id = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + movie_id + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
// grab the span elements by ID and replace their text with the json text
// $("#movie-title").text(json.title);
$("#txt-movie-title").val(json.title)
$("#txt-movie-genres").val(json.genres[0].name)
console.dir(json);
},
error: function(e) {
console.log(e.message);
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="movie" type="text" /><button>Search</button>
<h1>Movie info:</h1>
<p>Movie title: <span id="span-movie-title"></span> </p>
<div class="input-group">
<input id="txt-movie-title" name="title" type="text" />
<div class="input-group-addon">
Movie Name
</div>
</div>
<div class="input-group">
<input id="txt-movie-genres" name="genres" type="text" />
<div class="input-group-addon">
Movie Genre
</div>
</div>
Something like:
$("#txt-movie-genres").val(json.genres.map(g => g.name).join(",");
Which will create an array of names and then join them into a comma delimited string.
You could covert json.genres arrays to array of genres names using .map() methidand then join them to comma separated string using join():
var names = $.map(json.genres, function() { return this.name }).join(",");
Related
Currently, I get the value of an id and pass it in my data object to be sent to the server.
const field_value = $('#id_field').val();
const scores_value = $('#id_scores').val();
$.ajax({
data: {'Fields':field_value, 'Scores': scores_value},
});
I want to achieve this dynamically in case I add more forms so it can automatically update without me having to change any code.
I tried using the jquery each method to access the class.
$(".class").each(function() {
const get_updated_value = $(this).val();
});
This dynamically gets the values, but I am having trouble passing the returned values to the data object.
If each element with '.class' has still an own id you could take these id's as the keys of the data object:
var updated_values = {};
$(".class").each(function() {
updated_values[$(this).attr('id')] = $(this).val();
});
$.ajax({
data: updated_values,
});
Working example:
function update() {
var updated_values = {};
$(".input").each(function() {
updated_values[$(this).attr('id')] = $(this).val();
});
console.log(updated_values);
}
input {
display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<input type="text" placeholder="My task" id="field" class="input">
<input type="text" placeholder="My date" id="scores" class="input">
<input type="text" placeholder="My time" id="something_new" class="input">
<input type="button" value="Update" onclick=update() id="save">
</div>
This form has a text input for each day of the week, as well as an "Add Another" button to create more inputs under each day. The submissions go through but only the first value that's entered into the input gets posted to the Spreadsheet's cell.
So for example, if the user has multiple entries entered in for SUNDAY_NOTES, like so:
SUNDAY_NOTES = "Late."
SUNDAY_NOTES = "This thing."
SUNDAY_NOTES = "Something."
... then only "Late" ends up in the spreadsheet's cell with my current code. Ideally, I'd like to have a comma-separated or linebreak-separated string in the cell: ("Late., This thing., Something."). I'm using the following code (which I copied) to post the submissions to a Google Spreadsheet.
<form method="post" id="timesheet" >
<input type="text" name="SUNDAY_NOTES">
<input type="text" name="SUNDAY_NOTES">
// user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES">
// and so forth
<input type="submit" id="submit" />
</form>
<script>
var $form = $('form#timesheet'),
url = 'https://script.google.com/macros/s/abcd123456789/exec'
$('#submit').on('click', function(e) {
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: $form.serializeArray()
}).success(
console.log('success')
);
})
</script>
(This question doesn't accurately describe the use-case of my form, I just overly-simplified it for posting purposes)
to have an array of inputs values with same name, add [] after the name like : name="SUNDAY_NOTES[]" ,
so replace <input type="text" name="SUNDAY_NOTES"> with <input type="text" name="SUNDAY_NOTES[]">
then join the array values with a comma with
data : $form.serializeArray().map((e) => { return e.value}).join(',')
$form.serializeArray() will have an array of objects, that's why it's useful to use .map() to retun an array of values to be able to join them.
$(document).ready(function() {
var $form = $('form#timesheet');
$form.submit(function(e) {
e.preventDefault();
var myValues = $form.serializeArray().map((e) => {
return e.value
}).join(',');
console.log(myValues);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form method="post" id="timesheet">
<input type="text" name="SUNDAY_NOTES[]">
<input type="text" name="SUNDAY_NOTES[]"> // user can click a button to keep adding more SUNDAY_NOTES fields
<input type="text" name="MONDAY_NOTES[]"> // and so forth
<input type="submit" id="submit" />
</form>
EDIT :
in order to keep the structure as is ( key, value pairs ), create a function group that loops through an array and add the values to the key
function group(arr){
var tempArr = [];
arr.forEach(function(e){
if(!tempArr[e.name]) tempArr[e.name] = e.value
else tempArr[e.name] += ',' + e.value
});
return tempArr;
}
$('#submit').on('click', function(e) {
var jqxhr = $.ajax({
url: url,
method: "GET",
dataType: "json",
data: group($form.serializeArray())
// rest of your code
here's a fiddle : https://jsfiddle.net/cwgL6L0L/29/ ( check the console )
I am not a techie in terms of html or ajax or javascript. But i had to develop a script. My problem is "hide" is not working in my ajax.
I have 2 text field that gives the search result. I want to hide the search suggestion (in "ul" tag) of one when the user searches in the other.
Below given is the javascript and html
function autocomplet() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#country_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#country_list_id').show();
$('#country_list_id').html(data);
}
});
} else {
$('#country_list_id').hide();
}
document.getElementById('house_list_id').style.display = 'none';
}
function autocomplet_house() {
var min_length = 0; // min caracters to display the autocomplete
var keyword = $('#house_id').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh_house.php',
type: 'POST',
data: {keyword:keyword},
success:function(data){
$('#house_list_id').show();
$('#house_list_id').html(data);
}
});
} else {
$('#house_list_id').hide();
}
document.getElementById('country_list_id').style.display = 'none';
}
<form>
<div class="label_div">Search Name:  </div>
<div class="input_container">
<input type="text" id="country_id" name="country_name" autocomplete="off" onkeyup="autocomplet()">
<ul id="country_list_id"></ul>
</div>
<div class="label_div">Search House:  </div>
<div class="input_container">
<input type="text" id="house_id" name="house_name" autocomplete="off" onkeyup="autocomplet_house()">
<ul id="house_list_id"></ul>
</div>
</form>
It seems like you have a hide-condition, that is never met:
var min_length = 0;
if (keyword.length >= min_length){
/* keyword is always zero length or greater */
} else {
/* will never reach here */
}
Besides, I think you want to hide 'the other list', when showing the 'current list' ... Try changing your ajax-success like this:
success:function(data){
$('#country_list_id').html(data).show();
$('#house_list_id').hide();
}
success:function(data){
$('#house_list_id').html(data).show();
$('#country_list_id').hide();
}
Ok ... I have been thinking, and have rearranged everything.
Try this:
<script>
function autocomplet(Elm){
var Name = Elm.attr('name');
var Word = Elm.val();
var ListA = $('#'+Name+'_list_id');
var ListB = Elm.parents('form').find('ul').not(ListA).hide();
var min = 0; // min caracters to display the autocomplete
if( Word.length >= min ){
$.ajax({
url: 'ajax_refresh_'+Name+'.php',
type: 'POST',
data: {Word:Word},
success:function(data){
ListA.empty().html(data).show();
}
});
}
}
</script>
<form>
<div class="label_div">Search Name: </div>
<div class="input_container">
<input type="text" name="country" autocomplete="off" onkeyup="autocomplet($(this));">
<ul id="country_list_id"></ul>
</div>
<div class="label_div">Search House: </div>
<div class="input_container">
<input type="text" name="house" autocomplete="off" onkeyup="autocomplet($(this));">
<ul id="house_list_id"></ul>
</div>
</form>
Thanks a lot OLA, you gave me an idea to reduce the redundancy of the code. I've Cleared my browsing history and it worked.
I am stuck in passing the multiple value through AJAX call in Codeigniter.
My View is :
<script>
$( document ).ready(function() {
var current_id = 0;
$('#btn').click(function(){
nextElement($('#Outer_00'));
})
function nextElement(element){
var newElement = element.clone()
.find("input:text").val("").end();
var id = current_id+1;
current_id = id;
if(id <10)id = "0"+id;
$('input', newElement).attr("id", id );
newElement.appendTo($("#elements"));
if($('#elements').find('div').length=='5')
{
$('#btn').prop('disabled',true);
}
}
$('#exercises').on('click', '.remove', function() {
if($('#elements').find('div').length<'6')
{
$('#btn').prop('disabled',false);
}
if($('#elements').find('div').length=='1')
{
$('.remove').addAttr("disabled",true);
}
$(this).parent().remove();
return false; //prevent form submission
});
});
</script>
/******************************
<script>
var base_url = '<?=base_url()?>';
$(document).ready(function()
{
$('#Edit').click(function()
{
$('#Name').removeAttr("disabled");
});
$('#Add').click(function()
{
$('#Name').attr("disabled","disabled");
$('#Phone').attr("disabled","disabled");
$('#email').attr("disabled","disabled");
$('#CurrentlyLocated').attr("disabled","disabled");
$('#KeySkills').attr("disabled","disabled");
//var queryString = $('#form1').serialize();
$.ajax({
url: '<?php echo site_url('PutArtistProfile_c/formDataSubmit');?>',
type : 'POST', //the way you want to send datas to your URL
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
success : function(data)
{ //probably this request will return anything, it'll be put in var "data"
$('body').html(data);
}
});
});
});
</script>
<p>
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" id="00" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>
<div id="count"></div>
<input type="button" id="btn" value="Add Audio"></button>
</p>
My Controller is :
public function formDataSubmit()
{
$queryAudio1 = $this->input->post('Audio1');
$queryAudio2 = $this->input->post('Audio2');
$queryAudio3 = $this->input->post('Audio3');
$queryAudio4 = $this->input->post('Audio4');
$queryAudio5 = $this->input->post('Audio5');
}
How can I pass Multiple Values of text box? The above code is passing the values to the controller. But on clicking 'x' Button the value of text box is been getting deleted, but the id of the textbox is getting Incremented, Thus I am not able to pass the further values of textbox to controller via AJAX. Please help me over here.
instead of doing :
data: {Name:$("#Name").val(), Phone: $("#Phone").val(), email: $("#email").val(),
birthday: $("#birthday").val(), bornIn: $("#bornIn").val(),
CurrentlyLocated: $("#CurrentlyLocated").val(), KeySkills: $("#KeySkills").val(),
Audio1: $("#00").val(), Audio2: $("#01").val(), Audio3: $("#02").val(),Audio4: $("#03").val(), Audio5: $("#04").val(),
},
You can do as
data:$("#Form_id").serialize(); // all form data will be passed to controller as Post data.
If you have a remove button then getting the value by id may result in a js error, Why don't you make use of html element array:
<div id="elements">
<div id="Outer_00">
Audio: <input type="text" name="audio[]" value="">
<input type="button" class="remove" value="x"></button>
</div>
</div>
IT is very simple:
Consider you want to pass: user name, surname, and country. These are
three input boxes then:
using Jquery do so:
Javascript side
$.post("url",{name:name,surname:surname,country:country},
function(data){
console.log("Query success");
});
In your Model or controller where your Query will be handled
$name=$this->input->post("name");
$surname=$this->input->post("surname");
$country=$this->input->post("country");
in your case just pass parameters that YOU need. I use codignitter and
this method works fine!
I have a timeline that loops posts and allows for users to comment on each post. After entering the comment it is meant to prepend to the post in which the comment is made. Problem now is that it prepends to the very first post. This means that this prepend action is not following the loop.
Add comment function
<!--Function to add comment-->
var msg2 = $("#feeds li #comment-form #comment");
var msg = $("#feeds #comment-form #hidden");
var textarea = $('#comment');
$('.comment-btn').on("click",function(event) {
var one = $(this).parent().find(msg2).val();
var two = $(this).parent().find(msg).val();
$.ajax({
type: "POST",
url: "add_comment.php",
data: "msg2="+ one +"&msg=" + two,
msg: "Checking...",
success: function(data){
$('#feeds li #comment-form').parent().find('textarea').val("");
updateComment();
}
});
});
And this is the updateComment function
<!--Function to update the comment feed-->
function updateComment(){
var id = 0;
id = $('#feeds li #other-comments').attr('data-id');
$.ajax({
'url' : 'comment.php',
'type' : 'POST',
'data' : {
'latest_comment_time' : id
},
success : function(data){
if(id != 0){
$('#sub-comments').prepend(data);
}
}
})
}
Edited
html
<div id='comments'>
<form action='' id="comment-form" method="post">
<textarea id="comment" name="comment" placeholder="Add comment..."></textarea>
<input type="button" class='comment-btn' value='Send'>
<input type="hidden" name="msg" value="<?=$item['msg_id']?>" id="hidden">
</form>
<div id="sub-comments">
<?php require('comment.php');?>
</div>
</div>
Note: the 'feeds li' is for the looping post.