Getting wrong Form Data name when posting - javascript

I am trying to pass multiple parameters to a javascript function. When reviewing the post data I get incorrect data names.
HTML:
//Test function with button (HTML)
<button onClick='printList("projects",{"qid":1,"oid":3),getSampleEntity);'>Test getSampleEntity</button>
Javascript:
var getSampleEntity = function(oid, qid) {
//Returns Object
return $.ajax({
url: URL + 'downloadQuadrat_Organism.php',
type: 'POST',
data: { 'organismID': oid, 'quadratID': qid },
dataType: dataType
});
}
....
var printList = function(lid,options,get) {
var items = get(options);
var list = $("ul#"+lid);
list.empty();
items.success(function(data){
$.each(data, function(item,details) {
var ul = $('<ul/>');
ul.attr('id', lid+'_'+details.ID);
var li = $('<li/>')
.text(details.ID)
.appendTo(list);
ul.appendTo(list);
$.each(details,function(key,value) {
var li = $('<li/>')
.text(key+': '+value)
.appendTo(ul);
});
});
});
}
The resulting post data:
organismID[qid]:1
organismID[oid]:3
I see what is happening, but my question is how do I pass multiple parameters in to my printList() so that those parameters will be passed effectively to getSapleEntity()?

Try
var items = get(options.oid, options.qid);

Related

How to transfer a variable value from one function to anoter function?

Actually i want to transfer the value of my variable to another function in javascript. I tried many methods. In fact I search on stackoverflow but i didn't get correct output.
When i click on button show() function runs and form open
function show(){
var target = event.target || event.srcElement;
var id = target.id;
var x = document.getElementById(id).parentElement.id; // I am getting the value of 'x' when i alert it shows correct output
//alert(x);
$.ajax({
url: 'php/retrieve_characters.php',
type: 'post',
data: {},
success: function(response) {
var data = $.parseJSON(response);
if(data!='') {
$.each(data, function(i, item) {
$('#0').attr('src',data[0].charac);
$('#1').attr('src', data[1].charac);
});
}
}
})
}
Now when form opens i click a button which is in form and new function runs
function setimage(){
var target = event.target || event.srcElement;
var id = target.id;
$.ajax({
url: 'php/retrieve_characters.php',
type: 'post',
data: {},
success: function(response) {
var data = $.parseJSON(response);
if(data!='') {
$.each(data, function(i, item) {
var parent=document.getElementById("par1");
var child = parent.lastElementChild;
while (child) {
parent.removeChild(child);
child = parent.lastElementChild;
}
var li = document.createElement("img");
li.setAttribute("id", "char"+id);
li.setAttribute("src", data[id].charac);
li.setAttribute("onclick", "show()");
li.setAttribute("class", "imgs-thumbnail");
parent.appendChild(li);
});
}
}
})
}
In function setimage() i want the value of x which is in first function.
Remember one thing I don't want to call one function into another because in both functions i m retrieving data from database which will be messed up if both functions will be concatenated.

Retrieving data from myapifilms.com api

I am following a tutorial on YouTube showing how to get data from the myapifilms.com api and I am having trouble rendering the data to HTML. Currently my ajax call is working and the data is showing in the console. The problem I am having is getting the data to show on the page itself. I searched through the question already asked but had no luck. Here's my js code so far:
$(document).ready(function(){
$("#searchMovie").click(searchMovie);
var movieTitle = $("#movieTitle");
var table = $("#results");
var tbody = $("#results tbody"); //table.find("tbody");
function searchMovie() {
var title = movieTitle.val();
$.ajax({
url: "http://www.myapifilms.com/imdb/idIMDB?title="+ title +"&token= + token goes here +&format=json&language=en-us&aka=0&business=0&seasons=0&seasonYear=0&technical=0&filter=2&exactFilter=0&limit=1&forceYear=0&trailers=0&movieTrivia=0&awards=0&moviePhotos=0&movieVideos=0&actors=0&biography=0&uniqueName=0&filmography=0&bornAndDead=0&starSign=0&actorActress=0&actorTrivia=0&similarMovies=0&adultSearch=0&goofs=0&quotes=0&fullSize=0&companyCredits=0",
dataType: "jsonp",
success: renderMovies
})
function renderMovies(movies) {
console.log(movies);
tbody.empty();
for(var m in movies) {
var movie = movies[m];
var title = movie.title;
var plot = movie.simplePlot;
var posterUrl = movie.urlPoster;
var imdbUrl = movie.urlIMDB;
var tr = $("<tr>");
var titleTd = $("<td>").append(title);
var plotTd = $("<td>").append(plot);
tr.append(titleTd);
tr.append(plotTd);
tbody.append(tr);
}
}
}
});
I feel like I am so close but can't quite figure what I am missing. Again I was following a tutorial so if there's a better way to accomplish this goal I'm definitely open to suggestions.
Update:
I changed my code to this and I'm getting undefined in the browser. I changed the for loop to this
success: function (movies) {
console.log(movies);
tbody.empty();
for (var m in movies) {
$(".movies").append("<h3>"+ movies[m].title +"</h3>");
$(".movies").append("<h3>"+ movies[m].plot +"</h3>");
}
}
I figured out a solution, instead of using myapifilms, I used the tmdb api instead. Changing my code to this worked:
var url = 'http://api.themoviedb.org/3/',
mode = 'search/movie?query=',
input,
movieName,
key = 'myapikey';
//Function to make get request when button is clicked to search
$('button').click(function() {
var input = $('#movie').val(),
movieName = encodeURI(input);
$.ajax({
type: 'GET',
url: url + mode + input + key,
async: false,
jsonpCallback: 'testing',
contentType: 'application/json',
dataType: 'jsonp',
success: function(json) {
console.dir(json.results);
for (var i = 0; i < json.results.length; i++){
var result = json.results[i];
$(".moviesContainer").append('<div class="movies col-md-12">'+
'<img class="poster" src="http://image.tmdb.org/t/p/w500'+ result.poster_path +'" />'
+'<h3>'+ result.title +'</h3>'
+'<p><b>Overview: </b>'+ result.overview +'</p>'
+'<p><b>Release Date: </b>'+ result.release_date +'</p>'
+'</div>');
}
},
error: function(e) {
console.log(e.message);
}
});
});

passing array value to url in jquery ajax

i'm passing the array value to url like this
view code
from_multiselect('functio[]',$function,'','id=function')
baseurl/test/roles?id=1,2,3
this is my jquery
$("#role > option").remove();
var id = $('#function').val();
alert(id);
var str=new Array();
alert(id);
$.ajax({
type: "POST",
url: "test/roles?id="+id,
success: function(roles)
{
alert(roles);
$.each(roles,function(id,roles)
{
var opt = $('<option />');
opt.val(id);
opt.text(roles);
$('#role').append(opt);
});
}
});
});
});
Page give error when i pass the array value in url like Disallowed Key Characters.
Thank in advance
and then post this array like this:
$("#role > option").remove();
var id = $('#function').val();
var valArray = id.split(',');
var str=new Array();
alert(id);
$.ajax({
type: "POST",
url: "test/roles?id="+valArray,
success: function(roles)
{ alert(roles);
$.each(roles,function(id,roles)
{
var opt = $('<option />');
opt.val(id);
opt.text(roles);
$('#role').append(opt);
});
}
});
});
});
in the method add parameter to accept array.
This is CodeIgniter error.
So, to solve this, please go to
/application/config/config.php
AND
search for
$config['permitted_uri_chars']
change to:
$config['permitted_uri_chars'] = 'a-z 0-9~%\.\:_\+-,?&=';

getting value and label from an attribute using jquery

From the following a I need to get value from the data-autocomplete attribute (we have label and value in there but I need to collect only value) by using jQuery, please help.
North Chigwell Primary, 115 Allunga Road, CHIGWELL TAS 7011
This is code how I am trying :
callback: function (e) {
var a = $(e.currentTarget); // access the selected item
var address = $.trim(a.text());
// data-autocomplete
var moniker = $(a).attr("data-autocomplete");
$('#addressQas').val(address);
//$.ajax({
new FancyAjaxinator().jsonPost({
url: "/address/selectLine",
//dataType: "json",
data: {
"moniker": moniker,
"address": address
},
success: function (data) {
//console.log(data.responseObject);
var qasAddress = data.responseObject;
$('#address-line1').val(qasAddress.addressLine1);
if (qasAddress.state) {
$('#address-line2').val(qasAddress.addressLine2);
$('#address-townCity').val(qasAddress.suburb);
$('#address-state').val(qasAddress.state);
$('#address-state').parent().find('span.ui-selectmenu-text').text($("#address-state option[value=" + qasAddress.state + "]").text());
$('#address-postcode').val(qasAddress.postcode);
$('#address-line1').valid();
$('#address-townCity').valid();
$('#address-state').valid();
$('#address-postcode').valid();
}
$('#QASaddressField').hide();
$('.qasAddressFields').show();
//setFocus();
}
});
this.close;
return false;
}
Try
var a = $('a');// or the jQuery wrapper for the target a
var json =a.data('autocomplete');
console.log(json.value)
Demo: Fiddle
Using .attr()
var moniker = $(a).attr("data-autocomplete");
var json = JSON.parse(moniker);
console.log(json.value);

AJAX list update, get new elements and count

I have this HTML list
<ul id='usernameList'>
<li class='username'>John</li>
<li class='username'>Mark</li>
</ul>
and a form to add new names via AJAX, multiple add separated by commas. The response is a list with the names
[{name:David, newUser:yes}, {name:Sara, newUser:yes}, {name:Mark, newUser:no}]
I'm trying to insert this names sorted alphabetically in the list, like this example https://jsfiddle.net/VQu3S/7/
This is my AJAX submit
var form = $('#formUsername');
form.submit(function () {
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
dataType: "json",
beforeSend: function () {
//
},
success: function (data) {
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});
}
});
return false;
});
My question is, how I can update the value of listUsernames and numUsernames after adding an item?
You just need to update numUsernames at that point.
Add this where your comments are:
numUsernames = listUsernames.children().length;
listUsernames already has the updated children, as it's a reference to the parent element.
Edit: Re: your comment below:
This should probably work:
$(".username", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
return false; // stop `.each` loop.
}
});
First you don't need a double jQuery wrapping:
$(htmlUser).appendTo($(listUsernames));
listUsernames is already a jQuery object, so try:
$(htmlUser).appendTo(listUsernames);
And after every adding, you can update the numUsernames variable with:
numUsernames = listUsernames.children().length;
but this is not necessary because you can always access listUsernames.children().length in the success handler.
I update your JSFiddle
var listUsernames = $('#usernameList');
var numUsernames = listUsernames.children().length;
var data = [{name:'David', newUser:'yes'}, {name:'Sara', newUser:'yes'}, {name:'Mark', newUser:'no'}]
$.each(data, function(i, user) {
if(user.newUser == "yes"){
var htmlUser = "<li class='username'>" + user.name + "</li>";
var added = false;
$(".ingredient", listUsernames).each(function(){
if ($(this).text() > user.name) {
$(htmlUser).insertBefore($(this));
added = true;
}
});
if(!added)
$(htmlUser).appendTo($(listUsernames));
}
// HERE I DO alert('numUsernames')
// I get the same number of users before sending form
// How can I update here the value of listUsernames and numUsernames?
});

Categories

Resources