Append form data into a json file - php

I want to append form data into a json file, here is my code however i'm not sure what I have done wrong. Every time I submit data via post I only get an error response. Where is this code going wrong?
HTML
<form class="ajax form-inline">
<div class="form-group">
<label for="exampleInputAmount">Yo, whats your first name?</label>
<div class="input-group">
<input type="text" class="form-control" id="fname" placeholder="First name">
</div>
</div>
<div class="form-group">
<label for="exampleInputAmount">&& Last name?</label>
<div class="input-group">
<input type="text" class="form-control" id="lname" placeholder="Last name">
</div>
</div>
<button type="submit" class="btn btn-primary">Submit to JSON</button>
</form>
JS/ Jquery
$('form.ajax').on('submit', function(){
var $fname = $("#fname")
var $lname = $("#lname")
var object = {
firstname: $fname.val(),
lastname: $lname.val(),
}
var params = JSON.stringify(object);
$.ajax({
type: 'POST',
data: params,
dataType: "json",
url: 'save_to_json.php',
success: function(data) {
console.log('success');
},
error: function(data) {
console.log('error');
},
complete: function() {
console.log('complete');
}
});
return false;
e.preventDefault()
});
PHP / save_to_json.php
<?php
if (!isset($_POST['params']) && !empty($_POST['params'])) {
$params = $_POST['params'];
$jsonObject = json_encode($params);
file_put_contents('my_json_data.json', $jsonObject, FILE_APPEND);
}
else {
echo "Noooooooob";
}
?>

First of all, use event.preventDefault() method to stop your form from being submitted.
Here's the reference:
event.preventDefault()
Second, there's no point using var params = JSON.stringify(object); in your code.
And finally, Remove this line dataType: "json", unless you're expecting a json object as response from server. dataType is the type of data that you're expecting back from the server.
So your jQuery script should be like this:
$(document).ready(function(){
$('form.ajax').on('submit', function(e){
e.preventDefault();
var $fname = $("#fname");
var $lname = $("#lname");
var params = {
firstname: $fname.val(),
lastname: $lname.val(),
}
$.ajax({
type: 'POST',
data: params,
url: 'save_to_json.php',
success: function(data) {
console.log('success');
},
error: function(data) {
console.log('error');
},
complete: function() {
console.log('complete');
}
});
return false;
});
});
And this is how you can process the AJAX request,
<?php
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
$params = array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname']);
$jsonObject = json_encode($params);
file_put_contents('my_json_data.json', $jsonObject, FILE_APPEND);
}
else {
echo "Noooooooob";
}
?>
Edited:
Based on your requirement you should process the AJAX request like this:
<?php
if (isset($_POST['firstname']) && isset($_POST['lastname'])) {
$params = array('firstname' => $_POST['firstname'], 'lastname' => $_POST['lastname']);
$jsonObject = json_encode($params);
$json = file_get_contents('my_json_data.json');
if(empty($json)){
$jsonObject = json_encode(array('username' => [$jsonObject]));
file_put_contents('my_json_data.json', $jsonObject);
}else{
$json = json_decode($json, true);
$newJson = $json['username'][0] . "," . $jsonObject;
$jsonObject = json_encode(array('username' => [$newJson]));
file_put_contents('my_json_data.json', $jsonObject);
}
}
else {
echo "Noooooooob";
}
?>

Related

Post and display data on the same page using PHP (MVC) AJAX

I'm trying to post input data and display it on the same page (view_group.php) using AJAX but I did not understand how it works with MVC, I'm new with MVC if anyone could help me it would be very helpful for me.
view_group.php
<script type = "text/javascript" >
$(document).ready(function() {
$("#submit").click(function(event) {
event.preventDefault();
var status_content = $('#status_content').val();
$.ajax({
type: "POST",
url: "view_group.php",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {}
});
});
}); </script>
if(isset($_POST['postStatus'])){ $status->postStatus($group_id); }
?>
<form class="forms-sample" method="post" id="form-status">
<div class="form-group">
<textarea class="form-control" name="status_content" id="status_content" rows="5" placeholder="Share something"></textarea>
</div>
<input type="submit" class="btn btn-primary" id="submit" name="submit" value="Post" />
</form>
<span id="result"></span>
my controller
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
}
first in the ajax url you must set your controller url , then on success result value will be set on your html attribute .
$.ajax({
type: "POST",
url: "your controller url here",
data: {
postStatus: postStatus,
status_content: status_content
},
success: function(result) {
$('#result).text(result);
}
});
Then on your controller you must echo the result you want to send to your page
function postStatus($group_id){
$status = new ManageGroupsModel();
$status->group_id = $group_id;
$status->status_content = $_POST['status_content'];
if($status->postStatus() > 0) {
$message = "Status posted!";
}
echo $status;
}

$_POST data is not passing to my function in Wordpress via AJAX

I have created an AJAX function in Wordpress. The function is called on form submission. The function is run, but it is not receiving any of the form data that I have submitted. What am I missing?
PHP Function
I have added the PHP function here, which is called successfully via AJAX. This form creates a new user successfully, but only when I create the variables manually (eg. see $new_user_data['user_login'] = 'This Text Works';). For some reason, the $_POST data isn't coming through to the function.
add_action("wp_ajax_register_user", __NAMESPACE__ . "\\register_user");
add_action("wp_ajax_nopriv_register_user", __NAMESPACE__ . "\\register_user");
function register_user() {
// NONCE VERIFICATION
if ( !wp_verify_nonce( $_REQUEST['nonce'], "rtr_register_nonce")) {
exit("Oops! This is embarassing!");
}
// Get all post data for the user.
$new_user_data = array();
$new_user_data['first_name'] = sanitize_text_field($_POST['first-name']);
$new_user_data['last_name'] = sanitize_text_field($_POST['last-name']);
$new_user_data['user_email'] = $_POST['email'];
$new_user_data['user_pass'] = sanitize_text_field($_POST['password']);
$new_user_data['user_login'] = 'This Text Works';
$new_user_data['role'] = 'subscriber';
// Create the User
$registered_user = wp_insert_user( $new_user_data );
$result['user'] = $registered_user;
// AJAX CHECK
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$result = json_encode($result);
echo $result;
} else {
header("Location: ".$_SERVER["HTTP_REFERER"]);
}
die();
}
JQuery
function registerUser(){
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
function nextPrev(n) {
// This function will figure out which tab to display
var x = document.getElementsByClassName("form-tab");
// Exit the function if any field in the current tab is invalid:
if (n === 1 && !validateForm()) {
return false;
}
// Hide the current tab:
x[currentTab].style.display = "none";
// Increase or decrease the current tab by 1:
currentTab = currentTab + n;
// if you have reached the end of the form... :
if (currentTab >= x.length) {
//...the form gets submitted:
//document.getElementById("regForm").submit();
registerUser();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
$('#nextBtn').click(function () {
nextPrev(1);
});
$('#prevBtn').click(function () {
nextPrev(-1);
});
Form
<?php
$nonce = wp_create_nonce("rtr_register_nonce");
$link = admin_url('admin-ajax.php?action=register_user&nonce='.$nonce);
?>
<form id="regForm" <?php echo 'data-nonce="' . $nonce . '"'; ?> action="<?php echo $link; ?>" method="post" enctype="multipart/form-data">>
<div class="my-3 text-center">
<span class="form-step">1</span>
<span class="form-step">2</span>
</div>
<div class="form-tab">
<p><input name="first-name" placeholder="First Name" oninput="this.className = ''"></p>
<p><input name="last-name" placeholder="Last Name" oninput="this.className = ''"></p>
<p><input name="dob" type="date" oninput="this.className = ''"></p>
</div>
<div class="form-tab">
<p><input name="email" type="email" placeholder="Email" oninput="this.className = ''"></p>
<p><input name="password" type="password" placeholder="Password" oninput="this.className = ''"></p>
</div>
<div style="overflow:auto;">
<div style="float:right;">
<button type="button" class="btn btn-brand" id="prevBtn">Previous</button>
<button type="button" class="btn btn-brand" id="nextBtn">Next</button>
</div>
</div>
</form>
Seems you are not triggering registerUser() check following script works fine for me
jQuery(document).ready(function($) {
jQuery('body').on('click', '#nextBtn', function() {
registerUser();
});
});
function registerUser(){
var nonce = jQuery('#regForm').attr("data-nonce");
var formData = jQuery('#regForm').serialize();
jQuery.ajax({
url: ajaxurl,
type: 'post',
dataType: 'json',
data : {action: 'register_user', nonce: nonce, formData: formData},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
}
add method="post" to your 'form' - 'get' is the default https://stackoverflow.com%2Fquestions%2F2314401%2Fwhat-is-the-default-form-http-method&usg=AOvVaw1dKc3hW4K6r5SwQurLztBw
The "user_login" is a username of the user so probably it doesn't accepts space too.
See also WP Insert Post
Please try passing some username such as "custom_user" and see the result.
Hope this might work.
Ok it was a bit of help from everyone here. But yes, I was calling the AJAX correctly, but not actually submitting the form. I added a .on(submit) to the form and then added a listener to the form to perform the AJAX call on submit. Here's the amendments below.
function nextPrev(n) {
var x = document.getElementsByClassName("form-tab");
if (n === 1 && !validateForm()) {
return false;
}
x[currentTab].style.display = "none";
currentTab = currentTab + n;
if (currentTab >= x.length) {
// ADDED THIS SUBMIT() HERE
document.getElementById("regForm").submit();
return false;
}
// Otherwise, display the correct tab:
showTab(currentTab);
}
// ADDED AN EVENT LISTENER TO TRIGGER THE AJAX CALL HERE
$('#regForm').on('submit', function () {
var nonce = $('#regForm').attr("data-nonce");
var formData = $('#regForm').serialize();
$.ajax({
url: rtr_register_user.ajaxUrl,
type: 'post',
dataType: 'json',
data: {
action: 'register_user',
nonce: nonce,
formData: formData
},
success: function (response) {
console.log(response);
$('#regForm').html('Your form has been submitted successfully');
},
});
});

AJAX submit form data fails. It works using $_GET when i turn off e.preventdefault

This is my first post here. Sorry if my English appears to be bad.
I attempted to use the following codes to submit form data to my signup/submit/index.php.
Here is my sample HTML
<form name="signup_form" id="signup_form" action="submit">
<input type="text" class="form-control" placeholder="CreateUsername" name="username" id="username" autocomplete="off">
<input type="password" class="form-control" placeholder="CreatePassword" name="password" id="password"></form>
Here is my Ajax
.on('success.form.fv', function(e) {
e.preventDefault();
loadshow();
var $form = $(e.target),
fv = $form.data('formValidation');
// Use Ajax
$.ajax({
url: $form.attr('action'),
type: 'POST',
data: $('#signup_form').serialize(), //or $form.serialize()
success: function(result) {
// ... Process the result ...
//alert(result);
if (result=="2")
{
swal({
type: "success",
title: "HiHi!",
text: "GoodLuck",
animation: "slide-from-top",
showConfirmButton: true
}, function(){
var username = $("#username").val();
var password = $("#password").val();
functionA(username,password).done(functionB);
});
}
else (result=="agent_na")
{
swal({
type: "error",
title: "ERROR",
text: "N/A",
animation: "slide-from-top",
showConfirmButton: true
});
Here goes my PhP
<?php
$params = array();
$gett = $_POST["username"];
parse_str($gett,$params);
print_r ($gett); // it prints an empty array
print_r ($gett); // it prints an empty array
echo $params["username"] // it shows undefined username index
?>
I have attempted to serialize $gett before parse_str it. It returns me (){}[].
Could please assist me on this?? I spent almost 20 hours on this, google and tried a lot. Am new to JS.
I try to keep it simple
HTML
<!-- Include Jquery Plugin -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="signup_form">
<input type="text" name="username" placeholder="Enter the user name" />
<input type="password" name="password" placeholder="Enter password here" />
<input type="submit" value="Login" />
</form>
<script>
/* Page loaded */
$(function(){
/* Trigger when the form submitted */
$("#signup_form").submit(function(e) {
var form = $(this);
$.ajax({
type: "POST",
url: "backend.php",
data: form.serialize(), // Checkout the document - https://api.jquery.com/serialize/
success: function(data) {
// handle the return data from server
console.log(data);
}
});
e.preventDefault();
return false;
})
})
</script>
PHP (backend.php)
<?php
// Always check param exists before accessing it
if(isset($_POST['username']) && isset($_POST['password'])){
// Print all the post params
print_r($_POST);
// or by param
// echo "User Name: " . $_POST['username']. " <br />";
// echo "Password: " . $_POST['username']. " <br />";
}
?>
Hope this helps!
This is a sample of how you can debug an ajax call:
Javascript:
$(function(){
$("#signup_form").submit(function(e) {
var formData = new FormData($(this));
$.ajax({
type: "POST",
url: "backend.php",
data: formData,
success: function(data) {
console.log(data);
// if (data.length > 0) ....
}
});
e.preventDefault();
return false;
});
});
PHP:
<?php
if (isset($_POST['signup_form'])){
$params = array();
$gett = $_POST['username'];
parse_str($gett,$params);
print_r ($gett);
echo $_POST['username'];
}else{
die('No $_POST data.');
}
?>
Your php code had some problems in it, you missed a semi-colon and you tried to print from an empty array, calls through ajax won't show any run time errors, and thus you need to be very careful when you're trying to debug an ajax to php call.
Hope this helps.

Serialize form data to PHP

I've inherited some PHP code, never having worked with it before, and I'm stuck. I've tried to use echo like I would console.log() in JS, but I'm hardly getting into the script.
I'm trying to post 3 input values and a select option to PHP code, and email that information off to someone. Fairly simple I would assume.
HTML
<form method="post" class="contact-form" id="register-form">
<fieldset>
<input type="text" name="first_name" placeholder="First Name" class="col-xs-12 col-sm-12 col-lg-12 input-text" id="firstName" required>
<input type="text" name="last_name" placeholder="Last Name" class="col-xs-12 col-sm-12 col-lg-12 input-text" id="lastName" required>
<input type="text" name="location_preference" placeholder="Location Preference" class="col-xs-12 col-sm-12 col-lg-12 input-text" id="locationPreference" required>
<select name="internType" style="width: 100%; display: block; color: #000;" id="internType" required>
<option selected="" value="default">Please Select</option>
<option value="inside">Inside</option>
<option value="outside">Outside</option>
<option value="open">Open</option>
</select>
<button name="submit" type="submit" class="btn btn-success submitinformation pull-right" id="submit"> Submit</button>
<button name="reset" type="reset" class="btn btn-success submitinformation pull-right" id="reset"> Reset</button>
</fieldset>
</form>
Pretty basic..
JavaScript
var PATH = 'processor.php';
var APP = 'wse01010';
$("#register-form").on("submit", function(e){
e.preventDefault();
var errors = 0;
var inputs = $('input:text, #internType');
$(inputs).map(function(){
if( !$(this).val() || $(this).val() == "default") {
$(this).addClass('warning'); //Add a warning class for inputs if Empty
errors++;
} else if ($(this).val()) {
$(this).removeClass('warning');
}
});
var formData = $(this).serialize();
console.log(formData);
//console.log($(this)[0]);
//var formData = new FormData( $(this)[0] );
//console.log(formData);
if(errors < 1) {
// If no errors, send POST
$.ajax({
url: PATH + '?i=' + APP,
type: 'POST',
data: formData,
async: true,
success: function (data) {
alert("Success");
},
error: function(xhr, textStatus, errorThrown){
alert('Request failed. Please try again.');
}
});
}
});
This alerts Success every time.
PHP
$firstName = $_POST['first_name'];
if( !isset( $_POST['first_name'] ) ) {
var_dump($_POST); // This gives me an empty array: array(0) { }
$outcomeArr = array(
'outcome'=>'failure',
'message'=>'Step 1 failed.'
);
echo json_encode( $outcomeArr );
exit();
}
unset( $_POST['submit'] );
$postVar = print_r($_POST,true);
//Other code omitted
Here's how the data is being passed.
I'm not sure how to get my Form Data into the correct format (if that's the issue), or why PHP isn't recognizing my POST. I'm also not sure of any other checks I should be doing to validate the POST.
This is the JavaScript that ended up working for me
var form_processor = {
settings : {
'outcome' : -1,
'status' : 0, // 0 == correct, 1 == errors detected
'error_msg' : '',
'path' : 'processor.php',
'app' : 'wse01010'
},
sendData : function(formData){
var self = this;
$.ajax({
url: self.settings.path + '?i=' + self.settings.app ,
type: 'POST',
data: formData,
async: true,
success: function (data) {
toastr.success('Your request went through!', "Success")
},
error: function(xhr, textStatus, errorThrown){
toastr.error("Something went wrong. Please try again.", "Error!")
},
cache: false,
contentType: false,
processData: false
});
},
bindForm : function(){
var self = this;
$('.contact-form').submit(function(e){
self.settings.formObj = $(e.target);
e.preventDefault();
var errors = 0;
var inputs = $('input:text, #internType');
$(inputs).map(function(){
if( !$(this).val() || $(this).val() == "default") {
$(this).addClass('warning'); //Add a warning class for inputs if Empty
errors++;
} else if ($(this).val()) {
$(this).removeClass('warning');
}
});
if( errors > 0 ) {
self.settings.status = 0;
self.settings.error_msg = '';
toastr.error("Please fill in all of the fields.", "Error!")
return false
} else {
formData = new FormData( $(this)[0] );
self.sendData(formData);
}
});
},
init : function(){
this.bindForm();
}
}
form_processor.init();
In your PHP, you start off with this:
echo "1";
When using AJAX, an echo is the same as a return, so this is where your function stops. Remove all unnecessary echo's or your function will simply not continue.
Furthermore, you are using spaces in your HTML name attributes:
<input type="text" name="first name"> <!-- Incorrect -->
Use underscores instead or you will not be able to retrieve the value properly:
<input type="text" name="first_name"> <!-- Correct -->
Afterwards, $firstName = $_POST["first_name"]; is the correct way to retrieve your values in PHP.
I recommend to not use space in name so change that in firstname etc.
for serializing u need this.
$(function() {
$('#register-form').on('submit', function(e) {
var data = $("#register-form").serialize();
$.getJSON("http://YOUR PHP FILE TO CATCH IT &",data)
});
});
on your php page use $_GET['firstname'] for example and add that to a variable.
Your code is setting the content type of the form twice, and both times incorrectly:
Drop enctype="multipart/form-data" from the <form> tag. (This is for file uploads)
Drop contentType: "application/json; charset=utf-8" from the jQuery ajax() call. (This is for JSON, which PHP does not understand natively)
The correct encoding is application/x-www-form-urlencoded, which is the default value for both the <form> tag and the ajax() call.

jquery/php form in modal window

I have a form in a modal window. When I submit the form through ajax I don't get the success message. My aim is to see the message created in the php file in the modal after submitting the form. Here is the code:
<p><a class='activate_modal' name='modal_window' href='#'>Sign Up</a></p>
<div id='mask' class='close_modal'></div>
<div id='modal_window' class='modal_window'>
<form name="field" method="post" id="form">
<label for="username">Username:</label><br>
<input name="username" id="username" type="text"/><span id="gif"><span>
<span id="user_error"></span><br><br>
<label for="email">Email:</label><br>
<input name="email" id="email" type="text"/><span id="gif3"></span>
<span id="email_error"></span><br><br>
<input name="submit" type="submit" value="Register" id="submit"/>
</form>
</div>
The modal.js
$('.activate_modal').click(function(){
var modal_id = $(this).attr('name');
show_modal(modal_id);
});
$('.close_modal').click(function(){
close_modal();
});
$(document).keydown(function(e){
if (e.keyCode == 27){
close_modal();
}
});
function close_modal(){
$('#mask').fadeOut(500);
$('.modal_window').fadeOut(500);
}
function show_modal(modal_id){
$('#mask').css({ 'display' : 'block', opacity : 0});
$('#mask').fadeTo(500,0.7);
$('#'+modal_id).fadeIn(500);
}
The test.js for the registration of the user
$(function() {
$('#form').submit(function() {
$.ajax({
type: "POST",
url: "test.php",
data: $("#form").serialize(),
success: function(data) {
$('#form').replaceWith(data);
}
});
});
});
And the PHP FILE
<?php
$mysqli = new mysqli('127.0.0.1', 'root', '', 'project');
$username = $_POST['username'];
$email = $_POST['email'];
$mysqli->query("INSERT INTO `project`.`registration` (`username`,`email`) VALUES ('$username','$email')");
$result = $mysqli->affected_rows;
if($result > 0) {
echo 'Welcome';
} else {
echo 'ERROR!';
}
?>
Try putting the returncode from your AJAX call into
$('#modal_window')
instead of in the form
$('#form')
BTW: Why not use the POST or GET method of jQuery? They're incredibly easy to use...
Try something like this.
First write ajax code using jquery.
<script type="text/javascript">
function submitForm()
{
var str = jQuery( "form" ).serialize();
jQuery.ajax({
type: "POST",
url: '<?php echo BaseUrl()."myurl/"; ?>',
data: str,
format: "json",
success: function(data) {
var obj = JSON.parse(data);
if( obj[0] === 'error')
{
jQuery("#error").html(obj[1]);
}else{
jQuery("#success").html(obj[1]);
setTimeout(function () {
jQuery.fancybox.close();
}, 2500);
}
}
});
}
</script>
while in php write code for error and success messages like this :
if(//condition true){
echo json_encode(array("success"," successfully Done.."));
}else{
echo json_encode(array("error","Some error.."));
}
Hopes this help you.

Categories