Tell me please, there is a form for sending data to the database. Without a script it works fine, but nothing happens with the script. In the console — Form Data has all the data, and the 200th code arrives, but is not added to the database.
PHP:
<?php
$data = $_POST;
if (isset($data['add'])) {
$posts = R::dispense('posts');
$posts->head = $data['head'];
$posts->desc = $data['desc'];
R::store($posts);
}
?>
HTML:
<form method="POST" id="FormID">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
JS:
<script>
$("#FormID").submit(function(e)
{
var form = $(this);
var url = form.attr('action');
e.preventDefault();
$.ajax({
type: "POST",
url: url,
data: $("#FormID").serialize(),
success: function(data)
{
c = "hello";
$('#FormStatus').text(c);
}
});
});
</script>
You said:
if (isset($data['add'])) {
So the code only does anything if add in the data.
<button type="submit" name="add">Добавить</button>
add is a submit button. It will be included in the data when you submit the form.
data: $("#FormID").serialize(),
You aren't submitting the form. jQuery serialize does not include submit buttons because they aren't successful controls when you aren't submitting the form.
Use some other mechanism to determine if there is data to process (such as the presence of head and desc.
You have forget the action for your form
Why don't simply use $data['name'] instead of R::dispense?
If you what to do a POST request why don't you use $.post()?
What you need is these:
PHP Code:
<?php
$data = $_POST;
if (isset($data['add'])) {
if(isset($data['head']) AND !empty($data['head']) AND isset($data['desc']) AND !empty($data['desc'])) {
$head = htmlspecialchars($data['head']);
$desc = htmlspecialchars($data['desc']);
echo "Hello from server";
}
else {
echo "Please fill the form";
}
}
?>
HTML:
<form method="POST" id="FormID" action="path_to_php_file.php">
<input type="text" name="head" required />
<input type="text" name="desc" required />
<button type="submit" name="add">Добавить</button>
</form>
JS:
<script>
$("#FormID").submit(function(e)
{
e.preventDefault();
var form = $(this),
url = form.attr('action');
var data = {};
// To have post paramaters like
// { 'head' : 'Head value', 'desc' : 'Desc value' }
$.each(form.serializeArray(), function(i, field) {
data[field.name] = field.value;
});
$.post(url, data, function(Responses) {
// Will write "Hello from server" in your console
console.log(Responses);
});
});
</script>
Related
I am trying to send my form data to an .php file with AJAX but JS is misbehaving
, what actually happens is that when i leave the input fields empty every thing works fine (i.e. the php program executes and make changes in my database as expected) but when i fill form data , like when i fill name , email ,password my client side page refreshes and php file dosent gets executed .
Sorry for any grammatical mistakes .
I appreciate any help from anyone !
Thanks alot !
var form = document.getElementById("form_signup");
var formdata = new FormData(form);
$('#form_signup').on('submit', function(ev) {
console.log(formdata);
ev.preventDefault();
$.ajax({
url: "./process_php/Signup1.php",
data: $('form').serialize(),
cache: false,
processData: false,
contentType: false,
type: "POST",
success: function(response) {
console.log("done" + response);
}
});
return false;
});
<?php
if (!isset($_REQUEST['username'])) {
die();
}
$username = "temp_username";
$email = "temp_email";
$password = "temp_password";
$sqlconnection = new mysqli("", "", "", "");
$insertstatement = "INSERT INTO new_users (Name , Email , Password , Subscriber ) VALUES ('$username' , '$email' , '$password' , 'Normal' ) ";
if ($sqlconnection->query($insertstatement) === TRUE) { //if entered into db successfully
echo "DONE";
}else {
//run js to inform
}
?>
<!--I have loaded jquery and also my external js file-->
<form class="font1" id="form_signup">
<!-- main content , signup form -->
<h2 id="form_name" class="font1">LOGIN</h2>
<input type="text" name="username" placeholder="Username" minlength="3" autofocus id="username"><br>
<input type="email" name="email" placeholder="Email" minlength="10"><br>
<input type="password" name="pass" placeholder="Password" minlength="8"><br>
<input type="submit" value="Confirm">
</form>
Seems problem with $('form').serialize(). Here form is not the one same as var form = document.getElementById("form_signup");
$('#form_signup').on('submit', function(ev) {
console.log(formdata);
ev.preventDefault();
$.ajax({
url: "./process_php/Signup1.php",
data: $('#form_signup').serialize(),
// rest of the code
I want to use Acymailing Joomla! component installed at example.com/mailer to manage subscriptions from non Joomla site on example.com
In that case I have simple script
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize(),
success: function () {
swal('Great success!');
}
});
});
});
and form
<form class="form-inline" action="https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub" method="post">
<div class="form-group">
<label class="sr-only" for="user_name">Email address</label>
<input id="user_name" type="text" name="user[name]" value="" class="form-control" placeholder="Email">
</div>
<div class="form-group">
<label class="sr-only" for="user_email">Password</label>
<input id="user_email" type="text" name="user[email]" value="" class="form-control" placeholder="Password">
</div>
<button type="submit" class="btn btn-default">Sign Up!</button>
<input type="hidden" name="user[html]" value="1" />
<input type="hidden" name="acyformname" value="formAcymailing1" />
<input type="hidden" name="ctrl" value="sub"/>
<input type="hidden" name="task" value="optin"/>
<input type="hidden" name="redirect" value="https://example.com"/>
<input type="hidden" name="option" value="com_acymailing"/>
<input type="hidden" name="visiblelists" value=""/>
<input type="hidden" name="hiddenlists" value="1"/>
</form>
Everything works fine except success, error states...
Joomla Acymailing have sub.php file to handle ajax responses
if($config->get('subscription_message',1) || $ajax){
if($allowSubscriptionModifications){
if($statusAdd == 2){
if($userClass->confirmationSentSuccess){
$msg = 'CONFIRMATION_SENT';
$code = 2;
$msgtype = 'success';
}else{
$msg = $userClass->confirmationSentError;
$code = 7;
$msgtype = 'error';
}
}else{
if($insertMessage){
$msg = 'SUBSCRIPTION_OK';
$code = 3;
$msgtype = 'success';
}elseif($updateMessage){
$msg = 'SUBSCRIPTION_UPDATED_OK';
$code = 4;
$msgtype = 'success';
}else{
$msg = 'ALREADY_SUBSCRIBED';
$code = 5;
$msgtype = 'success';
}
}
}else{
if($modifySubscriptionSuccess){
$msg = 'IDENTIFICATION_SENT';
$code = 6;
$msgtype = 'warning';
}else{
$msg = $modifySubscriptionError;
$code = 8;
$msgtype = 'error';
}
}
if($msg == strtoupper($msg)){
$source = acymailing_getVar('cmd', 'acy_source');
if(strpos($source, 'module_') !== false){
$moduleId = '_'.strtoupper($source);
if(acymailing_translation($msg.$moduleId) != $msg.$moduleId) $msg = $msg.$moduleId;
}
$msg = acymailing_translation($msg);
}
$replace = array();
$replace['{list:name}'] = '';
foreach($myuser as $oneProp => $oneVal){
$replace['{user:'.$oneProp.'}'] = $oneVal;
}
$msg = str_replace(array_keys($replace),$replace,$msg);
if($config->get('redirect_tags', 0) == 1) $redirectUrl = str_replace(array_keys($replace),$replace,$redirectUrl);
if($ajax){
$msg = str_replace(array("\n","\r",'"','\\'),array(' ',' ',"'",'\\\\'),$msg);
echo '{"message":"'.$msg.'","type":"'.($msgtype == 'warning' ? 'success' : $msgtype).'","code":"'.$code.'"}';
}elseif(empty($redirectUrl)){
acymailing_enqueueMessage($msg,$msgtype == 'success' ? 'info' : $msgtype);
}else{
if(strlen($msg)>0){
if($msgtype == 'success') acymailing_enqueueMessage($msg);
elseif($msgtype == 'warning') acymailing_enqueueMessage($msg,'notice');
else acymailing_enqueueMessage($msg,'error');
}
}
}
And JSON looks like on Joomla side registration to the same form by index.php?option=com_acymailing&ctrl=sub
message Subscribe confirmed
type success
code 3
{"message":"Subscribe confirmed","type":"success","code":"3"}
The question is: how to obtain that submission statuses success, error, already submbited etc on external submission form (at example.com page)?
this simple change may do it for you:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: $('form').serialize()
}
}).done(function (data) {
swal('Great success!');
});
});
});
I personally like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
swal('Great success!');
});
since your result is in JSON, that should be more like:
$.post("https://example.com...", {
data: $('form').serialize()
}, function(data) {
console.log(data); // shows full return object in console
swal('Great success!');
}, "json");
Try the following, I have explained the changes inside comments:
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var formdata = $(this).serializeArray(); //i really prefer serializeArray better than serialize (up2u)
$.ajax({
type: 'post',
dataType: 'json', //because your data is json
url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
data: formdata,
success: function (d) {//d is the return/response of your url (your question answer)
swal(
d.type+': '+d.code ,
d.message,
d.type
);
},
error: function(d){
swal(
'Oops..' ,
'Something went wrong!', //your json must be in trouble
'error'
);
console.log(d); //delete this in production stage
console.log(d.responseText); //i add this so you will know what happenned exactly when you get this error. delete this too in production stage
}
});
});
});
I don't feel your ajax had issues, what i can see from the Joomla php code, everytime when you request that joomla URL you will always get a response header status code as 200, so your javascript will always land on success block of ajax code, returning with some json based message, when i checked the joomla acymaling (version 5.8.1 for joomla 3.8.3) code for that controller, i saw on line number 74 they are checking if the request is made using ajax, but missing Access-Control-Allow-Origin in php header which will restrict your outside call so you can replace this if condition from :
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
}
to
if($ajax){
#ob_end_clean();
header("Content-type:text/html; charset=utf-8");
header("Access-Control-Allow-Origin: *");
}
so to allow calls from any other domain as well, but do remember this can also cause vulnerabilities to you joomla code. also you need to change your HTML form as well add one more hidden field in your HTML :
<input type="hidden" name="ajax" value="1" />
so to allow ajax request by your joomla controller file.
now in your success block of ajax you can make a check something like this :
success:function(data, status, xhr){
var json = $.parseJSON(data);
swal(json.message, json.type);
}
I hope this will help you in acomplishing what you want to, Happy coding.
I also face this type of problem.for solving this type of problem i Put a variable in the success as argument html.
e.g. success(html)
and
console.log(html)
this shows all errors including notices and all. turn on errore_reporting['E_ALL'];. and do not set dataType to 'json' .
Simple solution to your question is :
success: function (data) {
$("#<id_of_tag>").html(data);
}
data : Response returned from the server to your AJAX call
id_of_tag : where you want to display your returned output.
Its just an example, you can decide, what kind of data you want to return and what you want to do with your response.
To answer your question: On Success parameter in function will contain your response.
As in my case, i am returning another JSP page, which i want to display in div tag.
Also check below link : I think it might help you
Best way to check if AJAX request was successful in jQuery
The problem I've been trying to solve for hours and hours now is following: I cannot stop the redirecting of #myform action after the data has been submitted succesfully to database. I've tried multiple methods but none seem to work. I'm in dire need of help!
The code:
Html(mainview.php):
<div id="submitAccordion">
<form id="myForm" action="userFiles.php" method="post">
Name: <input type="text" name="accordionName" /><br />
<input id="sub" type="submit" name="go" />
</form>
<span id="result"> </span>
</div>
Javascript(mainview_script.js):
$("#sub").click(function () {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function () {
return false;
});
php(userFiles.php):
session_start();
require_once 'database.php';
if ( isset($_SESSION['user_id']) ) {
$sql = "INSERT INTO useraccordion (id, h3) VALUES (:id, :accordion)";
$stmt = $conn->prepare($sql);
$stmt->bindParam(':id', $_SESSION['user_id']);
$stmt->bindParam(':accordion', $_POST['accordionName']);
if ( $stmt->execute() ) {
echo "Succesfully inserted";
} else {
echo "Sorry, there was an error";
}
}
I have tried ajax method, prevent.default etc, but none work!
Either change your input type to button
<input id="sub" type="button" name="go" value="Submit"/>
Or try this:
$("form").submit(function(e){
e.preventDefault();
});
First, move your $("#myForm").submit(... out of the click event so it is it's own thing. Then, pass in e into that function. So it would look like this...
$("#myForm").submit(function(e) {
e.preventDefault();
return false;
});
$("#sub").click(function() {
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),data, function(info) {
$("#result").html(info);
});
});
That will fix your immediate problem. My thought is... Do not even use a form for this. There is no reason to. You are posting the data via Ajax, so there is no reason to have a form that would submit. I would do something like this...
HTML...
<div id="form">
<div class="form-item">
<label for="name">Name:</label>
<input name="name" id="name" type="text" />
</div>
<button id="sub">Submit Form</button>
</div>
Javascript...
$("#sub").click(function() {
var postData = {};
//this is here to be dynamic incase you want to add more items....
$("#form").find('input').each(function() {
postData[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: "YOUR URL HERE",
type: "POST",
data: postData,
success: function(msg) {
$("#result").html(msg);
}
});
});
It is sufficient to prevent deafult action on sub:
$("#sub").click(function (e) {
e.preventDefault();
var data = $("#myForm :input").serializeArray();
$.post( $("#myForm").attr("action"),
data, function(info) {
$("#result").html(info); } )
});
$("#myForm").submit(function (event) { event.preventDefault(); });
That should stop the submission
If you are submitting your form data via ajax or jquery then you should change your input type form 'submit' to 'button' type
<input id="sub" type="button" name="go" value="go"/>
I am fetching php json encoded data using ajax and then setting values to form input then sending it to other page . But json fetched values does not post to other page while normal input values are posting . Here's the code i am using . Your help will be highly appriciated .
`
if(isset($_POST['send_mail'])){
header('Content-Type: application/json');
$out = array('a'=>"Volvo", 'b'=>"BMW", 'c'=>"Toyota");
echo json_encode($out);
//print_r($out);
exit();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function send_mail_test(){
var txt = $("#test_txt").val();
if( txt !=""){
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType: "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data){
document.getElementById('code_r').setAttribute('value', data.a);
}
});
//return false;
}
else alert("please enter some text");
//return false;
}
</script>
<form method="post" action="sub.php" name="myform" onSubmit="return send_mail_test()">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>`
sub.php
<?php
print_r($_POST);
?>
UPDATE
I am using onclick on button in another form and trying to change action page from there and then submitting form to that action is that possible ??
<script>
function action(){
var str = location.href;
var x = "feedback.php?page="+str;
$("#quick_query").attr("action", x);
$('#quick_query').submit();
}
</script>
<form id="myform" method="post" action="">
<input type="button" onclick="action()">
</form>
It is changing the action but doesn't submit the form ? how can i achieve it that will be of great help.
ANSWER UPADTED:
The problem with your code is that the submit event occurs even before ajax is called. The following changes have been done in your code
HTML
<form method="post" action="sub.php" name="myform" id="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="button" name="_mail" value="send" onclick="return send_mail_test()" >
</form>
<br><hr><br>
<form method="post" action="xyz.php" name="anotherform" id="anotherform">
<input type="button" name="change" value="Change action of above form" onclick="changeformaction();" >
</form>
The onsubmit on the form is removed & the submit button is changed to normal button. The send_mail_test() function is called on the Send button now.
JAVASCRIPT
<script>
function send_mail_test() {
var txt = $("#test_txt").val();
if (txt != "") {
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType : "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data) {
$('#code_r').val(data.a);
$('#myform').submit();
}
});
}else{
alert("please enter some text");
return false;
}
}
function changeformaction(){
$("#myform").prop('action','newaction.php');
$('#myform').submit();
}
</script>
Here a small change is made in ajax success callback , after the response is received and the value is set in the input , the form is made to submit then.
No change is needed in your ajax file.
Try this:
<script>
$(function () {
$('form[name="myform"]').on('submit', function (e) {
e.preventDefault();
var txt = $(this).find("#test_txt").val();
if (txt.length > 0) {
$.ajax({
url: "chckvar.php",
type: "POST",
//async : false,
dataType: "JSON",
data: {
send_mail: 1,
txt_val: txt
},
success: function (data) {
$('#code_r').attr('value', data.a); //$('#code_r').val(data.a);
$(this).submit()
}
});
} else alert("please enter some text");
});
});
</script>
<form method="post" action="sub.php" name="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>
Form:
<form action="" id="register" method="post">
<input type="text" placeholder="eg. John">
<input type="text" placeholder="eg. Appleseed">
<input type="text" placeholder="youremail#domain.com">
</form>
JS:
$('form#register').on('submit',function (e) {
$.ajax({
url: 'submit.php',
cache: false,
type: 'POST',
context: this,
data : $(this).serialize(),
success: function(json) {
console.log("json: " + json);
}
});
e.preventDefault();
});
PHP:
$formData = json_encode($_POST);
echo print_r($formData,1);
... after filling the form and hitting submit, it does submit the form without an error, but the data returned (JSON) is empty:
json: []
What am I doing wrong?
This is because you are not using name attribute in your fields
serialize()
Requires name field in your form
1:-
$formData = json_encode($_POST);
echo print_r($formData,1);
should be :-
$formData = json_encode($_POST);
echo $formData;
2.You are not having name attribute in your form fields. please provide that otherwise serialize() will not work correctly.