Ajax does not return any result - javascript

My Ajax function does not return any result
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form >
</div>
</div>
$(document).ready(function(){
$("#ok").click(function() {
var login = $("#login").val();
var password = $("#password").val();
var dataString = 'login='+ login + '&password=' + password;
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$userId= $row["id"];
$today=time();
$week=strftime('%W',$today) ;
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
}

The issue is because the button click is submitting the form in the standard manner, meaning your AJAX request is prevented from completing. It's better practice to hook to the submit event of the form.
Also note that your PHP code will never return 0, it would be better to have a error handler should the AJAX not complete as expected. Finally, your current code is wide open to attack; you should look in to using SSL and using prepared statements to avoid SQL injection.
That said, here's a fix for your AJAX issues:
<div id="container">
<div id="connexion">
<form id="myform" method="post" action="">
<input type="text" id="login">
<input type="password" id="password"><br />
<input name="Submit" type="submit" id="ok" value="OK" class="btn "><br /><br />
<span id="errormess"></span>
</form>
</div>
</div>
$("#myform").submit(function(e) {
e.preventDefault(); // stop standard form submission
$.ajax({
type: "POST",
url: 'login.php',
data: {
login: $("#login").val(),
password: $("#password").val()
},
dataType: "json",
success: function(data) {
$('#errormess').html(data);
}
error: function() {
$('#errormess').html("problem");
}
});
});

I think you are giving the data parameter wrongly. It should be like
var dataString = {"login": login,
"password": password}
HTML
<div id="container">
<div id="connexion">
<form method="post" action="">
<input type="text" id="login">
<input type="password" id="password">
<br />
<input name="Submit" type="button" id="ok" value="OK" class="btn ">;
<br /> <br />
<span id="errormess"></span>
</form >
</div>
</div>
JS
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var login = $("#login").val();
var password = $("#password").val();
var dataString = {"login": login,
"password": password}
$.ajax({
type: "POST",
url: 'login.php',
data: dataString,
dataType: "json",
success: function(data) {
if (data == 0) {
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
}//success
});//ajax
return false;
});//ok
});//document
Also change the input type from submit to button and have and e.preventDefault() in your JS.

javascript code :
$(document).ready(function(){
$("#ok").click(function(e) {
e.preventDefault();
var data = (this.form).serialize(); // added code
$.ajax({
url: 'login.php',
data: data,
dataType:'json',
type:'POST',
async:false,
success: function(data) {
if (data.success == 0) { // added code
$('#errormess').html("problem");
} else {
$('#errormess').html(data);
}
},
error: function(data) { // if error occured
}
});
});//ok
});//document
php code :
$sql = "SELECT * FROM utilisateurs WHERE login ='$login' AND
password=$password'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$userId = $row["id"];
$today = time();
$week = strftime('%W', $today);
}
$arr = array(
'userId' => $userId,
'week' => $week,
);
echo json_encode($arr);
} else { // added code
$arr = array("success" => '0');
echo json_encode($arr);
}
Please do check. I have modified the response from PHP as well as jquery code.

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

Ajax script not function

I have a request with ajax that still loads the php script instead of performing its function without refreshing. Am guessing there is an issue with my ajax Below is anything wrong with the ajax script
HTML
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='text' name='conn_id' id='conn_id' value='$ad_id'>
<input type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
</form>
Ajax request
$('#connect_form').submit(function(e) {
e.preventDefault();
var ad_id = $('#conn_id').val();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: ad_id
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});
PHP SCRIPT
require_once("db.php");
$db = new MyDB();
session_start();
if (isset($_POST['connect'])) {
$my_id = $_SESSION['log_id'];
$ad_id = $_POST['conn_id'];
$rand_num = rand();
$hsql = <<<EOF
SELECT COUNT(hash) as count FROM connect WHERE(user_one = '$my_id'
AND user_two = '$ad_id') OR(user_one = '$ad_id'
AND user_two = '$my_id');
EOF;
$hret = $db->querySingle($hsql);
if ($hret == 1) {
$response = "Your are already connected to '$ad_id'";
} else {
$csql = <<<EOF
INSERT INTO connect(user_one, user_two, hash) VALUES('$my_id', '$ad_id', '$rand_num');
EOF;
$cret = $db - > exec($csql);
if (!$cret) {
echo "Error connecting to '$ad_id'";
} else {
echo "Successful";
}
}
}
The form executes but not without refreshing the page. Please what is the issue with the ajax?
I recommend you to send form data serialized, using serialize() method.
Also, use submit event for form: $('form').on('submit', function (e) {}
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "connect_exec.php",
data: $('form').serialize()
}).done(function(response) {
console.log(response);
}).fail(function(data) {
console.log(data);
});
});
$('#connect').click(function(e) {
e.preventDefault();
var ad_id = $('#conn_id').val();
console.log(ad_id);
$.ajax({
type: "POST",
url: "connect_exec.php",
data: ad_id
})
.done(function (response) {
console.log(response);
})
.fail(function (data) {
console.log(data);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action='connect_exec.php' method='post' id='connect_form' enctype='multipart/form-data'>
<input type='text' name='conn_id' id='conn_id' />
<input onclick="return;" type='submit' name='connect' class='conn_text' id='connect' value='connect +'>
</form>

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

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

POST via Ajax does not work correctly

I looked now through a various number of StackOverflow pages and other websites - but can't find the correct solution for my problem. I try to post two values over to a php page via Post:
loginframe.php:
<form class="signin">
<input type="username" id="inputUsername" class="control" placeholder="Username" required autofocus>
<input type="password" id="inputPassword" class="control" placeholder="Password" required>
<div id="remember" class="checkbox">
<label>
<input type="checkbox" value="remember-me">Remember me
</label>
</div>
<button class="btn-login" type="submit" value="login" id="btn-login">Sign in</button>
</form>
My js:
$(document).ready(function(){
$("#btn-login").click(function(){
var username = $("#inputUsername").val();
var password = $("#inputPassword").val();
$.ajax(
{
type: "POST",
url: 'login.php',
data: {
user: username,
pass: password
},
success: function(result)
{
$("#result").html(result);
}
});
});
});
My login.php
<?php
if(isset($_POST['user']) && isset($_POST['pass']))
{
echo $_POST['user'];
echo $_POST['pass'];
} else {
include 'loginframe.php';
}
This login.php is just to check now if the data is passed. That is absolutely not the case. It always opens loginframe.php...
I can't find the error - I appreciate your help! Thank you a lot.
Use prevent default method.
$(document).ready(function(){
$("#btn-login").click(function(event){
event.preventDefault(); // this one prevents the default submission of the form
var username = $("#inputUsername").val();
var password = $("#inputPassword").val();
$.ajax(
{
type: "POST",
url: 'login.php',
data: {
user: username,
pass: password
},
success: function(result)
{
$("#result").html(result);
}
});
});
});

Categories

Resources