It is not able to auto-post with JS & AJAX - javascript

I have a formA that posts and saves to the MYSQL DB
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post"> <== first visable form ,Submitting the data into DB
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
I have a hidden form called PayForm that store some var with hidden input method and get the $input_amount as amount from FromA
It is noted that I haven't made the submit button .
This form is going to post to the EPayment Gateway .
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
...
</form>
Here is my idea workflow :
1)User press "Submit" button in FormA ==> info in FormA is going to store into DB .
2)JS is running . Force the PayForm to post automatically . Then, The user is directed to the Payment Gateway .
In short , the Submit button in FormA trigger both forms post
actions .
Here is my JS
<script type='text/javascript'>
var payFormDone = false;
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // THIS WILL TRIGGER THE NEXT CODE
$('#payForm').submit();
}
});
$("#payForm").submit(function(event) {
/* stop form from submitting normally */
//event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $(this),
url = $form.attr( 'action' );
/* Send the data using post with element id name and name2*/
var posting = $.post( url, {
merchantId: $('#merchantId').val(),
amount: $('#amount').val(),
orderRef: $('#orderRef').val(),
currCode: $('#currCode').val(),
mpsMode: $('#mpsMode').val(),
successUrl: $('#successUrl').val(),
failUrl: $('#failUrl').val(),
cancelUrl: $('#cancelUrl').val(),
payType: $('#payType').val(),
lang: $('#lang').val(),
payMethod: $('#payMethod').val(),
secureHash: $('#secureHash').val()
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#FormA').submit();
});
});
</script>
Now ,the idea is not working . It can only trigger second form action .
The first form action is not triggered .At least ,the data in FormA has not saved to the DB .
In short ,
posting.done(function( data ) {
alert('success');
payFormDone = true;
$('#payFormCcard').submit();
});
Is not working .I think !
update
This is how I post FormA to the server
<?php
// Include config file
require_once 'database.php';
header("Content-Type:text/html; charset=big5");
print_r($_POST);
// Define variables and initialize with empty values
$CName = $Address = $Phone = $amount= $Purpose= $Ticket = "";
$CName_err = $Address_err = $Phone_err = $amount_err = $Purpose_err = $Ticket_err="";
// Processing form data when form is submitted
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Validate name
$input_CName = trim($_POST["CName"]);
if (empty($input_CName)) {
$CName_err = "Please enter a name.";
} elseif (!filter_var(trim($_POST["CName"]), FILTER_VALIDATE_REGEXP, array("options" => array("regexp" => "/^[a-zA-Z'-.\s ]+$/")))) {
$CName_err = 'Please enter a valid name.';
} else {
$CName = $input_CName;
}
......
if (empty($CName_err) && empty($Address_err) && empty($amount_err) && empty($Phone_err)) {
// Prepare an insert statement
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "INSERT INTO donation (CName, Address, Phone, Amount ,Ticket, Purpose) VALUES (?, ?, ?, ? ,?, ?)";
$q = $pdo->prepare($sql);
$q->execute(array($CName, $Address, $Phone, $amount ,$Ticket ,$Purpose));
Database::disconnect();
}
}
?>

you should not comment event.preventDefault(); from the second form. Currently what happens is it submitting it as default action which is post to url.

Inside posting.done() please remove/detach the onSubmit handler for FormA just before calling the $('#FormA').submit();
posting.done(function( data ) {
alert('success');
$('#FormA').off('submit');
$('#FormA').submit();
});
EDIT:
Okay, why not send the formA fields with AJAX inside its onSubmit handler and submit formB from the posting.done() handler ?
<script type='text/javascript'>
$('#formA').on('submit', function(e){
e.preventDefault();
/* Send the data using post with element id name and name2*/
var posting = $.post( "<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>", {
field1: $('#field1').val(),
.....
} );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
$('#FormB').submit();
}
});
</script>

The submit handler for FormA actually prevents the submission of the form. That's why data is not saved to db.
$('#FormA').on('submit', function(e){
if( !payFormDone ) {
e.preventDefault(); // => HERE you are preventing the form from submitting
$('#payForm').submit();
}
});
Here you are in the submit handler for the form, but the call to preventDefault stops the submit for FormA and instead triggers the submit of payForm.
See https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault
Also instead of having that you trigger via javascript I'd probably send the first one normally. Then as response of the POST in the first form You might print a message to the user with something like: "You are being redirected to the payment gateway.. " and an hidden form with all the fields that is triggered automatically after x seconds. IMHO this approach is easier and more reliable.
So in the first html page I'll remove all your javascript code and leave only:
<form name="A" id="FormA" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="post">
........field inputs. .....
<input type="submit" class="btn btn-primary" value="Submit">
</form>
When the user clicks on the button he submits the data to the php page in POST. On the server the data is saved to DB and the server prints a message to the user and redirect to the payment gateway (via javascript this time). Something like:
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST') {
.... save data to db
?>
<form name="payForm" id="payForm" method="post" action=" https://test.paydollar.com/b2cDemo/eng/payment/payForm.jsp">
<input type="hidden" id="merchantId" value="sth">
<input type="hidden" id="amount" value="<?php echo $input_amount; ?>" >
<input type="hidden" id="orderRef" value="<?php date_default_timezone_set("Asia/Taipei"); $date = date('m/d/Y h:i:s a', time()); echo $date ; ?>">
<input type="hidden" id="currCode" value="sth" >
<input type="hidden" id="mpsMode" value="sth" >
<input type="hidden" id="successUrl" value="http://www.yourdomain.com/Success.html">
<input type="hidden" id="failUrl" value="http://www.yourdomain.com/Fail.html">
<input type="hidden" id="cancelUrl" value="http://www.yourdomain.com/Cancel.html">
<p>You are being redirected to the payment gateway. If the redirect takes too long</p>
<input type="submit" value"click here">
</form>
<script>
// submits the form after 5 seconds
setTimeout(function(){ $('#payForm').submit(); }, 5000);
</script>
<?php } // this ends the POST block ?>

If I correctly understand the question:
<script type='text/javascript'>
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
var $payForm = $("#payForm");
$.post( $payForm.attr('action'), $payForm.serialize(), function(data) {
alert('success');
// redirect to whereever you want
});
});
});
</script>
UPDATE:
case 2) redirecting to payment gateway:
<script type='text/javascript'>
$("#payForm").submit(function(e) {
alert('redirecting to payment gateway');
});
$('#FormA').on('submit', function(e){
e.preventDefault();
$('input[type="submit"]', $(this)).attr('disabled','disabled');
$.post( $(this).attr('action'), $(this).serialize(), function() {
$("#payForm").submit();
});
});
</script>
NOTE: replace all your script with just this one, and check in browser if requests are made in the data posted - F12 (Developer tools) - Network tab.
Keep in mind that this code is written on a scratch so it may have some errors, but it shows the way.

Related

Page reload and redirect using PHP and Ajax

I have a registration form using php, I'm checking the inputs with a validations and control the submitting form using ajax.
Everything works fine, except, after clicking submit button, Ajax loads the success result, in same registration form, and also not reload the page and redirect.
I want to reload and redirect register.php page to register.php?action=joined using Ajax form submit.
Before Ajax register.php have its own statement, if the registration succsessful ($_GET['action'] == 'joined')* its redirect and destroy the registration form and show success form.*
Please refer on the codes. Can someone help me how to figure this out.
registercontrol.php
<?php
if(isset($_POST['fullname'])){
//fullname validation
$fullname = $_POST['fullname'];
if (! $user->isValidFullname($fullname)){
$infofn = 'Your name must be alphabetical characters';
echo '<p>'.$infofn.'</p>';
}
}
// If form has been submitted process it
if(isset($_POST['submit']) && $_POST['submit'] == 'register')
{
// Create the activasion code
$activasion = md5(uniqid(rand(),true));
try
{
// Insert into database with a prepared statement
$stmt = $db->prepare('INSERT INTO members (fullname) VALUES (:fullname, :email, :active)');
$stmt->execute(array(
':fullname' => $fullname,
':email' => $email,
':active' => $activasion
));
$id = $db->lastInsertId('memberID');
// Send email
$to = $_POST['email'];
$subject = "Verify Your Account";
$body = "<p>Thank you for registering on the demo site.</p>
<p>Hello ".$fullname.", Please click this link to activate your account: <a href='".DIR."activate.php?x=$id&y=$activasion'>".DIR."activate.php?x=$id&y=$activasion</a></p>";
$mail = new Mail();
$mail->setFrom(SITEEMAIL);
$mail->addAddress($to);
$mail->subject($subject);
$mail->body($body);
$mail->send();
// Redirect to index page
header('Location: register.php?action=joined');
exit;
// Else catch the exception and show the error.
}
catch(PDOException $e)
{
$error[] = $e->getMessage();
}
}
?>
register.php and ajax validations
<script type="text/javascript">
$(document).ready(function() {
$("#fullname").keyup(function(event) {
event.preventDefault();
var fullname = $(this).val().trim();
if(fullname.length >= 1) {
$.ajax({
url: 'registercontrol.php',
type: 'POST',
data: {fullname:fullname},
success: function(response) {
// Show response
$("#vfullname").html(response);
}
});
} else {
$("#vfullname").html("");
}
});
$('#submit').click(function(event) {
event.preventDefault();
var formData = $('#register-form').serialize();
console.log(formData);
$.ajax({
url: 'registercontrol.php',
method: 'post',
data: formData + '&submit=register'
}).done(function(result) {
$('.hidden').show();
$('#result').html(result);
})
});
});
</script>
<?php
// If action is joined show sucesss
if(isset($_GET['action']) && $_GET['action'] == 'joined')
{
echo '<div>
<p>Registration is successful, please check your email to activate your account.</p>
</div>';
}
else
{ ?>
<div>
<h1>Create an Account!</h1>
</div>
<form id="register-form" role="form" method="post"
action="registercontrol.php" autocomplete="off">
<input type="text" name="fullname" id="fullname" placeholder="Your name" value="" required>
<div id="vfullname"></div>
<input type="email" name="email" id="email" placeholder="Your Email" value="" required>
<input id="submit" type="submit" name="submit" value="Create Account">
<p class="hidden">Please check everything.</p>
<div id="result"></div>
</form>
<?php } ?>
Thank you.
Check the done block and perform your redirect with JavaScript:
$('#submit').click(function(event){
event.preventDefault();
var formData = $('#register-form').serialize();
console.log(formData);
$.ajax({
url: 'registercontrol.php',
method: 'post',
data: formData + '&submit=register'
}).done(function(result){
var url_to_redirect = "register.php?action=joined";
window.location.href = url_to_redirect;
})
});

Can't submit form without reloading page

I build a link shortener,just for fun!
Everything works, but everytime I create a link and submit the form, the page reloads! I wanted to prevent that with onclick="return false;"but it didnt work.
<input class="submit" type="submit" value="Create!" />
$('#contactForm').submit(function () {
sendContactForm();
return false;
});
But nothing works, the file is just stuck and doesn't do anything! What am I doing from ? This is the problem page https://viid.su
PHP
require("db_config.php");
$uid = 1;
$flink = $_POST['url'];
if(!preg_match("/^[a-zA-Z]+[:\/\/]+[A-Za-z0-9\-_]+\\.+[A-Za-z0-9\.\/%&=\?\-_]+$/i", $flink)) {
$html = "Error: invalid URL";
} else {
$db = mysqli_connect($host, $username, $password);
$conn = new mysqli($host, $username, $password, $database);
$id = substr(md5(time().$flink), 0, 5);
if($conn->query("INSERT INTO `".$database."`.`link` (`id`, `flink`,`adonly`,`userid`) VALUES ('".$id."', '".$flink."','true','".$uid."');")) {
$html = 'Your short URL is <a class="test" href="https://viid.su/'.$id.'">https://viid.su/'.$id.'</a>';
} else {
$html = "Error: cannot find database";
}
mysqli_close($db);
}
You can submit a form without reloading the page by using something like an AJAX call.
JavaScript
$('#contactForm').submit(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "path/to/your/script.php",
data: $('#contactForm').serialize(), // Packs the form's elements
success: function(data)
{
// Do something here if the call succeeded
alert(data);
}
});
}
HTML
<form id="contactForm">
<input type="text" name="username" />
<input type="text" name="email" />
<input type="submit" value="Submit form" />
</form>
PHP
<?php
echo $_POST['username'];
?>
Something along those lines should work, and you don't need anything else, as you are already using jQuery.
you need to use event object as parameter in function callback and call event.preventDefault()
Just change the <input type="submit" /> into something like <button onclick="return false;" id="shortenLinkButton">Send</button>
Then with jQuery you can catch the even like this:
// This code will be usable after the page has fully loaded
$(document).ready(function(){
// Catch the onclick event
$('#shortenLinkButton').on('click', function() {
// do something
alert('clicked the button, do your ajax stuff here after retrieving the data from the input');
});
});

Submit and fetch data without refreshing the page

I'm new to php and mySQL. I've created a webpage, it's essentially a noticeboard. The page has a form to submit content and the content is shown below instantaneously. The content appears when the submit button is pressed, but now if I wanted to submit content immediately after the form still displays the echo that says submission was successful. Could someone point me in right direction to get the page functioning in a way that users can submit content one after the other without refreshing the page? Any help is greatly appreciated. Apologies for the messy code.
This is my input code:
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
if(! get_magic_quotes_gpc() ) {
$name = addslashes ($_POST['name']);
$proposal = addslashes ($_POST['proposal']);
}else {
$name = $_POST['name'];
$proposal = $_POST['proposal'];
}
$email = $_POST['email'];
$sql = "INSERT INTO db3". "(name, proposal, email, join_date )
VALUES('$name','$proposal','$email', NOW())";
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not enter data: ' . mysql_error());
}
echo "<div class='msg-box' id='msg-box'>Entered data successfully</div>\n";
mysql_close($conn);
This is my form:
<form name="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
<fieldset>
<input name = "name" type = "text"
id = "name" placeholder="Name..." required autocomplete="off">
<input name = "email" type = "text"
id = "email" placeholder="example#gmail.com..." autocomplete="off">
<textarea name = "proposal" type = "textarea" maxlength="1000"
id = "proposal" placeholder="Your proposal goes here..." required autocomplete="off"></textarea>
</fieldset>
<fieldset>
<input name = "add" type = "submit" id = "add" value = "Submit">
</fieldset>
</form>
This is my retrieval code:
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
$sql = 'SELECT id, name, proposal FROM db3 ORDER BY ID DESC ';
mysql_select_db('_db');
$retval = mysql_query( $sql, $conn );
if(! $retval ) {
die('Could not get data: ' . mysql_error());
}
while($row = mysql_fetch_array($retval, MYSQL_ASSOC)) {
echo
"<article>".
" <div class='id'> ID :{$row['id']} </div> ".
" <section> <p> {$row['proposal']} </p></section> ".
" <section class='name'><h3> {$row['name']} </h3></section> ".
"</article>"
;
}
mysql_close($conn);
?>
Use this code:
<script>
submitHandler: function(form) {
$.ajax({
url: '',
type: 'POST',
data: $("#submission").serialize(),
success: function() {
alert('submitted data: '$("#submission").serialize());
return false;
}
});
}
</script>
Please change the form line with this one:
<form name="submission" id="submission" method = "post" action = "<?php $_PHP_SELF ?>" >
You can do this using AJAX
You will use javascript to send the data to a PHP script which will process it. The same script will return the new data that was just submitted so you can display it on the page.
An example would be
HTML
<form id="comment">
<input type="text" id="userInput" name="comment" placeholder="Tell us what you feel about this" />
<input type="submit" value="Submit" />
</form>
jQuery
<script>
$("#comment").on('submit', function(e) {
// Stop the form from being submitted the standard way
e.preventDefault();
// Put the user's input into a variable
var userInput = $('#userInput').val();
// Do some validation of the data if needed
// ...
// ...
// Perform AJAX request (a.k.a send the data to the server)
$.ajax({
// There are many parameters one can use here
// Browse the documentation to get familiar with the most useful ones
url: 'proccess.php', // The PHP script that will handle the request
type: 'POST', // This can be set to GET, but in this case we'd use POST
data: { comment: userInput }, // "comment" will result in $_POST['comment'], and userInput is the value of it
// If the script returns a 200 status (meaning the request was successful)
success: function(data) {
// The data variable will be the response from the PHP script
// Depending on what you are going to do with the data returned,
// you may want to ensure it is returned as valid JSON
},
error: function() {
// The request failed - So something here
// ...
// ...
}
});
});
</script>
PHP (process.php)
<?php
$data = $_POST['comment'];
// Do all you would normally do when submitting a post
// ...
// ...
// Now, upon successfully storing the data in your database,
// you can return something to the 'data' variable in the AJAX.success function
?>
Do some research on AJAX and jQuery. It's really fun to work with

Textbox not clearing after ajax call

I have this chat room on my website, where the user types their message into a textbox and when they press enter (or the send button), jQuery takes the data from the textbox, disables the textbox, sends the data to the file send.php where it is then processed and put into the database, and then it should clear and undisable the textbox once it successfully runs through the PHP script. What is happening is the data is being submitted and it runs through the script (sends the data to the database successfully) but the jQuery is not clearing and undisabling the textbox.
Can someone explain to me what is wrong?
jQuery:
$('#formSend').on('submit', function (e) {
e.preventDefault();
var textArea = document.getElementById('styled');
if( textArea.value != "" ) {
var formData = $('form').serialize();
$('.expand').prop("disabled", true)
$.ajax({
type: 'post',
url: 'send.php',
data: formData,
dataType: "json",
success: function (formData) { //put data in parentheses when coming back
alert("Success");
$(".expand").val('');
$('.expand').prop("disabled", false);
if( formData["banned"] == 1 ) {
var rel = confirm("You have been banned.");
if (rel) {
location.reload();
}
else {
location.reload();
}
}
}
});
}
else {
alert("Your message must be longer than 1 (one) character.");
$('#styled').focus();
}
});
send.php:
<?php
include("../config.php");
session_start();
$msg = strip_tags( $_POST['msg'], '<b></b>' );
if( $msg == "" ) {
exit("There is no message.");
}
$username = $_SESSION['USER'];
$date = new DateTime();
$formattedDate = $date->format('Y-m-d H:i:s');
$stmt = $db->prepare("SELECT id, username FROM users WHERE username = :username");
$stmt->execute(array(":username" => $username));
$row = $stmt->fetch();
$userID = $row['id'];
$checkBanned = $db->prepare('SELECT banned FROM users WHERE username = :username');
$checkBanned->execute(array(
':username' => $username
));
$banned = $checkBanned->fetch();
if( $banned['banned'] == "yes" ) {
$return = array('banned' => 1);
echo json_encode($return);
exit;
}
try {
$stmt = $db->prepare('INSERT INTO `chat-messages` (userID,msg,date) VALUES (:userID, :msg, :date)');
$stmt->execute(array(
':userID' => $userID,
':msg' => $msg,
':date' => $formattedDate
));
}
catch(PDOException $e) {
echo $e->getMessage();
}
?>
Here is the form too, if needed.
<form action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="hidden" name="banned" value="no" />
<input type="submit" name="submit" value="Send" class="send" />
</form>
I think the problem is you have not sent any responce if user is not banned and message is stored successfully.
If "success" is not being alerted then that is the problem.
Try this,
try { $stmt = $db->prepare('INSERT INTO `chat-messages` (userID,msg,date) VALUES (:userID, :msg, :date)'); $stmt->execute(array( ':userID' => $userID, ':msg' => $msg, ':date' => $formattedDate ));
$output = "success";
} catch(PDOException $e) { $output = $e->getMessage(); }
finally{
echo json_encode($output);
}
I see you are refreshing the page afterwards, that could make the form to autocomplete to the previous value, try this:
<form autocomplete="off" action="send.php" method="post" name="formSend" id="formSend" />
<textarea id="styled" class="expand" name="msg" placeholder="Your Message Here" onfocus:"setbg(\'#e5fff3\');"required></textarea>
<input type="hidden" name="banned" value="no" />
<input type="submit" name="submit" value="Send" class="send" />
</form>
If you dont want to reload the page (which should actually happen, if you dont prevent the submit event from beeing triggered in the ajax callback by event.preventDefault()) you have to reset the form by doing something like $('#formSend').reset();
Furthermore, there is no disabled='false', you need to remove the attribute: $('.expand').removeAttr('disabled');.
By the way, it is good habit to save selector you need more than one time ;)
Have you tried something like:
$('.expand').removeAttr("disabled");

Ajax and php, result in a div

I want show the result of my server page in the "result" div.
This is my scheme:
home.php
<script src="myscripts.js"></script>
<div id="loginform">
<div id="result"></div>
<?php include_once 'core.login.php'; ?>
</div>
myscripts.js
$(document).ready(function() {
$('#login').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#result').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
core.login.php
<?php
// stuff about $db variable e other stupid things like $tool = new Tools etc...
$email = $_POST["email"];
$password = $_POST["password"];
// Initializing login process
if (isset($email) or isset($password)) {
$tool->decode($email, $password, $db);
}
?>
<form action="core.login.php" method="POST" id="login">
<fieldset>
<legend>Data login:</legend>
Email:<input id="email" type="email" name="email" placeholder="someone#example.com" required>
<br>
Password:<input id="password" type="password" name="password" required>
<br>
<input type="submit" value="Submit">
</fieldset>
</form>
class.php
public function decode($email, $password, $db) {
if ($stmt = $db->prepare("SELECT password FROM users WHERE email = ?")) {
$stmt->bind_param('s', $email);
$stmt->execute();
$stmt->store_result();
$stmt->bind_result($password_db);
$stmt->fetch();
if ($stmt->num_rows == 1) {
if ($password == $password_db) {
echo "Success";
} else {
echo "Error";
}
} else {
echo "Email didn't found!";
}
}
}
Without AJAX if i start the code normally it work, it give me the correct echo result ( success or error ) but when i use AJAX, nothing happen.
UPDATE
Ok guys the problem was the action url, my core file is in the folder core/core.login.php, now it display the page in the result div, but the page core show me this now:
Fatal error: Call to a member function decode() on a non-object in website on line 9
Maybe ajax don't pass the variables like object?
Try this js
$(document).ready(function() {
$('#login').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $("#login").serialize(), // get the form data
type: $(#login).attr('method'), // GET or POST
url: $(#login).attr('action'), // the file to call
success: function(response) { // on success..
$('#result').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
Try with that in your js file:
(Or Document)
$('#loginform').on('submit', '#login', function() {
//AJAX etc..
})
instead of :
$('#login').submit(function() {
//AJAX etc..
}

Categories