Web development. Ajax - javascript

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" />

Related

ajax Uncaught ReferenceError: post is not defined at HTMLButtonElement.<anonymous>

Have no idea what it could be. Please help me release this ajax commentaries. I have never done this before. HTML form for input text and some ids:
<form id="send_comment" method="POST" action="write_comment.php">
<input hidden type="text" id="c_post_id" name="c_post_id" value="<?=$_GET["id"]?>">
<input hidden type="text" id="c_user_id" name="c_user_id" value="<?=$user_id?>">
<div class="form-group shadow-textarea">
<textarea class="form-control z-depth-1" type="text" id="c_text" rows="3" placeholder="Write comment here..." name="c_text" required pattern="^[a-zA-Z0-9\s]+$"></textarea>
</div>
<div class="col-md-12 text-center">
<button id="make_comment" class="btn btn-default" name="make_comment" type="submit" value="Submit"><i class="fas fa-check" style="font-size: 35px;"></i></button>
</div>
</form>
PHP processing:
if($_POST["make_comment"]) {
$c_post_id = $_POST["c_post_id"];
$c_user_id = $_POST["c_user_id"];
$c_text = $_POST["c_text"];
$date = date("m/d/y G:i:s<br>", time());
$sql = "INSERT INTO `comments` VALUES ('$c_post_id','$c_user_id',null,'$c_text','$date')";
if ($connect->query($sql) === TRUE) {
header("Location: http://thecobnmod.com/post.php?id=$c_post_id");
}
else {
exit( "Error: " . $sql . "<br>" . $conn->error);
}
}
JS ajax:
function funcSuccess (data) {
$("#comment_ajax").text(data);
}
function funcBefore (){
$("#comment_ajax").text("Loading comment...");
}
$(document).ready(function(){
$("#make_comment").bind("click", function () {
event.preventDefault();
$.ajax({
post: $("#c_post_id").val(),
user: $("#c_user_id").val(),
text: $("#c_text").val(),
url: "write_comment.php",
type: "POST",
data: {
c_post_id:post,
c_user_id:user,
c_text:text
},
dataType: "html",
beforeSend: funcBefore,
success: funcSuccess
});
});
});
Post id comes fro GET request to input field. I thought it could be a problem but not. now I really do not know what's wrong. Please help.
I strongly recommend consulting the documentations: Ajax doc
Ajax doesn't have post property AFAIK!
I'm not sure what you wanted to do, but here is a simple ajax example:
$.ajax({
url: 'here/is/some/url',
type: 'post',
data: {
some_key: 'value1',
other_key: 'value2',
/*...*/
},
dataType: 'html',
beforeSend: function() {/*...*/}
success: function(result) {/*...*/},
error: function(error) {/*...*/}
});

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

Saving form value to database through ajax wordpress

How can I save data to database using ajax and form. I have working this for one day but still no luck I don't know what's wrong with this code I came up right now. This is one is wordpress
Here is the code:
This javascript was in the header.php
<form>
<input name="MyUrlName" type="text" class="add_name" id="MyUrlName" placeholder="Name of website">
<input type="button" name="submit" id="MyUrlsubmit" value="Add URL" class="submit">
</form>
jQuery(document).ready(function(){
jQuery("#MyUrlsubmit").click(function(){
var name = jQuery("#MyUrlName").val();
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {"action": "savedata", "MyUrlName":name},
success: function(data){
//alert('success');
console.log(data);
}
});
});
});
Here is the code in function.php
function savedata(){
$name = $_POST['MyUrlName'];
global $wpdb;
$table_name = $wpdb -> prefix . "save_url";
$wpdb->insert(
$table_name, array(
'name' => $_POST['MyUrlName']
),
array(
'%s'
)
);
return true;
exit();
}
add_action('wp_ajax_nopriv_savedata', 'savedata');
add_action('wp_ajax_savedata', 'savedata');
I'm implementing it in frontend
Thank you in advance
use this code
<form>
<input name="MyUrlName" type="text" class="add_name" id="MyUrlName" placeholder="Name of website">
<input type="button" name="submit" id="MyUrlsubmit" value="Add URL" class="submit">
</form>
jQuery(document).ready(function(){
jQuery("#MyUrlsubmit").click(function(){
var name = jQuery("#MyUrlName").val();
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {action: "savedata", MyUrlName:name},
success: function(data){
//alert('success');
console.log(data);
}
});
});
});

Ajax is not getting data properly

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

Categories

Resources