Ajax call and PHP form submission not working together? - javascript

I am facing an issue while sending the data through the PHP script, in Index.php there is a form with some field values and a JavaScript script included in the Index.php which posts an image after I submit the form in Index.php with help of ajax, but Image is not posting/sending through ajax, only form field submission works.
If I call only Ajax during the time of form submission that is working or if I submit the form value all alone working, but if I call together the image is not working.
Index.php
<form enctype="multipart/form-data" method="post" action="saveRecord.php">
<?php include ('imagecropinterface/index.html'); ?>
<div>
<input autocomplete="off" type="text" maxlength="90" placeholder="HeadLine" id="headline" name="headline" style="width:386px;">
</div>
<div class="mt-2">
<input autocomplete="off" type="text" maxlength="90" name="subtitle" placeholder="Sub Title" style="width:386px;">
</div>
<div>
<input id='jour' type='text' value="" class=''>
</div>
<div>
<textarea name="fullText" placeholder="Synopsis" style="width:386px;"></textarea>
</div>
<input class="btn btn-secondary" name="save" id="btnid" value="Save" type="submit">
</form>
index.html
const downloadAllBtn = document.getElementById("btnid");
downloadAllBtn.addEventListener("click", downloadAll);
function downloadAll() {
$.ajax({
type: "POST",
url: "/ap-beta2/saveRecord.php",
data: {
data: imagesBase64,
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
}
saveRecord.php
if (isset($_POST['save']) && isset($_POST['data'])) {
echo ($_POST[data]);
echo ($_POST['headline']);
echo ($_POST['subtitle']);
}
How can I submit the form so that form value and ajax call POST together to the PHP page?
As suggested by #ADyson I have updated Ajax script, unfortunately, no progress!!
In the form, I put the id saveform
<form enctype="multipart/form-data" id = "saveform" method="post" action="saveRecord.php">
function downloadAll() {
$("#saveform").click(function (e) {
$.ajax({
type: "POST",
url: "https://myimpact.in/ap-beta2/saveRecord.php",
data: {
data: imagesBase64,
},
cache: false,
error: function (err, data) {
console.log("There was an error. Try again please!" + data, err);
},
success: function (data) {
console.log(data);
},
});
e.preventDefault();
});
}

Related

Form input field not recognized in jquery

I have this search form to post using jQuery:
<form id="search-article-form" method="post">
<input type="hidden" name="token" value="LSN71T8CeWr">
<input id="searcharticle" type="text" placeholder="search..."
name="searcharticle">
</form>
jQuery snippet:
$(function () {
$('#searcharticle').keyup(function() {
var form = $('#search-article-form');
console.log('form:', form.serialize());
$.ajax({
type: "POST",
url: "/search/article/",
data: form.serialize(),
success: searchSuccess,
dataType: 'html'
});
});
});
function searchSuccess(data, textStatus, jqXHR) {
console.log('data:', data);
$('#search-results').html(data);
}
The problem is that the form does not seem to be serialized properly, so on keyup I see only this in the console:
form: token=LSN71T8CeWr
Also on the server side, the received post parameters is empty.
So wondering what is wrong here and how to fix it?
Works fine in the attached snippet
$(function () {
$('#searcharticle').keyup(function() {
var form = $('#search-article-form');
console.log('form:', form.serialize());
});
});
function searchSuccess(data, textStatus, jqXHR) {
console.log('data:', data);
$('#search-results').html(data);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="search-article-form" method="post">
<input type="hidden" name="token" value="LSN71T8CeWr">
<input id="searcharticle" type="text" placeholder="search..."
name="searcharticle">
</form>

i want to send file to api url and get the response without redirecting to it using ajax

the code below is form with action api link
and thats my ajax request
$('#form1').submit(function(e) {
$.ajax({
type: "POST",
url: "http://www.example.com/uploader",
data: formdata,
success: function(data) {
alert(data);
}
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://www.example.com/uploader" id="myForm" method="post" name="myForm">
NDA DOC: <input type="file" name="file1">
<input type="submit" id="submit">
</form>
when i send a file to that api it respond with data i want to get this data without redirecting to it this code in wordpress site
You need to add enctype in form tag and use preventDefault to prevent the refresh of page.
You need to serialize the data and send in data.
On the success area you need to deal with response.
HTML
<form action="http://www.example.com/uploader" id="form1" method="post" name="myForm" enctype="multipart/form-data">
NDA DOC: <input type="file" name="file1">
<input type="submit" id="submit">
</form>
JS
$('#form1').submit(function(e){
e.preventDefault();
let data = $( this ).serialize()
$.ajax({
type: "POST",
url: "http://www.example.com/uploader",
data: data,
success: function(response){
// success action here
},
error: function(response) {
// error action here
}
});
});
You just need to add the following code to your function in your submit event.
e.preventDefault();
because, normally it would submit the form.

Form submit issues using jQuery and Ajax

Actually I have 2 questions about form submit using jQuery and Ajax.
Currenlty, I am validating a login form using jQuery/Ajax request. I want to disabled the login submit button after logged in successfully completed. So that I am using following .js code but it's not disabled the submit button.
Questions
a) what is the issue in my js code ? why it's not disable the login submit button after logged in successfully ?
b) Using jQuery/Ajax for login is safe for security ? If not what I need to to and Should I add server side validation too ?
Thanks a lot :)
.js code for login :
// Login form
function login_form (element,event){
e= $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
url: 'login_process',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data == '<div class="alert alert-success"><strong>Successfully logged!.</strong></div>') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
Login Process php page :
It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo '<div class="alert alert-success">';
echo '<strong>Successfully logged!.</strong>';
echo '</div>';
}
Html form :
<div class="container bellow-nav">
<div class="row">
<div class="col-md-6 content-area">
<h3>Login</h3>
<hr/>
<form role="form" method="post" id="login_form">
<div class="form-group">
<label for="email">Email addresse</label>
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<label for="pwd">Password</label>
<input type="password" name="pwd" class="form-control" placeholder="Password">
</div>
<div class="form-group">
<input type="hidden" name="_token" value="<?php echo $form_token; ?>">
<input type="submit" name="submit" value="LOGIN" class="btn btn-booking" id="login_bottom" onclick="login_form(this,event);" >
</div>
<div class="form-group validation_msg">
</div>
<div class="fomr-group">
<label for=""><p>Forgot password?</p></label> |
<label for=""><p>Don't have an account? <a href="signup">Join now</p></label>
</div>
</form>
</div>
</div><!--main row-->
</div><!--main container end-->
One reason could be that the data may have some leading or trailing spaces.
You can extract only the text message from the data and use that for comparison
if ($(data).text().trim() == 'Successfully logged!.') {
$('#login_form')[0].reset();
$("#login_bottom").prop("disabled", true);
} else {
$("#login_bottom").prop("disabled", false);
}
For the second part, I assume the server side login is using a secured cookie to store the authentication information is so yes it is secured.
Use json response insted of HTML
Login Process php page : It's return following message after successfully logged :
if(login($email, $user_pwd) == true) {
echo json_encode(['message'=>'Success'])
}
$.ajax({
url: 'login_process',
type: 'POST',
dataType: 'JSON',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function () {
$('#login_bottom').val('Validating...');
$("#login_bottom").attr("disabled", true);
},
success: function (data) {
$('.validation_msg').html(data);
$('#login_bottom').val('LOGIN');
$("#login_bottom").attr("disabled", false);
if(data.message == 'Success') {
$('#login_form')[0].reset();
$("#login_bottom").attr("disabled", true);
}
},
data: formData,
cache: false,
contentType: false,
processData: false
});
First and for most, YOU MUST ADD SERVER SIDE VALIDATIONS. JavaScript can be disabled on the browser and your validations will be disabled when that happens. Javascript can also be edit on the browser and your validations will be useless js validations is only good for user friendly feeling and not for security.
All you have to do is set the disabled attribute to disabled value
$("#login_bottom").attr("disabled","disabled");
However I don't think you are going inside that if. you should console log something and make sure you are passing the if statement.

How to call return false in ajax requests page?

How to call return false; in ajax requests page ?
First, When i press submit button , It's will call return checkform(this);
And in function checkform ( form ) will use ajax post to page test.php
In test.php can i use return fales; for break form id="f1"
I tested but not work, How can i do that ?
index.php
<form method="post" action="" ENCTYPE = "multipart/form-data" onsubmit="return checkform(this);" id="f1">
<label>
Your Username
</label>
<input type="text" name="username" id="username">
<br>
<label>
Your Password
</label>
<input type="password" name="password" id="password">
<br>
<input name="submit" type="submit" value="Sign in"/>
<span id="mySpan_username_password"></span>
</form>
<script language="JavaScript" type="text/javascript">
function checkform ( form )
{
$.ajax
(
{
url: 'test.php',
type: 'POST',
data: $('#f2').serialize(),
cache: false,
success: function (data) {
$('#mySpan_username_password').html(data);
}
}
)
}
</script>
<form id="f2">
<input type="text" name="username_send_value" value="xx"/>
<input type="text" name="password_send_value" value="yy"/>
</form>
test.php
<script>
return faalse;
</script>
You can return an error response to your ajax request e.g. 404.
test.php
<?php
header('HTTP/1.0 404 Not Found');
?>
This happens because your checkform method shoots an ajax call and just move on. It doesn't wait for the ajax response, this is because of the default async behavior of ajax call.
In order to fix it, first you need to decide whether you want the ajax call async or not.
if async:false
function checkform ( form )
{
var response=false;
$.ajax({
url: 'test.php',
type: 'POST',
async:false,//just add async:false here
data: $('#f2').serialize(),
cache: false,
success: function (data) {
$('#mySpan_username_password').html(data);
response=true;
}
});
return response;
}
if async:true
pass callback as parameter and handle code in callback.
function checkform ( form ,callback)
{
var response=false;
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#f2').serialize(),
cache: false,
success: function (data) {
$('#mySpan_username_password').html(data);
callback(true);
}
error: function(data){
callback(false);
}
});
}
Method call:
checkform(form,function(response){
if(response===true)
//....
else
//...
});

How to upload file using jquery ajax and php (without clicking any submit button)

I have a form like this:
<form method="post" class="form_cnvc">
<p><input type="text" name="f_nm" value="" placeholder="type your first name"></p>
<p><input type="text" name="l_nm" value="" placeholder="type your last name"></p>
<div class="dropfile visible-lg">
<input type="file" id="image_file_input" name="image_file_input">
<span>Select Images(.jpg , .png, .bmp files) </span>
</div>
<p class="submit"><input type="submit" name="submit" value="post"></p>
</form>
I want that when the user will selects an image, it would be automatically submitted to my PHP page so that I can save it in the database and return an insert_id with the thumbnail of the picture.
I want to do it using jQuery but not able to do so.
PHP code is:
Easy, use a change trigger on your input Element and do an ajax-request inside:
$("#image_file_input").change(function() {
$.ajax({
url: "my-target-url.php",
type: "post",
dataType: 'json',
processData: false,
contentType: false,
data: {file: $("#image_file_input").val()},
success: function(text) {
if(text == "success") {
alert("Your image was uploaded successfully");
}
},
error: function() {
alert("An error occured, please try again.");
}
});
});
Create a url or route and enter it at url: tag (domain/file.php) and then code serversided stuff:
function processFileUpload() {
if(count($_FILES) > 0) {
foreach($_FILES as $file) {
//DO whatever you want with your file, save it in the db or stuff...
//$file["name"];
//$file["tmp_name"];
//Insert here bla blubb
echo "success";
}
}
die();
}

Categories

Resources