how to submit form as JSON object - javascript

what I am doing is creating a form using JSON this form can then be edited a and produce new JSON object. The problem I am having seems to be with getting the form id.
The code I am using to return a JSON object is:
form = document.forms[0];
$.fn.serializeObject = function()
{
alert("start serializeObject");
var o = {};
var a = this.seralizeArray();
$.each(a, function(){
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
alert(o);
};
$(function() {
alert("here");
form.submit(function(){
result.append(JSON.stringify(form.serializeObject()));
return false;
});
});
This just refresh's the pageI am not sure why.
This program is not on a server and not be used on a server.
by this I mean It is only every going to be run locally on a local machine, with no apache2 setup.
Thanks.

You code can be written pretty easy. This is how I do it:
Ajax:
$('#formID').on('submit',function () {
$.ajax({
url: 'submit.php',
cache: false,
type: 'POST',
data : $('#formID').serialize(),
success: function(json) {
alert('all done');
}
});
});
If you are not sending it with Ajax, why would you do this? If you are simply submitting the form, you can do it using PHP like this:
<?php
$json_object = json_decode($_POST);
?>

$('#formID').on('submit',function (e) {
e.preventDefault();
$.ajax({
url: 'submit.php',
cache: false,
type: 'POST',
data : $('#formID').serialize(),
success: function(json) {
alert('all done');
}
});
});
if you want not redirect or refresh use e.preventDefault();

Related

Issue transferring data from ajax to PHP

I'm trying to send an associative array of key-value pair from client(javascript) to server(php). The size of the array or the values are not fixed. Need to forward the user selected options from one page to another. Not using forms
Tried using ajax, but php does not receive the array correctly. Using php7, jquery 2.4.1, sql server, javascript
javascript/jquery
var contributeArr = {};
$(document).on("change", ".contribute_txt", function() {
// some other code
contributeArr[this.id] = this.value;
});
$('#contri_submit').click(function(e) {
e.preventDefault();
var error = false;
var contributeArray = JSON.stringify(contributeArr);
var url = 'chapter.php';
var formData = new FormData();
if (error == false) {
formData.append("contributeArray", contributeArray);
}
else {
console.log("Something went wrong. Check your code.");
}
for (var pair of formData.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
$.ajax({
type: "POST",
url: url,
data: formData,
cache: false,
processData: false,
contentType: false,
success: function(result) {
window.setTimeout(function() {
window.location.href = url;
}, 2000);
},error: function(xhr,request,error) {
alert(error);
}
});
return false;
});
php
foreach ($_POST['contributeArray'] as $key => $value) {
$_SESSION['contribution'][$key] = $value;
}
print_r($_SESSION['contribution']);
print_r($_POST);
Sample data from console log:
contributeArray, {"LECH":"10","MASC":"20","PMEM":"30","LVME":"50"}
note: not sure what // some other code is... assuming you have everything correct there for your purposes
and assuming you are validating your $_POST data...
var contributeArr = {};
$(document).on("change", ".contribute_txt", function() {
// some other code
contributeArr[this.id] = this.value;
});
$('#contri_submit').click(function(e) {
e.preventDefault();
var my_url_value = 'chapter.php';
var real_url_to_ajax_app = 'https://realdomain.com/realfile.php';
$.ajax({
type: "POST",
url: real_url_to_ajax_app,
data: contributeArr,
success: function(result) {
window.setTimeout(function() {
window.location.href = my_url_value;
}, 2000);
},error: function(error) {
console.log(error);
}
});
return false;
});
in your PHP:
// assuming you are initializing $_SESSION['contribution'] per your needs
foreach ($_POST as $key => $value) {
// validate key/value here
$_SESSION['contribution'][$key] = $value;
}
echo 'some helpful response';
exit; // required
Please use json_decode and include latest jQuery.
I can solve your code if you did not solved yet

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;
}
}
});
});

auto submit form to a url if textfield is not empty

I'm trying to auto submit a form when the username column is not null. i've got my script down there but since i'm new to jquery, i've got it missed up and its not working
$(function() {
var $username = $('#username'),
if ($username != null){
$("#form1").submit,function(event){
event.preventDefault();
data = $(this).serialize();
$.ajax({
type: "POST",
url: "http://mysample.com/ans.php",
data: data,
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="ok"){
window.location = 'page.html';
}
});
});
});
Try to use on change listener, like
$(document).on('change', '#input_id', function(e) {
$('form_selector').submit();
});
$(document).on('submit', 'form_selector', function(e) {
//Your ajax submit logic
});
If you want to do an AJAX submission, just call $.ajax in the if:
$(function() {
var $username = $("#username").val();
if ($username != '') {
$.ajax({
type: "POST",
url: "/ans.php",
data: $("#form1").serialize(),
success: function(data) {
$('#log_msg').html(data);
var result = $.trim(data);
if(result==="ok"){
window.location = 'page.html';
}
});
}
});
You don't need to define a $("#form1").submit() handler for this.

Form Validation with Jquery and AJAX

I am using AJAX with JQUERY to call a PHP script to validate a user email. But, for some reason, the form submits even when it shouldn't. What am I doing wrong? I know the error is for sure not in my PHP.
My Code:
$("#signup").submit(function() {
var error= false;
var dataString = $(this).serialize();
var email= $("#email").val().trim();
if (email != 0) {
// Run AJAX email validation and check to see if the email is already taken
$.ajax({
type: "POST",
url: "checkemail.php",
data: dataString,
async: false,
success: function(data) {
var error= false;
if (data == 'invalid') {
var invalid= 1;
}
else if (data == 'taken') {
var taken= 1;
}
if (invalid == 1) {
alert('invalid email');
error = true;
}
if (taken == 1) {
alert('email taken');
error = true;
}
if (error == true) {
return false;
}
}
});
}
});
Try updating these:
$("#signup").submit(function(e) { //<----pass the event here as "e"
e.preventDefault(); //<----stops the form submission
var error= false;
var dataString = $(this).serialize();
var email= $.trim($("#email").val()); //<----use trim this way
If you absolutely have to use AJAX for form submission, this might be a better way to do it:
$('form').submit({
$.ajax({
type:'post',
url: 'someurl.php',
data: dataString,
context: this, // this here refers to the form object
success:function(data)
{
// perform your operations here
if(something_is_wrong)
{
// show message to user
}
else
{
this.submit(); // put this code in the block where all is ok
}
}
});
return false; // makes sure the form doesn't submit
});

Passing checkbox values as JSON in Jquery

I have an input form which has three text fields and a checkbox input section where the user can select more than one value. I also have an ajax request which sends a POST request to an api. I have written a function to iterate over the form inputs and parse them to JSON, however, it has come to my attention that this wont work for checkbox values. Here is my function:
<script>
console.log(document);
var form = document.getElementById("myform");
form.onsubmit = function (e) {
// stop the regular form submission
e.preventDefault();
// collect the form data while iterating over the inputs
var info = {};
for (var i = 0, ii = form.length; i < ii; ++i) {
var input = form[i];
if (input.name) {
info[input.name] = input.value;
}
addPerson(info);
}
}
function addPerson(info) {
$.ajax({
type: "POST",
url: "http://example.com",
data: JSON.stringify(info),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
alert("success");
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
}
});
}
</script>
I've been trying to get the checkbox values into JSON using
$.each($('input[id="data[i].id"]:checked'), function() {
var value = $(this).val();
qualifications.push(value);
});
but I cant figure out how to add these values to the JSON that is being posted to the server, can anyone help?
Have tried .serialize() and I THINK it is working-
<script>
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$(function() {
$('myform').submit(function() {
$('#result').text(JSON.stringify($('myform').serializeObject()));
return false;
});
});
function addPerson(result){
$.ajax({
type: "POST",
url: "http://example.com",
data: JSON.stringify(result),
contentType: "application/json; charset=utf-8",
crossDomain: true,
dataType: "json",
success: function (data, status, jqXHR) {
alert("success");
},
error: function (jqXHR, status) {
// error handler
console.log(jqXHR);
}
});
}
</script>
If anyone has thoughts/ comments as to how effective the above is, or if there is a better way of doing it, I would like to hear them?
Try this:
var input = form[i];
if (input.name) {
if(input.tagName.toLowerCase() === 'input' &&
(input.type.toLowerCase() === 'checkbox' || input.type.toLowerCase() === 'radio') &&
input.checked)
info[input.name] = input.value;
else
info[input.name] = input.value;
}
addPerson(info);
EDIT:
I suggest using jQuery form.serialize() method as #Drixson OseƱa mentioned.

Categories

Resources