JavaScript Misbehaviour - javascript

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

Related

Why jQuery.ajax() is not sending any data?

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>

How to obtain response from form submitted by AJAX?

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

multiple file upload using same form but different input fields using jquery php

I have searched for this thing on stack overflow, I was unable to find a relevant answer to my issue. Please have a look at the code I am using to fetch data and throw it to a php file and upload files to the respective folders and store their link to database. But I am not able to store data. It shows "unable to upload data."
Jquery file:
$(document).on('click','#modalMenu', function(){
var pagename = $("#pagename").val();
var page = 'modalMenu';
var menuname = $("#menuname").val();
var nav = $("#nav").val();
var content = CKEDITOR.instances['content'].getData();
var form_data = new FormData();
var file_data = $('#file').get(0).files[0];
var logo = $('#logo').get(0).files[0];
form_data.append('file', file_data);
form_data.append('logo', logo);
form_data.append('pagename', pagename);
form_data.append('menuname', menuname);
form_data.append('content', content);
form_data.append('nav', nav);
form_data.append('page', page);
$.ajax({
url: 'insert.php', // point to server-side PHP script
//dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
method: 'POST',
success: function(data){
alert(data);
location.reload();
}
});
});
form on some page
<form method="post" role="form" enctype="multipart/form-data" action="javascript:;">
<input type="text" class="form-control" placeholder="Page Name" id="pagename" name="pagename" style="max-width:25%; display:inline" />
<input type="text" class="form-control" placeholder="Nav Name" id="nav" name="nav" style="max-width:25%; display:inline" />
<input type="text" class="form-control" placeholder="Menu Name" id="menuname" name="menuname" style="max-width:25%; display:inline" />
<input type="file" name="logo" id="logo" title="Menu Logo" class="form-control" style="max-width:20%; display:inline"/>
<input type="text" class="form-control" placeholder="Summery Part.. Please make it crisp" id="content" name="content" style="max-width:30%; display:inline" />
<script>
var editor = CKEDITOR.replace( "content", {
uiColor: "#ffffff",
filebrowserBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html",
filebrowserImageBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html?type=Images",
filebrowserFlashBrowseUrl : "../ckeditor-ckfinder-integration/ckfinder/ckfinder.html?type=Flash",
filebrowserUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Files",
filebrowserImageUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Images",
filebrowserFlashUploadUrl : "../ckeditor-ckfinder-integration/ckfinder/core/connector/php/connector.php?command=QuickUpload&type=Flash"
});
CKFinder.setupCKEditor( editor, "../" );
</script>
<input type="file" name="file" id="file" class="form-control" style="max-width:25%; display:inline"/>
<input type="submit" id="modalMenu" name="modalMenu" class="btn btn-success" align="right" value="+" />
</form>
insert.php file
$pageName=$_POST['page'];
if($pageName=='modalMenu'){
$pagename=$_POST['pagename'];
$menuname=$_POST['menuname'];
$nav=$_POST['nav'];
$content=$_POST['content'];
$error=$_FILES['file']['error'];
if($error!=0)
{
echo "Error with File data Upload. File not uploaded, it seems the file is not selected or there is some error with the file or the server seems busy, try later.
We will redirect you back to the dashboard. Please wait..";
}
else
{
$fname=$_FILES['file']['name'];
$ftype=$_FILES['file']['type'];
$fsize=$_FILES['file']['size'];
$ftname=$_FILES['file']['tmp_name'];
$target="../modalMenu/$fname";
$ans=move_uploaded_file($ftname,$target);
if($ans)
{
$error=$_FILES['logo']['error'];
if($error!=0)
{
echo "Error with Image Data Upload. File not uploaded, it seems the file is not selected or there is some error with the file or the server seems busy, try later.
We will redirect you back to the dashboard. Please wait..";
}
else
{
$logo_name=$_FILES['logo']['name'];
$logo_type=$_FILES['logo']['type'];
$logo_size=$_FILES['logo']['size'];
$logo_tname=$_FILES['logo']['tmp_name'];
$target2="../modalMenu/$fname";
$ans=move_uploaded_file($ftname,$target2);
if($ans)
{
//save info to database
$con=mysql_connect("localhost","root","");
mysql_select_db("rcg_db",$con) or die (mysql_error());
$target=addslashes($target);
$query="INSERT INTO `modalmenu`(`pagename`, `nav`, `menuname`, `menulogo`, `content`, `readmore`) VALUES ('$pagename','$nav','$menuname','$target' ,'$content','$target2');";
$n=mysql_query($query);
if($n==1)
{
echo "File upload successful! Data is added. Please wait while page reloads";
}
else
{
echo "File not uploaded, server seems busy, try later. We will redirect you back to the dashboard. Please wait..";
}
}
}
}
else
{
echo "File not uploaded, server seems busy, try later. We will redirect you back to the dashboard. Please wait.";
}
}
}
Thank you in advance. In case I am not using a good way of coding please do recommend and resolve the issue.
From what I understand you want to send the ajax into PHP but PHP cant save it?
Ill give you an example
jQuery
$(#modalMenu).on('click',function(){
var fname = $("#fname").val();
var lname = $("#lname").val();
var age = $("#age").val();
$.ajax({
url: 'insert.php', //point to server-side PHP script
dataType: 'json',
type: "POST",
data:{
"fname" : fname,
"lname" : lname,
"age" : age,
"save" : true
},
success: function(yes){
if(yes.success == true){
window.location.reload(true);
}
}
});
});
PHP
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$age = $_POST['age'];
$sql = "INSERT INTO beneficiary (fname, lname, age)
VALUES ('$fname','$lname','$age')";
$result = mysql_query($sql);
echo json_encode(array(
"success" => true,
));
refer the below link, i think this is useful for you
http://www.codexworld.com/upload-multiple-images-using-jquery-ajax-php/

How to submit attr value and form values with POST using JQuery and PHP?

So I have a form with an input box and an 3 of a type of div that highlights when clicked. I'm trying to get it to submit the attribute and "#email" value and email it to me via PHP.
Here's my HTML:
<form id="form" name="form" class="custompurchase" action="custom.php" method="post">
<input type="email" id="email" name="email" maxlength="40" class="textbox2" placeholder="Email address" required/>
<a class="customoption storage" onclick="activate(this, 'storage');" data-name="500GB HDD">
...
</a>
<a class="customoption storage" onclick="activate(this, 'storage');" data-name="1TB HDD">
...
</a>
<a class="customoption storage" onclick="activate(this, 'storage');" data-name="2TB HDD">
...
</a>
</form>
Here's my JQuery:
$(function() {
var form = $('#form');
$(form).submit(function(event) {
event.preventDefault();
var email = $("#email").val();
var storage = $(".customoptionactive.storage").attr("data-name");
$.ajax({
type: "POST",
url: $(form).attr("action"),
data: email, storage
})
.done(function(response) {
...
});
});
});
And finally my PHP:
<?php
$emailto = "purchases#prismpc.net";
$subject = "Custom PC";
$email = $_POST['email'];
$storage = $_POST['storage'];
$entire = "Email: ".$email."\n"."Storage: ".$storage;
mail($emailto, $subject, $entire);
?>
However, when I see the email, this is all I get:
Email:
Storage:
What am I doing wrong? Do I need to set the dataType? Thank you so much for your answers!
Edit: Different from similar question because it was a simple syntax error.
Change your data option on your $.ajax
data: email, storage
to
data: {email:email, storage:storage}
You may want to use FormData and append custom data to it, as manta pointed it out here: Send FormData and String Data Together Through JQuery AJAX?
var formData = new FormData();
formData.append('storage', $(".customoptionactive.storage").attr("data-name"));
$.ajax({
type: "POST",
url: $(form).attr("action"),
data: formData
})
.done(function(response) {
...
});
this will save you time adding those input values manually

$_POST variables not passed by form

I'm hosting a simple contact form on App Engine using PHP, trying to pass $_POST variables from a form to a PHP script that sends the email. As I can read from the logs, the $_POST variables don't seem to get through and I struggle to understand why... hence would appreciate another pair of eyes on this... thank you. Here are the various bits of (simplified) code:
Within index.html at the root:
<form method="post" action="#" id="contactform">
<div>
<label for="email">Enter your email</label>
<input type="text" class="input-field" id="email" name="email" value="">
</div>
<a id="button-send" href="#" title="Send Email" class="button" style="width:100%;">Send E-Mail</a>
<div id="success">Your message has been sent successfully!</div>
<div id="error">Unable to send your message, please try later.</div>
</form>
The PHP file, also at the root:
<?php
$send_email_to = "test#test.com";
$email_subject = "Email subject line";
function send_email($email,$email_message)
{
// using AppEngine's mail function here
}
function validate($email,$message)
{
// a simple validation function
}
if(isset($_POST['email'])) {
$email = $_POST['email']; // this doesn't seem to work
}
else
{$email = "email#email.com";} // did this to confirm the $_POST didn't seem to be passed
$return_array = validate($email,$message);
if($return_array['success'] == '1')
{
send_email(,$email,$message);
}
header('Content-type: text/json');
echo json_encode($return_array);
die();
?>
And the javascript that controls the error messages:
$('#button-send').click(function(event){
$('#button-send').html('Sending message...');
event.preventDefault();
$('html, body').scrollTo( $('#contact'), 'fast' );
$.ajax({
type: 'POST',
url: 'send_form_email.php',
data: $('#contact_form').serialize(),
success: function(html) {
if(html.success == '1')
{
$('#button-send').html('Send message');
$('#success').show();
}
else
{
$('#button-send').html('Send message');
$('#error').show();
}
},
error: function(){
$('#button-send').html('Send message');
$('#error').show();
}
});
And in case this has to do with App Engine, my app.yaml looks like this:
- url: /js
static_dir: js
- url: /send_form_email.php*
script: send_form_email.php
- url: .*
script: index.html
Many thanks again – I've also put the full code on my Google Drive: https://drive.google.com/file/d/0B4yzSrEzbZ5jbk1oc2RWb2xSRWM/edit?usp=sharing
You are trying to serialise #contact_form but you have id="contactform"
The MIME type for JSON is application/json, not text/json.

Categories