I used some sample code from the Wiki API docs but when I enter a search item, nothing happens. No errors in the console, just nothing. The URL itself works if I enter it into a browser so I think something with the code is not passing in the proper value. Is there an issue with how I'm calling the API? Below is the relevant code:
$(document).ready(function(){
$('#search-submit').click(function() {
getWiki($('#searchVal').val());
});
/*add code for get lucky function*/
});
function getWiki(searchParam) {
$.ajax( {
url: 'http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page='+searchParam+'&callback=?',
dataType: 'json',
type: 'POST',
headers: { 'Api-User-Agent': 'Example/1.0' },
success: function(data) {
var result = data;
pageTitle = result.title;
$(".search-box").html(pageTitle);
}
});
};
Here is the HTML:
<body>
<div class="container">
<div class="col-lg-12 header">
<h1>Search Wiki</h1>
</div>
<div class="row search-box">
<div class="col-lg-10">
<input placeholder=" Search" class="input" type="text" id="searchVal" name="searchVal"/></div>
<div class="col-lg-2"><button type="submit" id="search-submit" name="search-submit" class="btn-default">
<i class="fa fa-search fa-2x"></i>
</button></div>
</div>
<div class="row button-box text-center">
<div class="col-lg-12">
<button type="button" class="btn btn-primary" id="random">I'm Feeling Lucky</button></div>
</div>
</div>
</body>
The returned JSON has a parse property before the result, so it has to be data.parse.title to get the title etc.
$(document).ready(function() {
$('#search-submit').click(function() {
getWiki($('#searchVal').val());
});
/*add code for get lucky function*/
});
function getWiki(searchParam) {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=' + searchParam + '&callback=?',
dataType: 'json',
type: 'POST',
headers: {
'Api-User-Agent': 'Example/1.0'
},
success: function(data) {
var result = data.parse;
var pageTitle = result.title;
$(".search-box").html('The title is : ' + pageTitle);
}
});
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Search for something : <input id="searchVal"><button id="search-submit">Search</button>
<br /><br /><br />
<div class="search-box"></div>
Related
I want to use this list because before submitting I might remove a few and add more files to the list. When I use the input to get the files it has only the last imported files, not the previous ones but I want to preserve the previous ones as well cause I want to add or subtract images or pdf files to list before submission.
HTML Code:
//<form method="POST" id="medical_record_form" enctype="multipart/form-data" '>
<div class="card">
<div class="card-body">
<div class="row form-row">
<div class="col-12 col-md-12">
<div class="form-group">
<label>Title</label>
<input type="text" name="title" id="title" class="form-control">
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<label>Medical Documents</label>
<div class="upload-img">
<div class="change-photo-btn">
<span><i class="fa fa-upload"></i> Upload File</span>
<input id="medical_documents" name="medical_documents"
type="file" multiple accept="image/*,.pdf"
onchange="readURL(this);" class="upload">
</div>
<small class="form-text text-muted">All Image Types Are Allowed, Plus
PDF Files</small>
</div>
</div>
<div class="upload-wrap" id="documets_wrapper">
<!-- the images preview goes here which is handled by javascript -->
</div>
</div>
</div>
</div>
</div>
<div class="submit-section">
<button type="submit" id="medical_submit_button" class="btn btn-primary submit-btn">Save
Changes</button>
</div>
</form>
Javascript code:
'''
// Fields
const medicalForm = document.getElementById('medical_record_form');
const title = document.getElementById('title');
const medicalDocuments = document.getElementById('medical_documents');
var filesList = [];
function readURL(input) {
if (input.files && input.files[0]) {
for (let i = 0; i < input.files.length; i++) {
filesList.push(event.target.files[i]); // not working
var tempHtml = '<div class="upload-images" id="image_' + i + '">' +
'<img src="' + URL.createObjectURL(event.target.files[i]) + '" alt="Upload Image">' +
'<i class="far fa-trash-alt"></i>' +
'</div>';
$('#documets_wrapper').append(tempHtml);
}
}
}
$("#medical_submit_button").on('click', function () {
medicalForm.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData();
formData.append('csrfmiddlewaretoken', theToken);
formData.append('title', title.value);
formData.append('medical_documents', filesList);
$.ajax({
type: 'POST',
url: addUrl,
contentType: false,
// contentType: 'multipart/form-data', // tried this one also
processData: false,
data: formData,
success: function (response) {
console.log('value of response');
console.log(response);
},
error: function (error) {
console.log('error: ', error);
},
cache: false,
contentType: false,
processData: false,
});
})
})
'''
I want to iterate over the items array that the google books API provide and print the result inside a div but somehow I am not able to do so. This is what I've written till now.
<body>
<div class="main-body">
<form id="form">
<div class="form-group">
<label for="usr">Enter Book Name</label>
<input type="search" class="form-control" id="search-text">
</div>
<div class="search-button">
<button onclick="function2();" type="button" id="search-button" class="btn btn-default">Search</button>
</div>
</form>
<div id="result">
<!--something seems wrong here-->
<h3 class="title"></h3>
<h4 class="author"></h4>
<img src="" alt="" class="thumbnail">
</div>
</div>
<script>
function function2(){
var result = document.getElementById('search-text').value;
$.ajax({
url: "https://www.googleapis.com/books/v1/volumes?q="+result,
type: 'GET',
dataType: 'json', // added data type
success: handleResponse
});
function handleResponse(res){
$.each(res.items,function(i,item){
var title = item.volumeInfo.title,
author = item.volumeInfo.authors[0],
thumb = item.volumeInfo.imageLinks.thumbnail;
<!--want to iterate over each element in items array and print it-->
$('.title').text(title);
$('.author').text(author);
$('.thumbnail').attr('src',thumb);
})
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
Your current code replaces the previous data with the current data on each iteration.
The easiest way to do what you want should be to build new elements and append them to your "result" div as shown below.
I would also recommend validating the data. Some queries I tested with returned books with no covers or authors.
function function2() {
var result = document.getElementById('search-text').value;
$.ajax({
url: "https://www.googleapis.com/books/v1/volumes?q=" + result,
type: 'GET',
dataType: 'json', // added data type
success: handleResponse
});
function handleResponse(res) {
$.each(res.items, function(i, item) {
var title = item.volumeInfo.title,
author = item.volumeInfo.authors[0],
thumb = item.volumeInfo.imageLinks.thumbnail;
var elTitle = $('<h3 class="title"></h3>').html(title),
elAuthor = $('<h4 class="author"></h4>').html(author),
elThumb = $('<img src="" alt="" class="thumbnail">').attr('src', thumb);
$('#result').append(elTitle, elAuthor, elThumb);
})
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="main-body">
<form id="form">
<div class="form-group">
<label for="usr">Enter Book Name</label>
<input type="search" class="form-control" id="search-text">
</div>
<div class="search-button">
<button onclick="function2();" type="button" id="search-button" class="btn btn-default">Search</button>
</div>
</form>
<div id="result">
</div>
</div>
</body>
I'm having trouble to send a serialized form through ajax to a php file. I can see the string on the client side, but on the server side I receive an empty array.
I'm trying to save the form data into a database, but a I can't seem to find a way to separate every input, and show it in my php file after I sent with ajax.
JavaScript
$(function() {
//twitter bootstrap script
$("button#guardar").click(function(e) {
//var info = $('#myform').serialize();
var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
alert(info);
window.location.href = "solicitudesProc.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
<form class="contact" id="myform" method="post" name='alta'>
<div class="modal-body">
<div class="row">
<div class="col-md-2">
<label>Solicitante</label>
<input type="text" class="form-control pull-right" name='solicitante' maxlength="20" required />
</div>
<div class="col-md-2">
<label>Fecha Emision</label>
<input type="text" class="form-control pull-right" name='fechaEmision' maxlength="20" />
</div>
</div>
<div class="row">
<div class="col-md-2">
<label>Area Solicitante</label>
<input type="text" class="form-control pull-right" name='area' maxlength="20" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cerrar</button>
<button type="submit" id="guardar" name='guardar' class="btn btn-danger pull-right" value="guardar">Generar</button>
</div>
</form>
server side solicitudesProc.php
<?php $info = $_POST;
echo $_POST["solicitante"]; print_r($_POST); ?>
Do not change location
Cancel the submit
I strongly suggest you either remove the form OR wire up the submit event:
$(function() {
$("form.contact").on("submit", function(e) {
e.preventDefault(); // stop the submit
var info = $(this).serialize();
$.ajax({
type: "POST",
url: "solicitudesProc.php",
data: info,
success: function(data) {
console.log(info);
$("#modalnuevo").modal('hide');
},
error: function(data) {
alert("failure");
}
});
});
});
I maked it work by doing this changes:
change the form action to the php file im sending.
<form action="solicitudesProc.php" class="contact" id="myform" method="post" name='alta' >
and my ajax changed to:
var info = $('#myform').serialize();
//var info = $('form.contact').serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: $("#myform input").serialize(),
success: function(data){
//console.log(info);
window.location.href = "solicitudes.php";
//window.location.reload();
$("#modalnuevo").modal('hide');
},
error: function(data){
alert("failure");
}
});
});
});
Thanks for your help!
My server generates a csrfToken, which is inserted into the following element:
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
The {{_csrfToken}}, is used for templating, but at run time is replaced at the server with the actual token.
<div class="formContainer">
<form class="form-horizontal signupform" role="form" action="/process?form=signupform" method="POST">
<input type="hidden" name="_csrf" value="{{_csrfToken}}">
<div class="form-group">
<label for="fieldName" class="col-sm-2 control-label">Name</label>
<div class="col-sm-4">
<input type="text" class="form-control"
id="fieldName" name="name">
</div>
</div>
<div class="form-group">
<label for="fieldEmail" class="col-sm-2 control-label">Email</label>
<div class="col-sm-4">
<input type="email" class="form-control" required id="fieldName" name="email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-4">
<button type="submit" class="btn btn-default">Register</button>
</div>
</div>
</form>
</div>
{{#section 'jquery'}}
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
{{/section}}
How do I update my jQuery call to include the token ? Right now it is generating errors because the token is not included...
Try this, you did not post anything in fact. I did not test it, if it fails, maybe you should collect data manually.
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
+ var payload = $(this).serializeArray()
var $container = $(this).closest('.formContainer'); $.ajax({
url: action,
type: 'POST',
+ data: payload,
success: function(data){
if(data.success){ $container.html('<h2>Thank you</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
though it looks like it's a duplicate post still as far as answer is concerned this is how you should do check this SO post
and I am writing the code for you here
<script>
$(document).ready(function(){
$('.signupform').on('submit', function(evt){
evt.preventDefault();
var action = $(this).attr('action');
var $container = $(this).closest('.formContainer');
var token = $('input[name="_csrf"]').attr('value')
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('Csrf-Token', token);
}
});
$.ajax({
url: action,
type: 'POST',
success: function(data){
if(data.success){ $container.html('<h2>Thank you!</h2>');
}else{
$container.html('There was a problem.');
}
},
error: function(){
$container.html('There was a problem.');
}
});
});
});
</script>
I am finding it difficult to send data to the controller through Ajax post since the object to be sent to the controller cannot be used within the ajax post because of the structure of my code.I am using knockout for data-binding the click event of the Update button.
This is my code
$(document).ready(function () {
var provider = function () {
var self = this;
self.providerID = ko.observable(providerEditInfo.ProviderID);
self.firstName = ko.observable(providerEditInfo.FirstName);
self.lastName = ko.observable(providerEditInfo.LastName);
self.contactEmail = ko.observable(providerEditInfo.ContactEmail);
self.NPI = ko.observable(providerEditInfo.NPI);
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: { providerForUpdate }, -- Cant send this
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
self.cancelEdits = function () {
if (confirm("Are you sure you want to Cancel?")) {
window.location.href = "/Provider/ShowTheListOfProviders";
}
};
}; //End of Constructor.
var providerForUpdate = new provider();
ko.applyBindings(providerForUpdate);
});
On the clck of Update Button,I am calling the 'updateProviderDetails' method.
HTML
#model Greenway.Demo.DataAccess.Entity.Provider
<body>
<div class="container">
<h1 class="col-sm-offset-2">Edit Provider Details:</h1>
<br />
<form class="form-horizontal" role="form" id="editProviderDetailsForm">
<div class="form-group">
<label class="col-sm-2 control-label labelfont">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" autofocus="autofocus" placeholder="Enter the First Name" id="firstName" name="firstName" data-bind="value:firstName , event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Last Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Enter the Last Name" id="lastName" name="lastName" data-bind="value:lastName ,event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group text-center">
<button type="Submit" data-bind="click: updateProviderDetails" class="btn btn-primary">Update</button>
<button type="button" data-bind="click: cancelEdits" class="btn btn-primary">Cancel</button>
</div>
</form>
</div>
</body>
<script type="text/javascript">
var providerEditInfo = #Html.Raw(Json.Encode(Model));
</script>
<script type="text/javascript" src="../../App_Scripts/Shared/Functions.js"></script>
Could someone guide me on how I can send the data to the controller with this code structure.I can't put updateProviderDetails outside the constructor because otherwise, I can't bind it.
Use ko.toJSON to serialize your view model to json:
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
This is also in the Knockout Tutorial