I''m trying to use ajax to show result login from php. But it's not work. It's show error Undefined index like this.
Notice: Undefined index: userEmail in
C:\xampp\htdocs\controllers\login.controllers.php on line 10
Notice: Undefined index: userPassword in
C:\xampp\htdocs\controllers\login.controllers.php on line 10
Login failed
Here are my source code:
login.views.php
<form id="loginForm" action="/controllers/login.controllers.php" method="post">
<input id ="userEmail" type="text" name="userEmail" placeholder="Email">
<input id ="userPassword" type="password" name="userPassword" placeholder="Password">
<button id ="loginSubmit" type="submit" name="loginSubmit">Login</button>
<div id="msg"></div>
</form>
login.Controller.php
<?php
include("../models/user.models.php");
include("../models/dataBase.models.php");
$dbc = new dataBase();
$connect = $dbc->connect('localhost','root','','how_database','','hide');
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$user = new user();
if ($user->login($connect,$_POST['userEmail'],$_POST['userPassword']) == true){
echo "Login Successful";
}
else {
echo "Login failed";
}
}
$dbc->close($connect);
?>
loginAjax.js
$("#loginSubmit").click(function(){
if ($("#userEmail").val() == "" || $("userPassword").val() == "") {
$("div#msg").html("Please enter your email and password");
}
else {
$.post(
$("#loginForm").attr("action"),
$("#loginForm:input").serializeArray(),
function(data){
$("div#msg").html(data);
}
);
}
$("#loginForm").submit(function(){
return false;
})
});
Update Question:
Now i want to add message "Waiting" when after click submit button, hide it when show result messages. What must i do?. Thanks.
You should need to call serialize() on the form, not serializeArray() on the list of inputs. Try this:
$.post(
$("#loginForm").attr("action"),
$("#loginForm").serialize(),
function(data){
$("div#msg").html(data);
}
);
The difference between the functions is the format the output. serializeArray() returns an object, which may not be in the correct format for your receiving endpoint, and serialize() turns the values of the form in to a querystring.
Try this:
$("#loginSubmit").click(function(){
if ($("#userEmail").val() == "" || $("userPassword").val() == ""){
$("div#msg").html("Please enter your email and password");
}else{
var formData = new FormData($("#loginSubmit")[0]);
$.ajax({
url: $("#loginForm").attr("action"),
type: 'POST',
data: formData,
async: false,
dataType: "json",
success: function (data) {
//here success
},
cache: false,
contentType: false,
processData: false
});
}
$("#loginForm").submit(function(){
return false;
})
});
Use this
$("#loginForm").serialize()
instead of
$("#loginForm:input").serializeArray()
You have to use
$.post(
$("#loginForm").attr("action"),
$("#loginForm:input").serialize(),
function(data){
$("div#msg").html(data);
}
Related
I am trying to send a form using Ajax without refreshing the page. It is important that the form gets submitted to the same page, that's why I use url: 'customer-management?form_sent=yes'.
HTML:
<form action="' . $_SERVER['REQUEST_URI'] . '" method="post">
<i onclick="$(this).closest(\'form\').submit()" id="' . $get_uncontacted_member->id . '" class="fa fa-phone-square called"></i>
</form>
JS:
$('.called').click(function() {
$.ajax({
type: 'post',
url: 'customer-management?form_sent=yes',
data: $(this).attr('id');
success: function(r) {
alert(r);
}
})
})
PHP:
if (isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes') { return 'That worked!' }
The page gets reloaded and I guess I am doing everything wrong.
You are not passing your data correctly. Since you are doing a POST Request, you should not pass your data as a query string. Instead, pass it thru the data property. Also, add return false; so that the form will not submit.
$.ajax({
type: 'post',
url: 'customer-management',
data: { form_sent: 'yes' },
success: function(r) {
alert(r);
}
});
return false;
You can remove this code:
onclick="$(this).closest(\'form\').submit()"
You have to return false; from your onclick even, or else the browser will continue to submit the form.
onclick="$(this).closest('form').submit(); return false;"
Try this:
<form method="post">
<i id="<?php echo $get_uncontacted_member->id; ?>" class="fa fa-phone-square called"></i>
</form>
<script>
$('.called').click(function()
{
$.ajax({
type : 'post',
url : 'customer-management',
data : {form_sent: 'yes',id:$(this).attr('id')},
success: function(r)
{
alert(r);
}
})
});
</script>
PHP:
<?php
if(isset($_POST['form_sent']) && $_POST['form_sent'] === 'yes')
{
echo 'That worked!';
exit;
}
?>
I have one checkbox. I want when I checked the checkbox so I get the 1 and then update a mysql query through that get value.
I also want if I unchecked the checkbox so I get a value 0 so then I again update the mysql query. Help me. it should be done with ajax call. code will be in PHP.
HTML code
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1" onclick="return Populat_Industry('set_home_vid.php');"/>
ajax call
<script>
function Populat_Industry(url){
var value=$(#action1).val();
$.ajax({
type: "POST",
url: url,
async: true,
data: "value="+value,
success: function(msg){
//alert('Success');
if(msg !='success'){
//alert('Fail');
}
}
});
}
</script>
PHP code
if($_POST['action1']=='1'){
$query= mysql_query("UPDATE homevideos SET is_active = '1
}
else{
mysql_query("UPDATE homevideos SET is_active = '0')
echo 'success';
Ajax call is async. you cannot use return with it this way. Write checkbox change event in jquery and send ajax call.
Do like this:
HTML:
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1"/>
JQUERY:
$("#action1").change(function () {
var value = $(this).val();
$.ajax({
type: "POST",
url: "set_home_vid.php",
async: true,
data: {
action1: value // as you are getting in php $_POST['action1']
},
success: function (msg) {
alert('Success');
if (msg != 'success') {
alert('Fail');
}
}
});
});
HTML :
<input type="checkbox" name="action1" id="action1" title="Action 1" value="1" url="set_home_vid.php" />
JQuery:
<script>
$("#action1").change(function(){
var value = $(this).val();
var url = $(this).attr("url");
$.ajax({
type: "POST",
url: url,
data: "value="+value, //POST variable name value
success: function(msg){
if(msg =='success'){
alert('Success');
}
else{
alert('Fail');
}
}
});
});
</script>
PHP:
if($_POST['value']==1){ //as used variable name "value" in ajax post data
$query= mysql_query("UPDATE homevideos SET is_active = 1"); //query was incomplete and missing ";"
echo 'success';
}
else{
mysql_query("UPDATE homevideos SET is_active = 0); // missing ";"
echo 'success';
}
Maybe you could use the .is jquery method
something like this:
$("#i").bind("change",function(){
if($(this).is(":checked"))
// set value for ajax
else
// set another value for ajax
// ajax code here
});
You forgot to put quotes around your call to get the input value:
var value=$("#action1").val()
Well, the problem is not new, as I saw (really surf a lot), but still can not find solution for myself.
Description of problem:
Have local Web server - XAMPP;
Firefox 29.0.1
And trying to send POST with $.ajax
function checkUser(){
$.ajax({
type: 'POST',
url: 'ajax/checkUser.php',
data: 'uname='+$("#username").val()+'&pword='+$("#password").val(),
success: function(){
someNewFunc();
},
});
};
This function I'm calling with:
$(document).ready(function(){
$(".button.postfix.login").on("click", function(){
if (($("#username").val() != "") && ($("#password").val() != "")) {
hide(); <-- hide pop ups about empty field
checkUser();
} else {$("#empty").show();} <-- pop ups
});
});
And here code of page with elements:
<input id="username" type="text" placeholder="Username" />
<input id="password" type="password" placeholder="Password" />
<a class="button postfix login" href="#"
onclick="event.preventDefault();">Sign in</a>
I guess that data are going out, but the page checkUser.php doesn't get anything.
What am I doing wrong?
P.S. checkUser.php:
<?php
print_r($_POST);
?>
Result - Array ( )
P.P.S. By the way, if POST change to GET it's working, but need to be POST
$(document).ready(function(){
$(".button.postfix.login").on("click", function() {
var username = $("#username").val();
var password = $("#password").val();
if ((username != "") && (password != "")) {
hide(); <-- hide pop ups about empty field
checkUser(username, password); // Pass the variables here as a parameter
} else {
$("#empty").show();} <-- pop ups
});
// Put the parameters here
function checkUser(username, password) {
$.ajax({
type: 'POST',
url: 'ajax/checkUser.php',
data: { username:username, password:password} //It would be best to put it like that, make it the same name so it wouldn't be confusing
success: function(data){
alert(data);
},
});
};
});
So when you're gonna call it on php
$username = $_POST['username'];
echo $username;
Does your someNewFunc callback fire? Do you see the HTTP AJAX request in the developer console in Firefox?
Try sending your post data as a dictionary to $.ajax:
$.ajax({
type: 'POST',
data: {
uname: $("#username").val(),
pword: $("#password").val()
}
});
I tried many ways to create a simple jquery ajax form but don't know why it is not submitting and/or returning the notification.
Here is my code:
Javascript
...
<script type="text/javascript" src="assets/js/jquery1.11/jquery-1.11.0.min.js"></script>
...
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
HTML
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<a type="submit">Sign up!</a>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
PHP
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
return json_encode($return);
Solved:
There were three problems. And different users solve each of these problems.
In PHP, you must "echo" the return array instead of "return"
At first, you should use a submit button instead of an anchor in the form
In the input, you must set both "id" and "name"
If any of these users want, you can edit or add a new answer with these details, and the points are yours.
You need to do 3 things.
First, wrap your jQuery codes inside $(document).ready() function,
<script type="text/javascript">
$(document).ready(function()
{
$('#form_signup').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'signup.php',
data: $(this).serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
});
</script>
Second, Add a submit button to your form. Also you are missing the name attribute for the email input field. That causes the error in the php file.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="signup" value="Sign Up!"/>
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
Third, echo the results since you are using AJAX to submit the form. return will not have any effects.
<?php
$our_mail = "our#email.com";
$subject = "Wohoo! A new signup!";
$email = $_POST['inputEmail1'];
$return = array();
$return['msg'] = 'Thank you!';
$return['error'] = false;
if(preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)){
$message = "Yesss!! We receive a new signup!
E-mail: $email
";
mail($our_mail, $subject, $message);
}
else {
$return['error'] = true;
$return['msg'] .= 'Something is wrong... snifff...';
}
echo json_encode($return);exit;
I checked and it's working fine.
Hope this helps :)
The problem is in your form.
<form id="form_signup" name="form_signup" method="POST">
<div>
<input type="email" id="inputEmail1" name="inputEmail1" placeholder="your#email.com">
</div>
<div>
<input type="submit" name="submit" value="Submit">
</div>
<div id="form_signup_text">
<!-- A fantastic notice will be placed here =D -->
</div>
</form>
The php code needs to echo instead of return.
just like this:
echo json_encode($return);
Also, your form needs a submit button - type="submit" on an <a> tag doesn't trigger the browser's functionality for handling <form>s
Finally, you need to ensure that your special submit handler is loaded at just the right time -- which, if it is included at the bottom of the page, right before the footer, it should be just fine. However, you can ensure this by wrapping it in
$(document).ready(function(){
//[...]
});
doesn't your a type="submit" need to be an input instead? or a button
I am trying to call webmethod in a ajax using jquery in asp.net, but sometimes it works well and sometimes it doesn't.
Here is my ajax code :
$.ajax({
type: "POST",
url: "frmTest.aspx/fncSave",
data: "{}"
contentType: "application/json; charset=utf-8",
dataType: "json",
async: "false",
cache: "false", //True or False
success: function (response)
result = response.d;
if (result != "") {
alert(response);
}
},
Error: function (x, e) {
alert("err");
return false;
}
});
Here My Server Side Code :
<WebMethod()>
Public Shared Function fncSave() As String
Dim sResult As Int16
Try
Dim obj As New ClsCommon()
sResult = obj.Save()
Catch ex As Exception
ex.Message.ToString()
End Try
Return sResult
End Function
$(this) in the "ajax" function is not the form.
So just try:
$('#form_signup').submit(function(event) {
event.preventDefault();
var $this = $(this);
$.ajax({
type: 'POST',
url: 'signup.php',
data: $this.serialize(),
dataType: 'json',
success: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
},
error: function (data) {
console.log(data);
$('#form_signup_text').html(data.msg);
}
});
});
I admit i didn't check the rest of the code, im pretty sure thats the problem.
Of course if the problem still goes, just "f12" and check console and network for server request and headers, make sure all the params are there.
Hope that helped
i have large form in my website and using serialize() to process the form.
my problem is:
the result always return false after the form has been completed! i checked using firebug. if false, the result being shown. it was actually data.ok == true had been called, but it didnt show the message in the page? and it didnt redirect the page to the destination address?
jquery ajax:
$("#details").live("submit", function(e){
var form = $(this).serialize();
var data_string = form;
$.ajax({
type: "post",
url: "../_include/ajax.php?details",
cache: false,
data: data_string,
dataType: "json",
success: function(data) {
if(data.ok) {
("#pop").html(data.message).addClass("oke").fadeIn("slow");
setInterval(function() {
location.href = data.redirect
},2000)
} else {
$("#pop").html(data.message).addClass("warning").fadeIn("slow");
}
}
});
e.preventDefault();
})
in PHP:
if (isset($_GET['details'])) {
if (empty($name)) {
$data['ok'] = false;
$data['message'] = 'Please enter name!';
} ................ {
.............
} else {
$db->query("UPDATE query....");
$data['ok'] = true;
$data['message'] = 'Your details has been submitted!';
$data['redirect'] = 'index.php?p=details';
}
echo json_encode($data);
}
You appear to have a syntax error in your success function (if that's not a copy/paste error):
("#pop").html(data.message).addClass("oke").fadeIn("slow");
should be:
$("#pop").html(data.message).addClass("oke").fadeIn("slow");
you check for GET in your PHP (if (isset($_GET['details']))), but send POST (by specifying the type as post) in your AJAX.
Either check the $_POST array instead of the $_GET, or change the type to get.