hy
i am trying to submit data using ajax and then get it. i tried this code..
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>index</title>
<link rel="stylesheet" href="css/bootstrap.css"/>
</head>
<body>
<div>
<form action="voteupdown.php" id="form" method="post">
<input type="text" name="fname" id="fname" class="form-control"/><br/>
<input type="text" name="lname" id="lname" class="form-control"/><br/>
<input type="submit" name="submit" id="submit" value="Submit"/>
</form>
<div id="result">
</div>
</div>
<script src="js/jquery.js"></script>
<script>
$(document).ready(function(){
$('#form').submit(function(){
return false;
});
$("#submit").click(function(){
$.get(("voteupdown.php"), function (data) {
$("#result").html(data);
});
});
});
</script>
<script src="js/bootstrap.js"></script>
</body>
</html>
the voteupdown.php
<?php
$name = $_POST['fname'];
$lname = $_POST['lname'];
echo $name;
?>
when i simple echo " hy this is test" in my voteupdown.php then the code will work, but when i try to echo the first and last name then it will show the below error.
Notice: Undefined index: fname in G:\xampp\htdocs\Questiona-Step1\voteupdown.php on line 3
Notice: Undefined index: lname in G:\xampp\htdocs\Questiona-Step1\voteupdown.php on line 4
Any help will be appreciated.
Your server side script is expecting data to be POSTed to it, your javascript is sending a GET request. In addition, your GET request is not actually including any of the data.
Assuming you want to keep the server side expecting POST you should change your javascript as follows
$("#submit").click(function(){
var fname = $('#fname').val();
var lname = $('#lname').val();
$.post("voteupdown.php"), {
fname: fname,
lname: lname
},function (data) {
$("#result").html(data);
});
});
Your code isn't working because your PHP is expecting data in the $_POST variable.
You're also not posting any of your form data to the PHP file.
Try the following:
$('body').on('submit', '#form', function(event) {
event.preventDefault();
var formData = $(this).serialize();
$.ajax({
url: 'voteupdown.php',
type: 'post',
data: formData,
success: function(result) {
$('#result').html(result);
},
error: function(jqXHR, textStatus, errorThrown) {
# error handling here
}
});
});
Use this code in your form submit call:
$("#submit").click(function(){
$.post(("voteupdown.php"),
{
fname: $("#fname").val(),
lname: $("#lname").val()
},
function (data)
{
$("#result").html(data);
});
});
You are using $.get method for ajax and you are trying to get val by $_POST. because of this you got this error. Try This hopefully it will help you:
$.post( "voteupdown.php", { fname: $("#fname").val(), lname: $("#lname").val() }, function( data ) {
$("#result").html(data);
});
or if you wants to get response in json format than use this
$.post( "voteupdown.php", { fname: $("#fname").val(), lname: $("#lname").val() }, function( data ) {
$("#result").html(data);
}, "json");
Related
i need some help,
am trying to send message to telegram bot
but things are not working out for me,
am just trying to archive what i want to do. am new to jquery and javascript
below is what i tried
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<script>
$(document).ready(function () {
$("#add_button").click(function(event) {
Execute();
});
var fname = document.querySelector('input[name="fname"]').value;
var country = document.querySelector('input[name="country"]').value;
Message: "<html><br>| Fullname: ${fname} <br> | Country: ${country} <br></html>";
function Execute(){
$.ajax({
type: 'POST',
url: 'https://api.telegram.org/bot<token>/sendMessage?chat_id=<id>text=<message>&parse_mode=html',
data: Message,
success: function(res) {
$('#response').text('Message sent');
},
error: function() {
alert("error failed");
}
});
};
});
</script>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
<input type="button" id="add_button" value="Submit">
<div id="response"></div>
<body>
</body>
</html>
There are several issues in you script:
Your <body> tag is misplaced
AFAIK, your payload must be form encoded (not as GET params)
Use ` for format strings instead of "
read the input values in the execute method, not outside (otherwise you read them only once on page load).
You cannot use <br> or <html> in the message, see the docs
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<input type="text" id="fname" name="fname" placeholder="fullname">
<input type="text" id="country" name="country" placeholder="country">
<input type="button" id="add_button" value="Submit">
<div id="response"></div>
<script>
const token = '<token>';
const chatId = '<chat_id>';
$(document).ready(function () {
$("#add_button").on('click', function (event) {
execute();
});
function execute() {
const fname = document.querySelector('#fname').value;
const country = document.querySelector('#country').value;
const message = `Fullname: ${fname}\nCountry: ${country}`;
$.ajax({
type: 'POST',
url: `https://api.telegram.org/bot${token}/sendMessage`,
data: {
chat_id: chatId,
text: message,
parse_mode: 'html',
},
success: function (res) {
console.debug(res);
$('#response').text('Message sent');
},
error: function (error) {
console.error(error);
alert("error failed");
}
});
}
});
</script>
</body>
</html>
And a security note:
Do NOT use this script in any production! NEVER EVER!
Everyone would be able to read and abuse your bot token.
Use a backend for this.
This is my JS file:-
$(document).ready(function(){
$('form').on('submit', function(){
var email = $("form input[type=text][name=emails]").val();
var todo = {email: email.val(),
pass:dat.val()};
$.ajax({
type: 'POST',
url: '/project',
data: todo,
success: function(data){
//do something with the data via front-end framework
location.reload();
}
});
return false;
});
});
This is my html document:-
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.js"></script>
<script src="/assests/todo-list.js"></script>
<body>
<form>
<div class="container">
<label><b>Email</b></label>
<input type="text" placeholder="Enter Email" name="emails" required>
<label><b>Password</b></label>
<input type="password" placeholder="Enter Password" name="psw" required>
<button type="submit" class="signupbtn">Sign Up</button>
</div>
</div>
</form>
</body>
</head>
</html>
I want that when i click submit button value from both text boxes gets saved in my database(using Mlab),for that i am using a json file to fire post request to the server.
My main post request handler:-
app.post('/project',parser,function(req,res)
{
var register=Todo(req.body).save(function(err,data)
{
if(err) throw err
res.json(data);
});
});
EDIT:-
I removed my Javascript file and now i am directly posting the form using and i am able to save my email address but not the password.
This is my main code now :-
app.post('/views/register',parser,function(req,res)
{
var data={
email:req.body.emails,
password:req.body.passcode
};
var send=Todo(data).save(function(err)
{
if(err) throw err
res.render('login')
})
});
If I understand your question right, you're missing the contentType param.
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
...
then try again.
I was not following the correct schema for the database when creating the object
var data={
email:req.body.emails,
password:req.body.passcode
};
The property name was pass and i was using password that's why it was not inserting the password.
var data={
email:req.body.emails,
pass:req.body.passcode
};
Can someone please guide me through where am I going wrong in this piece of code below
index.php :-
<script type="text/javascript">
function fun(){
alert("H");
$.ajax({
type: "POST",
url: 'test.php',
data: {name: 'Wayne', age: 27},
success: function(data){
alert(data);
},
error: function(error){
alert(error);
}
});
alert("HE");
}
</script>
<input type="button" value="submit" onclick="fun()" />
test.php :-
<?php
$name = $_POST['name'];
$age = $_POST['age'];
echo $name.$age;
?>
I'm not getting any output nor any error.
The problem is in the javascript code, specifically in how you're calling the function. Try this instead:
// javascript
document.getElementById('do-fun').addEventListener('click',function(){
fun();
});
// html
<input type="button" value="submit" id="do-fun" />
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){
}
});
I am trying to get the value of a textbox without pass through form actions (because i cannot neither redirect to another page or refresh the current one).
index.php
into head
<script type="text/javascript">
function send() {
$.ajax({
type:"POST",
url: "script.php",
data: {
fname: document.getElementById("fname").value,
lname: document.getElementById("lname").value
},
success: function callScriptAndReturnAlert() {
var sdata = new XMLHttpRequest();
sdata.onload = function() {
alert(this.responseText);
};
sdata.open("get", "script.php", true);
sdata.send();
}
});
}
</script>
into body
<button class="myclass" onclick="send();">MyButton</button>
<input type="text" id="fname" placeholder="First name here" />
<input type="text" id="lname" placeholder="Last name here" />
Button is before input just for UI stuffs
script.php
$prev = $_SESSION['prev'];
$fname = $_POST['fname'];
$lname = $_POST['lname'];
[....do something....]
echo 'You used '.$fname.' and '.$lname;
Well.. the script.php doesnt receive the value of the inputs fname and lname.
You are trying to make two ajax calls when you only need one.
<script type="text/javascript">
function send() {
$.ajax({
type:"POST",
url: "script.php",
data: {
fname: $("#fname").val(),
lname: $("#lname").val()
},
beforeSend: function(){
alert('Sending');
},
success: function(data) {
//Received data from PHP script
alert(data);
},
error: function(){
alert('Error !');
},
complete: function(){
alert('Done');
}
});
}
</script>
$.post(
'script.php', // Your PHP file
{ // The data to pass
'fname' : $('#fname').val(),
'lname' : $('#lname').val()
}
).done(function(data) { // Here your AJAX already finished correctly.
alert(data); // Show what the PHP script returned
});
The $.ajax(), $.get() and $.post() jQuery methods are for making AJAX calls and, due to that, they already manage their own XMLHttpRequest object.