Form reloading page without sending the data on submit - javascript

here's my code.
In my .js file:
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = '';
params += 'action=Send';
params += '&title='+title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
}
else
{
return true;
}
}
And in my index.php file:
<form action="" method="post" name="myform" id="myform"" >
Title: <input class="" type="text" name="title" value="" id="title"/> <br>
<input type="submit" value="Submit" onClick="javascript:Sendit();return false; ">
</form>
<?php
if ($_REQUEST["action"]=='Send')
{
$title = $_REQUEST["title"];
$sql = "INSERT INTO ...
$retval = $mysqli->query($sql, $conn);
if(! $retval ) {
echo('Could not enter data insert: ' . mysql_error());
}
else
{
//inform that everything went well
}
?>
This does not send a thing when the sunmit button is clicked. In fact, you can click the button until the end of the day that nothing happens (not even a message in the debugger)
If I delete the return false; from the onClick in the button, I click on the button and the page reloads even without filling in the title input which has to be filled in.
Ajax's success does not alert a thing and in both cases, nothing gets inserted in my database.
The insert query is correct, I've checked it.
Any ideas on how to send the data and validate?
Thanks

Use below Code to send req.
function Sendit()
{
bValidate = validateField();
if(bValidate)
{
var title = $("#title").val();
theUrl = 'index.php';
params = {};
params["action"] = 'Send';
params["title"] = title;
$.ajax ({
url: theUrl,
data: params,
async:true,
success: function (data, textStatus)
{
//do smth
alert('went well');
}
,
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
}
}

your validateField() function never returns true, so your if(bValidate) will never run. Javascript functions return undefined unless you explicitly return something, try this:
function validateField()
{
var title = document.getElementById('title').value;
if(!title.match(/\S/))
{
//do some alerting
return false;
} esle {
return true;
}
}

Related

e.PreventDefault and ajx submit not working together [return true] is not working

I have a function to check whether email exist, but I want to submit the form only if the email doesn't exist
So I wrote following function:
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
return true;
$(this).submit();
}
}
});
});
Now if it return true also i cant submit the form . Please help.
i saw this question and answer e.preventDefault doesn't stop form from submitting . But no effect
Notes
even i tried
if(response.status=='true') { $("#form-1").submit(); } .
But this also not working
The return statement is returning before the form is submitted
if(response.status == 'true') {
//return true; // returns before the form is submitted
$(this).submit();
return true; // move return after submit
}
Suggestion
You are thinking about this, the wrong way, let PHP handle the checking and insert in the backend.
First Solution
In your PHP do something like
$querycheck = mysqli_query($con,"SELECT * FROM Persons");
$countrows = mysqli_num_rows($querycheck );;
if($countrows == '1')
{
echo json_encode(['message' => 'Sorry This Email Already Used']);
}
else
{
// insert statement here
echo json_encode(['message' => 'Submitted']);
}
In your JS
$("#form-1").on("submit",function(e){
e.preventDefault();
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
alert(response.message); // display the message here to the user.
}
});
});
Second Solution
save the form in a variable.
$("#form-1").on("submit",function(e){
e.preventDefault();
const form = $(this); // get the current form
var given_email=document.getElementById("email");
var data = $("#form-1").serialize();
$.ajax({
type : 'POST',
url : 'check.php',
data : data,
beforeSend: function() {
$(".submit").val('sending ...');
},
success : function(response) {
var response = JSON.parse(response);
if(response.status=='error'){
alert("Sorry This Email Already Used ");
return false;
} if(response.status=='true') {
form.submit(); // submit the form here
return true;
}
}
});
});

how to pass #model.ApplicationId from html form to js

I am trying to make an auto save function that will save the form data. I am unable to pass my ApplicationId in from form to JS in order to auto save. Though with the fixed id, auto saving does work. I have the following code:
Js Code:
window.setInterval(AutoSaveDraft(id), 50000);
function AutoSaveDraft(id) {
$.post({
url: "/Application/Edit/"+id ,
data: $("#application-form").serialize()
}).done(function(data, textStatus, jqXhr) {
if (jqXhr.status === 200) {
alert("Data Application has been saved");
return true;
}
});
}
Html CODE:
<form asp-action="Edit" id="application-form" name="#Model.ApplicationId" >
...
</form>
Basically, I want the #Model.ApplicationId to be passed to my Js, so that I can use that in my Autosaving function.
Let's say you have your JS on the same page as your html, you could simply write:
window.setInterval(function () {
var id = '#Model.ApplicationId'; // Turned C# to JS here
AutoSaveDraft(id);
}, 50000);
function AutoSaveDraft(id) {
$.post({
url: "/Application/Edit/"+id ,
data: $("#application-form").serialize()
}).done(function(data, textStatus, jqXhr) {
if (jqXhr.status === 200) {
alert("Data Application has been saved");
return true;
}
});
}
Now let's say your JS is somewhere else:
HTML:
<form asp-action="Edit" id="application-form" name="#Model.ApplicationId" >
...
</form>
JS:
window.setInterval(function () {
var id = $("#application-form").attr('name'); // Retrieve the ID
AutoSaveDraft(id);
}, 50000);
function AutoSaveDraft(id) {
$.post({
url: "/Application/Edit/"+id ,
data: $("#application-form").serialize()
}).done(function(data, textStatus, jqXhr) {
if (jqXhr.status === 200) {
alert("Data Application has been saved");
return true;
}
});
}
That's said, I would suggest you to use data- attribute to pass that kind of data. Let's try with data-application-id.
<form asp-action="Edit" id="application-form" data-application-id="#Model.ApplicationId">
...
</form>
window.setInterval(function () {
var id = $("#application-form").data("application-id"); // Retrieve here
AutoSaveDraft(id);
}, 50000);
First off, your interval is wrong. What you are doing is calling a function and passing the result to the interval. You need to pass it a function that it can then call when needed. You are calling your function right away.
Next, all you need to do, is to use jQueries attr() method like so:
let id = 'application-form'
window.setInterval(() => AutoSaveDraft(id), 5000);
function AutoSaveDraft(id) {
let name = $(`#${id}`).attr('name')
console.log(name)
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form asp-action="Edit" id="application-form" name="#Model.ApplicationId">
</form>

Successful ajax script doesn't give me response

The general problem is that I cannot get back echo or return through ajax from another file.The alert(msg) is empty. Does that prevent.default stop sending the GET? I am not very fluent in programming, could you please help me in this?
I have my simple form:
<form class='findAndBlock1' method="GET" action="">
<input type='text' name="nameToBlock1" placeholder=" who do you want to block?" class='nameInput'>
<input type='submit' value="Search" class='submitInput1'>
</form>
After clicking it, the ajax script starts:
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg);
},
error : function(error) {
alert('error');
}
});
});
</script>
It is directed to the script that is routed like this:
Route::any('/searchFriendsToBlock', 'SettingsController#searchFriendsToBlock');
Here is the script that is run through ajax:
public function searchFriendsToBlock() {
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
echo "hello";
return Response::json($newArr);
}
Use dataType parameter in ajax request as you are sending response in json format the default dataType is set to html in jQuery.ajax()
<script>
$(".submitInput1").click(function(){
event.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "/searchFriendsToBlock",
data: {
},
success : function(msg) {
alert(msg.type);
},
error : function(error) {
alert('error');
}
});
});
</script>
And Your script should be like this
public function searchFriendsToBlock()
{
$q = Input::get('nameToBlock');
if (strlen($q) < 3)
return null;
$users = DB::table('users')->where //here goes some long request
$response = array();
foreach ($users as $user) {
if (!$user->f_first_name_public)
$user->first_name = "";
if (!$user->f_last_name_public)
$user->last_name = "";
$user->avatar = User::getUserAvatar($user->id);
$user->id = "";
$user->type = "user";
$newArr[] = $user;
}
$response['type'] = 'sussess';
$response['data'] = $newArr;
return Response::json($response);
}

About AJAX , FORM AND PHP

My ajax code looks like this which check the registration form username, email, etc...
jQuery(document).ready(function($) {
$("#formform").on('change', 'input',function(event){
var $form = $(this);
var $inputs = $form.find("input, select, button, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "/registration_check.php",
type: "post",
data: {formData:serializedData},
datetype: "JSON"
});
request.done(function (response, textStatus, jqXHR){
console.log(response);
});
request.fail(function (jqXHR, textStatus, errorThrown){
console.log("error");
});
request.always(function () {
$inputs.prop("disabled", false);
});
event.preventDefault();
});
});
And my PHP look like this:
$get_form_data=$_POST["formData"];
parse_str($get_form_data,$form_data);
if(isset($form_data["username"])){
if(strlen($form_data["username"])<5){
echo "Username must be at least 5 character";
}else{
if(ValidUserName($form_data["username"])){
if($checkUser->checkUserName(char_encoder($form_data["username"]))==true){
echo "Sorry this UserName Already Exist";
}else{
echo "UserName Available";
};
}else{
echo "Invalid Username";
}
}
}
Now How do i disable the form when Invalid Username comes from AJAX as response?
I though i should use return false..but don't know how to handle the response?
try as below format you can handle response in success event:
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
type: "POST",
url: "/registration_check.php",
data: {
formData:serializedData
},
beforeSend: function () {
//do stuff like loading process until you get the response
},
success: function (resp) {
var obj = jQuery.parseJSON(resp);
//console.log(obj); // this will display response in console.
//do stuff here
},
error: function(e){
alert("Error in ajax call: "+e);
}
}); // complete AJAX
PHP CODE:
$array = array();
if (isset($form_data["username"])) {
if (strlen($form_data["username"]) < 5) {
$array['success'] = false;
$array['message'] = "Username must be at least 5 character";
} else {
if (ValidUserName($form_data["username"])) {
if ($checkUser->checkUserName(char_encoder($form_data["username"])) == true) {
$array['success'] = false;
$array['message'] = "Sorry this UserName Already Exist";
} else {
$array['success'] = true;
$array['message'] = "UserName Available";
}
} else {
$array['success'] = false;
$array['message'] = "Invalid Username";
}
}
echo json_encode($array);
}
make your ajax call on form submit event and call event.preventDefault(); if ajax returns any error.
Hope this help :)

jQuery AJAX with PHP to upload contents to MYSQL DB

I am looking for a jQuery AJAX script alongside a PHP script that allows for the storage of information on a button click. The function defined within the jQuery should take three variables, all of which are defined pre-method call. I have the basis of operation complete but at the end of all operations - after the button is clicked and some time has passed - no data is added to the appropriate mysql database.
Here is my jQuery function "store"
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp
success : function() {
alert("WORKED!");
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
}
</script>
Here is the store.php file (very basic I know, I have also yet to secure this script via sanitizing user input)
<?php
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud']) && is_numeric($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld']) && is_numeric($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = strip_tags(stripslashes($_POST['tp']));
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
?>
Assume that I have onclick="store(3, 3, A)" as an attribute for a certain element. How can I fix this? If I remove the onclick attribute how do I pass the necessary parameters to the jQuery function? I appreciate any and all help!
<-- EDIT -->
New jQuery & AJAX Script ...
<script type="text/javascript">
function store(ud, ld, tp) {
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: 'ud='+ud+'&ld='+ld+'&tp='+tp,
error : function() {
alert("error");
},
success : function(data) {
alert(data);
},
complete : function() {
alert("complete");
}
});
}
$(function () {
$("a.rec").on("click", function () {
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
</script>
Revised PHP
<?php
if($_SERVER['REQUEST_METHOD'] === "POST"){
require ('../mysqli_connect.php');
$errors = 0;
if(isset($_POST['ud'])) {
$ud = $_POST['ud'];
} else {
++$errors;
}
if(isset($_POST['ld'])) {
$ld = $_POST['ld'];
} else {
++$errors;
}
if(isset($_POST['tp'])) {
$tp = $_POST['tp'];
} else {
++$errors;
}
if($errors == 0) {
$q = "INSERT INTO table_name (column_1, column_2, column_3, column_4) VALUES ('$ld', '$ud', NOW(), '$tp')";
mysqli_query($mysqli, $q);
} else {
echo 'There was a problem!';
}
} else {
$url = 'http://www.exampledomain.com/error.php';
ob_end_clean();
header("Location: $url");
exit();
}
?>
Now for my HTML
<li>
<div class="sample classes">
<a class="rec" data-ud="13" data-ld="10" data-tp="SCI">
<input type="submit" title="Something" value="Something" />
</a>
</div>
</li>
However, when this button is clicked, it still does not do anything!
As you said onclick is something you are going to want to avoid. This is how you do it.
$(function () { //This function will be ran when the page loads
$(".button-class").on("click", function () { //This will run when any button is clicked
var $this = $(this),
ud = $this.data("ud"),
ld = $this.data("ld"),
tp = $this.data("tp");
store(ud, ld, tp);
});
});
HTML
<input type="button" class="button-class" data-ud="3" data-ld="3" data-tp="A"/>
I find it easier to use JSON and pass variables in an object to the server:
<script>
(function(){
var store = function (ud, lrid, type) {
var data = {
ud:ud,
lrid:lrid,
type:type
};
$.ajax({
url: 'http://www.exampledomain.com/folder/store.php',
type: 'POST',
data: data,
success : function(data) {
alert(data);
},
error : function() {
alert("DIDN'T WORK!");
},
complete : function() {
}
});
};
$('#btn').on('click', function(){
store(1,2,3);
});
}());
</script>
Use this script to test you are getting the variables on the server side:
<?php
# Put this in http://www.exampledomain.com/folder/store.php to test it works
if($_SERVER['REQUEST_METHOD'] === "POST"){
if(
isset($_POST['ud']) &&
isset($_POST['lrid']) &&
isset($_POST['type'])
)
{
$var = $_POST['ud'] . ", ".$_POST['ud'] . ", ".$_POST['type'] ." passed successfully via ajax!";
echo json_encode($var);
}
}
?>

Categories

Resources