Access Wikipedia API JSON data in jQuery - javascript

$('#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" />

Related

Different Form Submit Actions for Different Forms

Super basic javascript question incoming...
I have two forms, one for uploading a file and one for providing text. I want to have a unique submit action for each of these forms. For the former, to upload the file, and for the latter, to serialize the form into JSON and POST it.
To attempt to accomplish this, I have one function called submit and another called submit2. The file upload form, which invokes submit works just fine.
The problem is with the second form, which invokes submit2. In particular, when I load the page, I get the following errors:
Query.Deferred exception: undefined is not a function (near '...$('form').submit2...').
TypeError: undefined is not a function (near '...$('form').submit2...')
Here's my HTML.
Upload an image
<form method="POST" enctype="multipart/form-data" action="upload">
<input id="img" name="file" type="file" accept=".jpeg,.jpg,.png">
<input class="btn btn-primary" type="submit" value="Submit">
</form>
Paste a URL
<form method="POST" name="urlForm" onclick="submit2()">
<input id="imgurl" name="url" type="text">
<input class="btn btn-primary" value="Submit">
</form>
And here's my javascript.
function ConvertFormToJSON(form){
var array = jQuery(form).serializeArray();
var json = {};
console.log(array)
jQuery.each(array, function() {
json[this.name] = this.value || '';
});
return json;
}
$(document).ready(function () {
var $status = $('.status');
$('#img').change(function (event) {
var obj = $(this)[0];
console.log(obj)
$status.html('');
if (obj.files && obj.files[0]) {
console.log(obj.files)
var fileReader = new FileReader();
fileReader.onload = function (event) {
$('.img-area').html(
`<img class='loaded-img' src='${event.target.result}' style="width:500px;height:500px;"/>`
);
}
fileReader.readAsDataURL(obj.files[0]);
}
});
$('#imgurl').change(function (event) {
var obj = $('#imgurl').val()
console.log(obj)
$('.img-area').html(
`<img class='loaded-img' src='${obj}' style="width:500px;height:500px;"/>`
);
});
$('form').submit(function (event) {
event.preventDefault();
var imageData = new FormData($(this)[0]);
console.log(imageData)
$status.html(
`<span class='eval'>Evaluating...</span>`
);
$.ajax({
url: 'some_api_endpoint',
type: 'POST',
processData: false,
contentType: false,
dataType: 'json',
data: imageData,
success: function (responseData) {
console.log(responseData)
if (responseData.error != null) {
$status.html(
`<span class='result failure'>Failed</span>`
);
} else {
$status.html(
`<span class='result success'>${responseData.message}</span>`
);
}
},
error: function () {
$status.html(
`<span class='eval'>Something went wrong, try again later.</span>`
);
}
});
});
$('form').submit2(function (event) {
event.preventDefault();
var json = ConvertFormToJSON($('form'))
console.log(json)
$status.html(
`<span class='eval'>Evaluating...</span>`
);
$.ajax({
url: 'some_api_endpoint',
type: 'POST',
processData: false,
contentType: 'application/json',
dataType: 'json',
data: JSON.stringify(json),
success: function (responseData) {
console.log(responseData)
if (responseData.error != null) {
$status.html(
`<span class='result failure'>Failed</span>`
);
} else {
$status.html(
`<span class='result success'>${responseData.message}</span>`
);
}
},
error: function () {
$status.html(
`<span class='eval'>Something went wrong, try again later.</span>`
);
}
});
});
});
Edit: Added the ConvertFormToJSON function for completeness, although I think that's orthogonal to the issue I'm facing.
Problem in there Jquery Object dont have submit2 method and when you want to access submit2 method this is return undefined and when call this is return undefined is not function.

Rendering the response of a jquery POST request in NodeJs

Functionality:
The functionality of this code is to update user details on the user Profile-page.
Code:
Profile.ejs
<script>
(function() {
function toJSONString( form ) {
var obj = {};
var elements = form.querySelectorAll( "input, select, textarea" );
for( var i = 0; i < elements.length; ++i ) {
var element = elements[i];
var name = element.name;
var value = element.value;
if( name ) {
obj[ name ] = value;
}
}
return JSON.stringify( obj );
}
document.addEventListener( "DOMContentLoaded", function() {
var form = document.getElementById( "test" );
form.addEventListener( "submit", function( e ) {
e.preventDefault();
var json = toJSONString( this );
//alert(json);
$.ajax({
type: "POST",
url: "/profile",
data: json,
success: function(){},
dataType: "json",
contentType : "application/json"
});
}, false);
});
})();
</script>
<div id="res">
<h4>
<%= status %>
</h4>
</div>
<form id="test" action="/profile" method="post">
<input type="text" name="name" id="name" value=""/>
<input type="text" name="about" id="about" value=""/>
<input type="text" name="hobbies" id="hobbies" value=""/>
<input type="submit" value="send" class="btn btn-primary btn-block"/>
</form>
Index.js
router.get('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:''});
});
router.post('/profile', loggedin, function(req, res, next) {
res.render('profile', {status:'Changes Updated'});
});
Expected-Outcome:
Once the post request with all the details are sent, the <div id="res"> should contain the text Changes Updated.
Actual-Outcome:
Once the post request is sent, 200 OK response is observed and the response packet has the text Changes Updated. However, the browser does not reflect it. The new response received is not rendered.
Kindly assist in resolving this issue, as I'm fairly new to this( And the entire code is put together from a lot of places ). Also, any extra information, or good reads on the subject would be much appreciated
You will need to use the jQuery html attribute to insert the desired results into the div. ejs is used for creating templates before your page has loaded, and not for inserting ajax data after the page has loaded.
Try this:
$(document).ready(function() { //the jQuery equivalent
var form = $('#test');
form.on('submit', function(e) {
e.preventDefault();
var json = toJSONString(this);
$.ajax({
type: "POST",
url: "/profile",
data: json,
success: function(data) {
console.log(data);
$('#res').html(data); //insert "data" into the inner html of the div
},
dataType: "json",
contentType : "application/json"
});
}, false);
});
});

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().

innerHTML.value not working?

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);

Autocomplete not working when added space

In my project, I am trying to create a autocomplete effect using the following plugin:
Devbridge jQuery Autocomplete
This plugin is working fine until I don't add space into my textbox (after adding a word). and when I just delete the entered word using backspace then the autocomplete is showing the previous list which should have shown before.
PS: Every time I am passing the full text of the text field to server through ajax call which is necessary in my application.
Here is my code:
JS Fiddle (not working because of ajax url)
JS
$(function () {
var result = $('#result');
var contents = {
value: "",
data: ""
};
/* Ajax call */
result.keydown(function (event) {
if (!event.shiftKey) {
var sugData;
var text = result.val(); //.split(" ").pop();
//console.log(text);
/* Send the data using post and put the results in a div */
$.ajax({
url: "http://localhost:9999/projects/1/autocomplete/suggestions",
type: "POST",
data: "drqlFragment=" + text, // + " ",
//data: "drqlFragment=when node_database_property ",
async: false,
cache: false,
headers: {
accept: "application/json",
contentType: "application/x-www-form-urlencoded"
},
contentType: "application/x-www-form-urlencoded",
processData: true,
success: function (data, textStatus, jqXHR) {
var resData = data.suggestions;
//console.dir(resData);
for (var i = 0; i < resData.length; i++) {
resData[i].value = resData[i].keyword;
}
sugData = resData;
//console.dir(sugData);
},
error: function (response) {
//console.dir(response);
$("#result").val('there is error while submit');
}
});
console.dir(sugData);
$('#result').autocomplete({
lookup: sugData
});
}
});
});
HTML
<form id="foo">
<textarea id="result" rows="4" cols="50"></textarea>
<input type="submit" value="Send" />
</form>
Sorry, I can't provide you the json data because it is being modified by the server whenever I press a key. (So, actually it is an object variable returning by the server on ajax call).

Categories

Resources