innerHTML.value not working? - javascript

I've been trying to write a JavaScript program that returns Wikipedia search results. A few days ago, I got it to the point where I could see the item being searched for, as confirmed by the alert() method, but now when I call the same alert() method it just returns "undefined":
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
I swear that this is exactly what I had while it was working, so there must be some subtle issue elsewhere. Any help is appreciated, complete code below:
HTML:
Random
<section>
<form>
<br>
<div class="divid">
<input type="text" value='' id="test" >
<button >Search</button>
</div>
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
JavaScript:
$(document).ready(function () {
$("button").click(function(e){
var search =document.getElementById("test").innerHTML.value;
alert(search);
});
var button = $('button');
var toSearch = '';
var searchUrl = "http://en.wikipedia.org/w/api.php"
var x="England";
input.autocomplete({
source: function (request, response) {
$.ajax({
url: searchUrl,
dataType: 'jsonp',
data: {
'action': "opensearch",
'format': "json",
'search': request.term
},
success: function (data) {
response(data[1]);
}
});
}
});
var playListURL = 'http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?';
$.getJSON(playListURL ,function(data) {
$.each(data.query.pages, function(i, item) {
//alert(item.title);
})
})
$.ajax({
//http://en.wikipedia.org/w/api.php?format=json&action=query&titles=India&prop=revisions&rvprop=content&callback=?
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: "Carl Sagan", format: 'json' },
dataType: 'jsonp',
success:
function (x) {
//alert( x.query.search[0].title);
}
});
})

Use .innerHTML to get the html in a DOM element
Use .value to get the value of an input, textarea, or other form input
.innerHTML.value is not a thing.

If you are using jQuery, try this:
var search = $("#test").html();
alert(search);

Related

Auto Complete Popup not working properly on cloned elements

I am unable to explain it properly,so i have added the image,please help me with this and please dont down vote.
Hi i am cloning the div on button click,and i want the auto complete box on the cloned elements also. on first element it is working fine but on cloned element the auto complete box(popup) is showing on 1st element but it should be shown on newly created textbox
following is the html code
<div class="repeatingSection">
<input id="Jobs[0].SampleType" name="Jobs[0].SampleType" type="text" class="form-control classSampleType" placeholder="Sample Name" required />
Add Job
following is the js code for cloning
function resetAttributeNames(section) {
var tags = section.find('input,button'), idx = section.index();
tags.each(function () {
var $this = $(this);
$.each(attrs, function (i, attr) {
var attr_val = $this.attr(attr);
if (attr_val) {
$this.attr(attr, attr_val.replace(/\[\d\]/,'['+(idx-5)+']'))
}
})
})
}
$('.addJob').click(function (e) {
e.preventDefault();
var lastRepeatingGroup = $('.repeatingSection').last();
var cloned = lastRepeatingGroup.clone(true)
cloned.find("input").val("");
cloned.insertAfter(lastRepeatingGroup);
resetAttributeNames(cloned)
});
and following is the code for auto completion
$(".classSampleType").click(function () {
var index = $(".classSampleType").index(this);
$("#Jobs\\["+index+"\\]\\.SampleType").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Lab/GetSampleType",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response(data);
}
})
},
messages: {
noResults: "", results: ""
}
});
});
For Reference i have added the image Reference Image
worked for me by making following changes
var cloned = lastRepeatingGroup.clone(true,false)
$(document).on('click','.classSampleType',function () {
var index = $(".classSampleType").index(this);
$("#Jobs\\["+index+"\\]\\.SampleType").autocomplete({
source: function (request, response) {
$.ajax({
url: "/Lab/GetSampleType",
type: "POST",
dataType: "json",
data: { Prefix: request.term },
success: function (data) {
response(data);
}
})
},
messages: {
noResults: "", results: ""
}
});
});

No data receive in Jquery from php json_encode

I need help for my code as i have been browsing the internet looking for the answer for my problem but still can get the answer that can solve my problem. I am kind of new using AJAX. I want to display data from json_encode in php file to my AJAX so that the AJAX can pass it to the textbox in the HTML.
My problem is Json_encode in php file have data from the query in json format but when i pass it to ajax success, function(users) is empty. Console.log also empty array. I have tried use JSON.parse but still i got something wrong in my code as the users itself is empty. Please any help would be much appreciated. Thank you.
car_detail.js
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
cache: false,
data: { car_rent_id: this.car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
car_detail.php
$car_rent_id = $_GET['car_rent_id'];
$query = mysql_query("SELECT c.car_name, c.car_type, c.car_colour,
c.plate_no, c.rate_car_hour, c.rate_car_day, c.car_status,
r.pickup_location
FROM car_rent c
JOIN rental r ON c.car_rent_id=r.car_rent_id
WHERE c.car_rent_id = $car_rent_id");
$users = array();
while($r = mysql_fetch_array($query)){
$user = array(
"car_name" => $r['car_name'],
"car_type" => $r['car_type'],
"car_colour" => $r['car_colour'],
"plate_no" => $r['plate_no'],
"rate_car_hour" => $r['rate_car_hour'],
"rate_car_day" => $r['rate_car_day'],
"car_status" => $r['car_status'],
"pickup_location" => $r['pickup_location']
);
$users[] = $user;
// print_r($r);die;
}
print_r(json_encode($users)); //[{"car_name":"Saga","car_type":"Proton","car_colour":"Merah","plate_no":"WA2920C","rate_car_hour":"8","rate_car_day":"0","car_status":"","pickup_location":""}]
car_detail.html
<label>ID:</label>
<input type="text" name="car_rent_id" id="car_rent_id"><br>
<label>Car Name:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_name" id="car_name" class = "form-control" placeholder = "Car Name" aria-describedby = "sizing-addon3">
</div></br>
<label>Car Type:</label>
<div class = "input-group input-group-sm">
<span class = "input-group-addon" id="sizing-addon3"></span>
<input type = "text" name="car_type" id="car_type" class = "form-control" placeholder = "Car Type" aria-describedby = "sizing-addon3">
</div></br>
Remove this in this.car_rent_id1 and cache: false this works with HEAD and GET, in your AJAX you are using POST but in your PHP you use $_GET. And car_rent_id is not defined, your function $_GET(q,s) requires two parameters and only one is passed.
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id'); // missing parameter
car_rent_id.value = car_rent_id1; // where was this declared?
$.ajax({
type: 'POST',
url: "http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
}
});
});
You can also use $.post(), post is just a shorthand for $.ajax()
$(document).ready(function() {
function $_GET(q,s) {
s = (s) ? s : window.location.search;
var re = new RegExp('&'+q+'=([^&]*)','i');
return (s=s.replace(/^\?/,'&').match(re)) ?s=s[1] :s='';
}
var car_rent_id1 = $_GET('car_rent_id');
car_rent_id.value = car_rent_id1;
$.post('http://localhost/ProjekCordova/mobile_Rentacar/www/php/car_detail.php', { car_rent_id: car_rent_id1 }, function (users) {
console.log(users);
$('#car_name').val(users.car_name);
});
});
and in your PHP change
$car_rent_id = $_GET['car_rent_id'];
to
$car_rent_id = $_POST['car_rent_id'];
Here is a code skeleton using .done/.fail/.always
<script
src="https://code.jquery.com/jquery-1.12.4.min.js"
integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ="
crossorigin="anonymous"></script>
<script>
$(function(){
$.ajax({
url: 'theurl',
dataType: 'json',
cache: false
}).done(function(data){
console.log(data);
}).fail(function(data){
console.log(data);
}).always(function(data){
console.log(data);
});
});
</script>
I've adapted your code, so you can see the error, replace the ajax call with this one
<script>
$.ajax({
url: "theurl",
dataType: "json",
data: { car_rent_id: car_rent_id1 },
success: function(users) {
console.log(users);
$('#car_name').val(users.car_name);
},
error: function(data) {
console.log(data);
alert("I failed, even though the server is giving a 200 response header, I can't read your json.");
}
});
</script>
A couple of recommendations on this, I would follow jQuery API to try an see where the request is failing http://api.jquery.com/jquery.ajax/. Also, I would access the ids for the input fileds with jQuery. e.g.: $("#theID").val().

Access Wikipedia API JSON data in jQuery

$('#searchButton').click(function(){
var searchInput = "";
searchInput = document.getElementById('test');
if(searchInput.value !== ""){
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch='+searchInput+'&utf8=', function(json){
alert(json.query.search[0].title);
});
}
});
I'm confused on why the Json doesnt seem to be loading into the page. It seems like the whole operation stops at the url as even if i enter a string into the alert it doesn't run either...
You got this error because CORS is not enabled for the origin from which you are calling the mediawiki and you can check the same more about here.
https://www.mediawiki.org/wiki/Manual:CORS
You can use jQuery jsonp request as below with dataType: 'jsonp' instead.
Working snippet:
$(document).ready(function() {
$('#searchButton').click(function(){
var searchInput = "";
searchInput = document.getElementById('test');
if(searchInput.value !== ""){
$.ajax( {
url: 'https://en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: searchInput.value
},
dataType: 'jsonp'
} ).done( function ( json ) {
alert(json.query.search[0].title);
} );
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" />
<input type="button" id="searchButton" value="Search" />

AutoComplete in jQuery with dynamically added elements

My requirement is to show few options when user input some characters (minimum 3) in one of input field which might be added dynamically too.
I can not load data at page loading at beginning because data is huge. There is an ajax call to get that filtered data.
The issue what I am getting is Expected identifier error on page loading at line# 2. So, could you please tell what is wrong with the below code?
$(document).on('keydown.autocomplete', 'input.searchInput', function() {
source: function (request, response) { // Line # 2
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getNames.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
How about using another approach: initialize the autocomplete when you create the input:
$(function() {
// settings for each autocomplete
var autocompleteOptions = {
minLength: 3,
source: function(request, response) {
$.ajax({
type: "GET",
url: "getNames.html",
data: { name: request.term },
success: function(data) {
response(data);
}
});
}
};
// dynamically create an input and initialize autocomplete on it
function addInput() {
var $input = $("<input>", {
name: "search",
"class": "searchInput",
maxlength: "20"
});
$input
.appendTo("form#myForm")
.focus()
.autocomplete(autocompleteOptions);
};
// initialize autocomplete on first input
$("input.searchInput").autocomplete(autocompleteOptions);
$("input#addButton").click(addInput);
});
<form id="myForm" name="myForm" method="post">
<input id="addButton" type="button" value="Add an input" />
<input name="search" class="searchInput" maxlength="20" />
</form>
jsFiddle with AJAX
The method where I am adding new input field there writing below code.
function addInput(){
// Code to append new input filed next to existing one.
$("table").find('input[id=clientId]:last').autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
}
And some where in other js which will be used to all other (static) input fields below code is used.
jQuery("input.searchInput").autocomplete({
source: function (request, response) {
var id = this.element[0].id;
var val = $("#"+id).val();
$.ajax({
type : 'Get',
url: 'getName.html?name=' + val,
success: function(data) {
var id = $(this).attr('id');
$(this).removeClass('ui-autocomplete-loading');
response(data);
},
error: function(data) {
$('#'+id).removeClass('ui-autocomplete-loading');
}
});
},
minLength: 3
});
Note :- For any autocomplete requests in dynamically added input fields, AutoComplete code of addInput() function will be called.
Thanks to #Salman and this post Enabling jQuery Autocomplete on dynamically created input fields to give me an idea.
Try this.
$("#autocompleteElement").autocomplete({
source:function (data, response) {
$ajax({
url:'your/url?name='+data.term,
success:function(data){
response(data);
}
})
}
});
This code based on jquery UI autocomplete.

Get response code and parse to message via jQuery ajax

I have this structure:
HTML:
<input type="submit" name="_ninja_forms_field_7" class="ninja-forms-field popup-submit" id="ninja_forms_field_7" value="" rel="7">
JS:
$('#ninja_forms_field_7').click(function () {
var name = $('#ninja_forms_field_6').val();
var surname = $('#ninja_forms_field_6').val();
var emailAddress = $('#ninja_forms_field_8').val();
var eCommerceSiteUrl = $('#ninja_forms_field_9').val();
var post_datas = emailAddress = +emailAddress+ & name = +name+ & surname = +surname+ & eCommerceSiteUrl = +eCommerceSiteUrl;
$.ajax({
type: 'POST',
url: 'myserviceaddress',
data: post_datas,
success: function (answer) {
console.log(answer);
}
});
});
It working good. But I want, If service response code 0, parse a text in page.
How can I do it?
Just add the error: function() lines you see below beneath success:
$.ajax({
type: 'POST',
url: 'myserviceaddress',
data: post_datas,
success: function (answer) {
console.log(answer);
},
error: function (jqXHR, textStatus, errorThrown) {
$("#result_div").html("textStatus");
}
});
Also, make sure you create a <div id="result_div"></div> so that the JQuery has a place to put the result in.

Categories

Resources