How to call PHP function without reloading? - javascript

In my test work, I want to send data to DB by pressing "Save" button and stay at the same page. But this button after sending data to DB opens /file.php and shown "Success".
I tried to solve the task by JS I found, but it doesn`t work.
$('#sub').click( function() {
$.post( $('myForm').attr('action'), $('#myForm :input').serializeArray(), function(info){ $('result').html(info);} );
clearInput();
});
$('myForm').submit(function() {
return false;
});
function clearInput() {
$('#myForm :input').each( function() {
$(this).val('');
});
}
<html>
<head>
<title>
OneTwoThree
</title>
</head>
<body>
<form id='myForm' action="db.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="age"><br>
<button id="sub">Send</button>
</form>
<span id="result"></span>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="script/myjs.js" type="text/javascript"></script>
</body>
</html>
Callable PHP file:
<?php
$conn = mysql_connect('localhost','root','');
$db = mysql_select_db('mytestbd');
$name = $_POST['name'];
$age = $_POST['age'];
$q = "INSERT INTO `post`(`number`, `sometext`) VALUES ('$age','$name')";
if(mysql_query($q))
echo "Success";
else
echo "Fail";
?>

Try this block of js which includes some changes and adjustments (noted below):
$(document).ready(function() { // ready wrapper (was missing in your code)
$('#sub').click( function(e) { // added 'e'
e.preventDefault(); // added to stop buttons default behavior
$.post( $('#myForm').attr('action'), // added '#' to id locator
$('#myForm').serialize(), // reduced to just serialize the form data
function(info){
$('#result').html(info); // added '#' to id locator
clearInput(); // moved clear form into success callback
}
);
});
$('#myForm').submit(function() { // added '#' for id locator
return false; // this submit handler is most likely
}); // not needed, but doesnt hurt
function clearInput() {
$('#myForm :input').each( function() {
$(this).val('');
});
}
});
PS Once you get the submission process working, you will want to switch your use of mysql_* functions to either mysqli or PDO (as mysql_ is depreciated in php 5.5x, and removed in php7+).
Then after you switch, look into Prepared Statements to safeguard from sql injection attacks.

Just use a include statement.
if(mysql_query($q))
echo "Success";
include('yourFileWithTheForm.php');
else
echo "Fail";
?>

Related

How to prevent form refresh but submit form data on same page?

My form kept submitting and then refreshing so I looked at How to prevent page from reloading after form submit - JQuery to figure out how to stop it. The difference in the answer, however, with my solution was that I was submitting the form to itself.
Here's my code:
HTML
<form autocomplete="off" method="post" name="rp">
<input placeholder="Code" type="text" name="code" required>
<button type="submit">Submit</button>
</form>
PHP
<?php
$response = "";
if(isset($_POST['code'])){
echo "<script> alert('test'); </script>";
$password = $_POST["code"];
$result = $connection->query("SELECT * FROM Users WHERE passwords = '$password' LIMIT 1");
if($result->num_rows != 0) {
// unpack object
$data = mysqli_fetch_array($result);
// retrieves user ID (set into a cookie for x amount of time?)
$id = $data["ID"];
mysqli_close($connection);
echo "<script> alert('test 2'); </script>";
$response = "test 2";
header("Location: assessment.php");
} else {
$response = "test 3";
echo "<script> alert('test 3'); </script>";
mysqli_close($connection);
}
}
?>
JS
$("form").submit(function (e) {
// prevent page refresh
e.preventDefault();
var formData = $(this).serialize();
// Make AJAX request
$.post("login.php", formData);
});
I want the form to submit the data but not refresh. What am I doing wrong?
EDIT:
The problem has been narrowed down to the php. Since the request is through javascript, what should the name in the if-statement argument be. It can't be 'rp'.
So I found out something extremely curious. When I changed the if statement to if(isset($_POST['code']){} as some urged me to in the comments and I entered in the correct password, it follows the correct loop and produces this error:
VM1368 jquery.min.js:2 GET http://localhost:8080/assessment 404 (Not Found)
However, it does not produce the alert code I place before the header(). When I put in an incorrect password, it also doesn't do anything (even though I have an else statement). I've updated the php section to include most of the code. The $response variable and the echo/alerts are for debugging.
Final Edit:
Ironically, the reason none of my debugging wasn't working was because the page wasn't refreshing so alerts and variable updates wouldn't happen. (My quest to stop page refresh created all these problems). The solution to my original question was provided by MH2K9 and Toni Michel Caubet in the comment section. Thank you to them and others who tried to help.
Try this :
HTML :
<form autocomplete="off" method="post" name="rp" onsubmit="return false;">
<input placeholder="Code" type="text" name="code" required>
<br>
<button type="submit">Submit</button>
<button id="back_button" type="button"><img src="pics/back_arrow.png">Back</button>
</form>
JS:
$("form").submit(function (e) {
// prevent page refresh
e.preventDefault();
var formData = $(this).serialize();
// Make AJAX request
$.post("login.php", formData , function(data) {
alert(data);
$("form").reset();
});
});
You can alternatively call a function using the onsubmit attribute in HTML.
<form onsubmit='return preventSubmit(e)'>
// form content
</form>
<script>
function preventSubmit(e) {
e.preventDefault()
return false
}
</script>

jQuery ajax not posting values to php script

I am having a problem with posting a value to my php script via jQuery/ajax. I have searched around looking for a solution but cannot seem to figure it out why i am not getting the value posted.
here's my code.
page.html
<body>
input message:<p><input type="text" id="note" name="note" placeholder="enter something that made you feel this way"></p><br />
<p><button name="submitMessage">submit</button></p>
<script src="../js/jquery-3.1.1.js"></script>
<script src="../js/welcomeScript.js"></script>
<script> $( document ).ready(function() {
$('[name=submitMessage]').on('click', function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: '../php/post-note.php',
data: {data: $('#note').attr('val')},
success: function(){
alert('added your note, you will now go to main app!');
window.location.href = "../home.php";
}
});
});
});
</script>
</body>
post-note.php
session_start();
$note = $_POST['data'];
if(isset($note) && isset($_SESSION['username'])){
$username = $_SESSION['username'];
$sqlMessage = "UPDATE mt_tbl SET note = '$note' WHERE userName = '$username'";
mysqli_query($conn, $sqlMessage);
echo "note: ".$note. " added to the dB!";
}
Instead of $('#note').attr('val') use $('#note').val()
Why? the reason is given below:-
console.log($('#note').attr('val'));
console.log($('#note').val());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id = "note" value = "2">

AJAX Call to PHP File for HTML Form Not Working

I have a login-form created using HTML that looks like this:
<div class= "form-header">Login</div>
<div class= "error-message" id= "login-error-exists"></div>
<form action= "login.php" method= "POST" onsubmit= "loginCheckIncorrect()">
<div class= "form-field">
<div class= "form-text">
username:
</div>
<input type= "text" class= "login-textbox" id= "login-login-username" name= "loginLoginUsername">
</div>
<div class= "form-field">
<div class= "form-text">
password:
</div>
<input type= "password" class= "login-textbox" id= "login-login-password" name= "loginLoginPassword">
</div>
<input type= "submit" value= "Login" class= "signup-confirm">
</form>
As you can see, its a simple form that is sent to login.php though POST. Upon submitting this form, it calls a JavaScript (using jQuery) function known as loginCheckIncorrect(), which is shown below:
function loginCheckIncorrect() {
"use strict";
var loginLoginUsername = $("#login-login-username").val(), loginLoginPassword = $("#login-login-password");
alert("test1");
$.post('usernameIncorrect.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
});
alert("test3");
event.preventDefault();
return false;
}
As you can see, this function creates the variables to store the value of username and password entered in each textbox. It sends an alert out (debugging), and then uses a jQuery.post function to send the variables to the PHP file, which I will show below. It then (is supposed to) takes the data sent back from the PHP file to echo into the error div I have in my HTML form.
It then calls an alert (more debugging) and uses a combination of event.preventDefault() and return false to (supposedly) stop the form from submitting. This is repeated after the post function.
This is my PHP code:
<?php
header("X-XSS-Protection: 1");
include("connect.php");
$username = mysqli_real_escape_string($con, $_POST["loginLoginUsername"]);
$password = mysqli_real_escape_string($con, $_POST["loginLoginPassword"]);
echo "<script>alert('test');</script>";
$sql = mysqli_query($con, "SELECT * FROM main WHERE username='$username' and password='$password'");
$count = mysqli_num_rows($sql);
if ($count == 1) {
echo "";
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
} else {
echo "username and/or password is incorrect.";
}
?>
When I attempt to execute this code, the only alert it displays is test1. Could someone explain to me why this is, and more importantly, how I can fix it? Thanks in advance.
Look at your network requests in your browser's debug panel to see if it's sending what you think it is, put some debug statements in your PHP to see what is and isn't getting hit.
In this case, I think you might be missing the .val() on $('login-login-password') just before the alert("test1") in your javascript.
There is no event defined. That would be a problem and the form will submit. And the preventDefault in the callback is useless since the function already finished.
1) The name of the php file is login.php
2) The url to which you are requesting the post is usernameIncorrect.php
Therefore:
$.post('login.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
});
Alert test1 is the only one appearing because the post fails.
Probably with a fail event you would have cached the error.
Try, if you want to test that:
$.post('wrongUrl.php', {'loginLoginUsername': loginLoginUsername, 'loginLoginPassword': loginLoginPassword}, function (data) {
$("#login-error-exists").html(data);
alert("test2");
event.preventDefault();
return false;
})
.fail(function() {
alert( "error" );
});

There is no alert when submitting a form using ajaxForm plugin

How can I have an alert that the form has been submitted successfully? I have already tried to look at the page of the plugin still come up empty handed.
This is the code I have tried so far maybe there is something wrong with my syntax:
<script type="text/javascript">
$(document).ready(function(){
$('#f1').ajaxForm({
success: function(){
alert("Form successfully submitted");
}
});
});
</script>
The code above works and successfully inserted all the data in the forms but the alert that suppose to appear after successfully submitted the form is missing for some reason.
This is the script that the form uses when submitting:
<?php
$title=$_REQUEST['articletitle'];
$articlemore=$_REQUEST['editor1'];
include "connection.php";
if (isset($_FILES['image']) && $_FILES['image']['size'] > 0)
{
$type=$_FILES['image']['type'];
// Temporary file name stored on the server
$tmpName = $_FILES['image']['tmp_name'];
// Read the file
$fp = fopen($tmpName, 'r');
$data = fread($fp, filesize($tmpName));
$data = addslashes($data);
fclose($fp);
$query = "INSERT INTO blog(articletitle, articleimage, articlemore) VALUES ('$title', '$data', '$articlemore')";
$results = mysqli_query($link, $query);
if(!$results)
{
echo "Saving Post Failed";
}
else
{
echo "You have a new Post!";
}
}//end if that checks if there is an image
else
{
echo "No image selected/uploaded";
}
// Close our MySQL Link
mysqli_close($link);
?>
Here is the Syntax
// wait for the DOM to be loaded
$(document).ready(function() {
// bind 'myForm' and provide a simple callback function
$('#myForm').ajaxForm(function() {
alert("Thank you for your comment!");
});
});
I hope this will help you
Change this:
$('#f1').ajaxForm({
to
$('#f1').ajaxForm(function(){

Automatically Show If Username Available With JQuery

I am trying to see if a username has already been taken in a mysql database and it does not seem to want to work. Ideally it would show as I was typing on the form. Any help would be greatly appreciated as I do not see anything wrong with the code.
On my main page is the code for the jquery, javascript and html.
The corresponding page is testusername.php.
<script type="text/javascript">
$(document).ready(function() {
$('#feedback').load('testusername.php').show();
$('#username_input').keyup(function() {
$.post('testusername.php', { username:form.username.value },
function(result) {
$('#feedback').html(result).show();
});
});
});
</script>
<form name='form'>
<fieldset>
<legend>Test Form</legend>
Username: <br /><input type='text' id='username_input' name='username'></input>
</fieldset>
</form>
<div id = "feedback"></div>
testusername.php is:
<?php
include 'functions2.php';
?>
<?php
$username = mysql_real_escape_string($_POST['username']);
$query1a = mysql_query("SELECT * FROM users WHERE username='$username'");
$count = mysql_num_rows($query1a);
if ($count==0)
{
echo "Available";
}
else {
echo "Username exists";
}
?>
This script should work to handle your client side part, Assuming you have jQuery loaded to your pafe properly.
<script type="text/javascript">
$(document).ready(function() {
$('#username_input').keyup(function() {
$.post('testusername.php', { username: $(this).val() },function(result){
$('#feedback').html(result).show();
});
});
});
</script>
For the server side, dont use * in the query. You may use something like SELECT 1 FROM .... Also you may want to make sure you are not going to be a victim of SQL Injection.

Categories

Resources