Autofill Input Javascript - javascript

I have this script to fill a input box from a link, but it loads only value="Autofill successful." and I want something to load dynamic thing like from a php file like get-fill.php?=names
<input type="text" name="name_textbox" id="id_textbox" />
<a onclick="autofill()" href="#">hey</a>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript" language="JavaScript">
function autofill(){
var object = document.getElementsByName('name_textbox');
object.item(0).value="Autofill successful.";
}
</script>

get-fill.php:
if(isset($_POST['names'])){
echo 'Autofill successful.';
} else {
echo 'names not set';
}
JS:
function autofill(){
$.ajax({
url: "get-fill.php",
type: "POST",
dataType: 'text',
data: {names: true},
success: function(text){
$("input[name=name_textbox]").val(text);
}
});
}
HTML
<input type="text" name="name_textbox" id="id_textbox" />
<a onclick="autofill()" href="#">hey</a>

Related

I am trying to send data to my PHP page from html page using ajax POST method but it give error ,Notice: Undefined index:

<head>
<title>Document</title>
<script>
$(document).ready(function () {
$("#search").on("keyup", function () {
var search_term = $(this).val();
console.log('value--', search_term)
$.ajax({
url: "ajax-live-search.php",
type: "POST",
data: { search: search_term },
success: function (ajaxresult) {
$("table-data").html(ajaxresult);
}
});
});
});
</script>
</head>
<body>
<div id="search-bar">
<label>Search</label>
<input type="text" id="search" autocomplete="off">
</div>
<div id="table-data">
</div>
</body>
PHP page
$search_input = $_POST["search"];
echo $search_input;
error
Notice: Undefined index: search in C:\xampp\htdocs\ajax\ajax-live-search.php on line 3
Change "type" to "method" as below:
$.ajax({
url: "ajax-live-search.php",
method: "POST",
data: { search: search_term },
success: function (ajaxresult) {
$("table-data").html(ajaxresult);
}
});

Grails - Ajax submit not working?

i'm trying to update a div when a form is submited, but it seems that I am forgetting something.
here's my html:
<%# page contentType="text/html;charset=UTF-8" %>
<html>
<head>
<meta name="layout" content="main" />
<g:javascript library="jquery"/>
</head>
<body>
<form id="formEntrada">
<label>Evento: </label>
<g:select from="${listaEvento}" name="evento_id" optionValue="nome" optionKey="id" noSelection="${['':'Selecione...']}" required="true"/><br><br>
<label>Participante: </label>
<input type="text" id="codigo" onkeyup="pesquisa(event,'/eventoEntrada/pesquisar')" value="${participante?.id}" size="15px"/>&nbsp&nbsp
<input type="text" value="${participante?.nome}" size="50px" disabled required="true">
<input type="submit" value="Adicionar">
</form>
<div id="divList">
<g:render template="list"/>
</div>
</body>
</html>
here's my JavaScript
$(document).ready(function () {
$('#formEntrada').submit(function () {
alert("evento_id+participante_id");
var evento_id = document.getElementById("evento_id").value;
var participante_id = document.getElementById("participante_id").value;
$.ajax({
type: 'POST',
url: '/eventoEntrada/entrada',
data: {"evento_id": evento_id, "participante_id": participante_id},
dataType: 'text',
success: function (data) {
$("#divLista").html(data);
}
})
});
});
and this is the method:
def entrada(){
EventoEntrada entrada = new EventoEntrada()
entrada.setEvento(Evento.get(params.evento_id))
entrada.setParticipante(Pessoa.get(params.participante_id))
println params.evento_id
println params.participante_id
entrada.hora_entrada = java.sql.Time.valueOf(new SimpleDateFormat("HH:mm:ss").format(new Date()))
entrada.saida_antecipada = false
if (!entrada.validate()) {
entrada.errors.allErrors.each {
println it
}
}else{
entrada.save(flush:true)
def listaParticipante = EventoEntrada.list()
render (template:"list", model:[listaParticipante:listaParticipante])
}
}
when i submit the form i get the url ".../.../eventoEntrada/index?evento_id=X&participante_id=Y"
why am i missing?
thanks!
I guess your Ajax url is the problem. you can try to give controller Name and action instead of giving path.
$(document).ready(function () {
$('#formEntrada').submit(function () {
var evento_id = document.getElementById("evento_id").value;
var participante_id = document.getElementById("participante_id").value;
$.ajax({
type: 'POST',
url: "${createLink(controller: 'controllerName', action: 'entrada')}",
data: {"evento_id": evento_id, "participante_id": participante_id},
dataType: 'text',
success: function (data) {
$("#divLista").html(data);
}
})
});
});

How to style oembedded tweet?

I have this script (using oembed):
<script type='text/javascript'> $(document).ready(function() {
$("#resolve").click(function() {
var url=$("#retweet_form_url").val();
if (url=="") {
$(".controls").addClass("error");
}
else {
$("#embed").show();
$.ajax( {
url: "https://publish.twitter.com/oembed?maxwidth=840&maxheight=1000&url="+url, dataType: "jsonp", success: function(data) {
$("#embed").html(data.html);
}
});
}
})
})
</script>
<input type="text" id="retweet_form_url" />
<button id="resolve">Get</button>
<div id="embed"></div>
It works, user input url of tweet and it tweet shows up, but I want to make it with no borders.. How?

Sending data to php file AJAX

So I have a target. It's to have a live area where you type in a username and every time you let a key go onkeyup() in the input area, I want it to send that data to a php file where that file will return what you just typed in and display it out where I want it. This isn't going as I like though :P. Please help, and thanks in advance.
JavaScript/jQuery/Ajax Code
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "GET",
url: "php/return.php",
data: user,
cache: false,
success: function(data){
$("#username-display").text(data);
}
});
}
HTML Code
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP Code
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $username;
?>
Please let me know if you need more info to help me solve this...
hey you can use following code
HTML CODE
<script type="text/javascript">
function changeUsername() {
// var user = $("#user").val();
$.ajax({
type: "GET",
url: "s.php",
data: {'user':$("#user").val()},
success: function(data){
$("#username-display").text(data);
}
});
}
</script>
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP CODE
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $_GET["user"];
?>
You need to correct your AJAX code also change type from GET to POST in php code so, final code will be like -
function changeUsername() {
var user = $("#user").val();
$.ajax({
url: "data.php",
data: {'user': user},
type : 'post',
success: function (data) {
$("#username-display").text(data);
}
});
}
PHP CODE :-
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo json_encode($username);
Change Get to Post.
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "POST",
url: "php/return.php",
data: {'user': user},
cache: false,
success: function(data){
alert(data);
$("#username-display").text(data);
}
});
}
Php code first try to get response.
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo $username; exit;
Try:
echo( json_encode( $username ) );
exit( 1 );

Adding email into MySQL database with PHP, JQuery, Ajax

My code so far
main.js file:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
success: function(html) {
alert(html);
}
});
});
index.html file:
<form method="post">
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="submit" name="submit" id="addButton">Add User</button>
</form>
<!-- jQuery first, then Bootstrap JS. -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
<script src="main.js"></script>
validation.php file:
<?php
if (array_key_exists("submit", $_POST)) {
$link = mysqli_connect("localhost", "my_username", "my_password", "my_db");
if (mysqli_connect_error()) {
die("Error Connecting To Database");
}
if (validateEmail($_POST['email'])) {
$query = "INSERT INTO `users` (`email`) VALUES ('".mysqli_real_escape_string($link, $_POST['email'])."')";
if (mysqli_query($link, $query)) {
$success = "Email: ".$_POST['email']." added";
} else {
echo "Error in query";
}
}
}
?>
Here is my validate email function:
function validateEmail($email) {
if (!preg_match('/^([a-z0-9\+\_\-\.]+)#([a-z0-9\+\_\-\.]{2,})(\.[a-z]{2,4})$/i', $email)) {
echo "Invalid Email";
return false;
} else {
$domain = array('umich.edu');
list(, $user_domain) = explode('#', $email, 2);
return in_array($user_domain, $domain);
}
}
Am I performing my Ajax request incorrectly because it never adds the email to the database?
Try something this :
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
'email': email
},
success: function(html){
}
});
There is a lot of way to do that, but I think this is the best way and the easiest way for you to make it work base on your current code.
First thing, You don't need to use type="submit" button when using AJAX.
HTML should be,
<form id='emailform'>
<input type="text" name="email" placeholder="Your Email" id="userInput"><br>
<button type="button" name="submit" id="addButton">Add User</button>
</form>
Your JS should be something like this, use jQuery's .serialize() function to your form:
$('#addButton').on('click', function() {
var email = $('#userInput').val();
$.ajax({
type: "post",
url: 'validation.php',
data: $('#emailform').serialize(),
dataType: "html",
success: function(html) {
alert(html);
}
});
});
Try this ;)
$('#addButton').on('click', function(event){
/* prevent default behavior of form submission. */
event.preventDefault();
var email = $('#userInput').val();
$.ajax({
type: "post",
data: {
email: email,
submit: 1
},
url: "validation.php",
success: function(html){
alert(html);
}
});
});
You need to send email and submit because you wrapped all code in if (array_key_exists("submit", $_POST)) { means you are checking if the submit field submitted or not.
You can use below function also in your main.js.
Please remember that whenever you run any post request and if you want to send some data to server you need to mention that variable or json one of the parameter.
$(document).ready(function(){
$("button").click(function(){
$.post("demo_test_post.asp", {email: "hello#hello.com"},
function(data, status){
alert("Data sent!");
});
});
});
Or you can use the below code also for better understanding
$.ajax({
type: 'POST',
// make sure you respect the same origin policy with this url:
url: 'validation.php',
data: {
email: email
},
contentType:'application/json',
success: function(html){
}
});

Categories

Resources