Getting undefined value while submitting form through ajax - javascript

I have a form from the front end that I am trying to submit to backend using ajax.
<form method="post" enctype="multipart/form-data" id="form_post">
<input type="hidden" name="name" id="name" class="name" value="ABC">
<input type="hidden" name="location" id="location" class="location" value="XYZ">
<textarea class="c-textarea desc" name="desc" id="desc" placeholder="Type your description"></textarea>
<input type="file" id="file" class="file" name="file" >
</form>
<script type="text/javascript">
$("#form_post").submit(function()
{
var formData = new FormData();
$f2 = $('#file');
formData.append('file', $f2.get(0).files[0]);
formData.append('name', name.value);
formData.append('location', location.value);
formData.append('desc', desc.value);
jQuery.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" + "class/send_data",
data: formData,
processData: false,
contentType: false,
success: function(res)
{
alert(res);
console.log(res);
},
error: function(errResponse)
{
console.log(errResponse);
}
});
return false;
});
</script>
In alert i am getting the value for desc but for name and location it is getting as undefined.
On backend i am fetching the values using following code
$data = array(
'name' = $this->input->post('name')
'location'->input->post('location')
'desc'->input->post('desc')
);
Can anyone please tell how i can fetch the values

As per my comment, you need to access the values sent via ajax using $_POST
<?php
$name = $_POST['name'];
$location = $_POST['location'];
echo $name.''.$location;
?>
EDIT
Change your data key in ajax call to
data: new FormData(this),

Related

How to pass an array of "FormData" via ajax and access in Laravel controller

# I just want to know how to send this array the controller by requete ajax
var dataPanier=[];
function addarray(objser)
{
dataPanier.push(objser);
}
$('.target').click(function() {
var btn_name=$(this).attr("name");
switch(btn_name) {
case 'FormPVC':
var dataformPVC = new FormData(),
form_data = $('#'+btn_name).serializeArray();
$.each(form_data, function (key, input) {
dataformPVC.append(input.name, input.value);
});
dataformPVC.append('Fichier', $('#File_PVC')[0].files[0]);
/* function addarray push dataform in array*/
addarray(dataformPVC);
break;
.
.
.
more . . .
I am attempting to send multiple forms data as an array by ajax to a Larave controller.
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: array ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
$("#btnTest").click(function(){
var formData = $('#frm1, #frm2').serialize();
console.log(formData);
$.ajax({
method: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="frm1">
<input name="n1" type="text"/>
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<form id="frm2">
<input name="n1" type="text" />
<input name="n2" type="hidden" value="test2"/>
<input name="n3" type="hidden" value="test3"/>
</form>
<input type="button" id="btnTest" value="send"/>
As your already using jQuery for the AJAX request, you could use the serialize() function. This supports multiple form elements, so it is possible to do:
var formData = $('#form1, #form2').serialize();
$.ajax({
type: 'POST',
url: 'lsitedevis',
data: formData ,
success: function(data) {
toastr.success('Successfully added Post!', 'Success Alert', {timeOut: 5000});
}
});
You might want to ask yourself why you have multiple forms but submitting them all as a single request. If it's for visual purposes, it might be easier to have a single form and separate the contents using other markup elements such as a <fieldset> or <div>.

How to send image file from local machine to server using jquery ajax request

I have an html form with input type = file, I have a link to API to store images to cloud. In this feature, a user can upload a file from his local machine and upload it to the server. The server returns the cloud url of the uploaded image. In postman it is working fine, but when using with jquery I am not able to figure out how to accomplish this. In postman There are several parameters set like filename, tag and employeeID. In file name field there is choose file button and form-data radio button is checked.
This is my jquery code so far
$("#test-btn").on("click", function() {
$.ajax({
url: 'myURL/external/upload',
type: 'POST',
headers: {
"appID": "some value",
"version": "some value",
"empID": "some value",
"contentType": "application/x-www-form-urlencoded"
},
data: new FormData($("#test-form")),
processData: false,
contentType: false,
success: function() {
console.log(data)
},
error: function(e) {
console.log(e)
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form enctype="multipart/form-data" method="post" name="upload-image" id="test-form">
<input type="file" name="filename" />
<input type="text" name="tag" value="some value" />
<input type="text" name="empID" value="some value" />
</form>
<button id="test-btn">make</button>
I've replaced the confidential fields with dummy values.
$("form#test-form").submit(function(){
var formData = new FormData(this);
$.ajax({
url : 'myURL/external/upload',
type : 'POST',
data: formData,
async: false,
// your other config, params
success : function(){console.log(data)},
error : function(e){console.log(e)}
});
return false;
});
or you can try:
<form enctype="multipart/form-data" method="post" name="upload-image" id="test-form" action="myURL/external/upload">
<input type="file" name="filename" />
<input type="text" name="tag" value="some value" />
<input type="text" name="empID" value="some value" />
</form>
<button id="test-btn">make</button>
$("form#test-form").submit(function() {
var formData = new FormData($(this)[0]);
$.post($(this).attr("action"), formData, function() {
// success
});
return false;
});

Sending data to php file AJAX

So I have a target. It's to have a live area where you type in a username and every time you let a key go onkeyup() in the input area, I want it to send that data to a php file where that file will return what you just typed in and display it out where I want it. This isn't going as I like though :P. Please help, and thanks in advance.
JavaScript/jQuery/Ajax Code
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "GET",
url: "php/return.php",
data: user,
cache: false,
success: function(data){
$("#username-display").text(data);
}
});
}
HTML Code
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP Code
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $username;
?>
Please let me know if you need more info to help me solve this...
hey you can use following code
HTML CODE
<script type="text/javascript">
function changeUsername() {
// var user = $("#user").val();
$.ajax({
type: "GET",
url: "s.php",
data: {'user':$("#user").val()},
success: function(data){
$("#username-display").text(data);
}
});
}
</script>
<div class="container" title="Press enter to submit">
<label>What is your name: </label><input type="text" name="user" required="" maxlength="200" id="user" onkeyup="changeUsername();" /> <br />
You typed: <strong id="username-display"></strong>
<strong id="msg"></strong>
</div>
PHP CODE
<?php
$username_vuln = $_GET["user"];
$username = htmlspecialchars($username_vuln);
echo $_GET["user"];
?>
You need to correct your AJAX code also change type from GET to POST in php code so, final code will be like -
function changeUsername() {
var user = $("#user").val();
$.ajax({
url: "data.php",
data: {'user': user},
type : 'post',
success: function (data) {
$("#username-display").text(data);
}
});
}
PHP CODE :-
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo json_encode($username);
Change Get to Post.
function changeUsername() {
var user = $("#user").val();
$.ajax({
type: "POST",
url: "php/return.php",
data: {'user': user},
cache: false,
success: function(data){
alert(data);
$("#username-display").text(data);
}
});
}
Php code first try to get response.
$username_vuln = $_POST["user"];
$username = htmlspecialchars($username_vuln);
echo $username; exit;
Try:
echo( json_encode( $username ) );
exit( 1 );

Saving form value to database through ajax wordpress

How can I save data to database using ajax and form. I have working this for one day but still no luck I don't know what's wrong with this code I came up right now. This is one is wordpress
Here is the code:
This javascript was in the header.php
<form>
<input name="MyUrlName" type="text" class="add_name" id="MyUrlName" placeholder="Name of website">
<input type="button" name="submit" id="MyUrlsubmit" value="Add URL" class="submit">
</form>
jQuery(document).ready(function(){
jQuery("#MyUrlsubmit").click(function(){
var name = jQuery("#MyUrlName").val();
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {"action": "savedata", "MyUrlName":name},
success: function(data){
//alert('success');
console.log(data);
}
});
});
});
Here is the code in function.php
function savedata(){
$name = $_POST['MyUrlName'];
global $wpdb;
$table_name = $wpdb -> prefix . "save_url";
$wpdb->insert(
$table_name, array(
'name' => $_POST['MyUrlName']
),
array(
'%s'
)
);
return true;
exit();
}
add_action('wp_ajax_nopriv_savedata', 'savedata');
add_action('wp_ajax_savedata', 'savedata');
I'm implementing it in frontend
Thank you in advance
use this code
<form>
<input name="MyUrlName" type="text" class="add_name" id="MyUrlName" placeholder="Name of website">
<input type="button" name="submit" id="MyUrlsubmit" value="Add URL" class="submit">
</form>
jQuery(document).ready(function(){
jQuery("#MyUrlsubmit").click(function(){
var name = jQuery("#MyUrlName").val();
jQuery.ajax({
type: 'POST',
url: "<?php echo admin_url('admin-ajax.php'); ?>",
data: {action: "savedata", MyUrlName:name},
success: function(data){
//alert('success');
console.log(data);
}
});
});
});

Send form data with jquery ajax json

I'm new in PHP/jquery
I would like to ask how to send json data from a form field like (name, age, etc) with ajax in a json format. Sadly I can't found any relevant information about this it's even possible to do it dynamically? Google searches only gives back answers like build up the data manually. like: name: X Y, age: 32, and so on.
Is there anyway to do that?
Thanks for the help!
Edit:
<form action="test.php" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input type="submit">
</form>
here is a simple one
here is my test.php for testing only
<?php
// this is just a test
//send back to the ajax request the request
echo json_encode($_POST);
here is my index.html
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="form" action="" method="post">
Name: <input type="text" name="name"><br>
Age: <input type="text" name="email"><br>
FavColor: <input type="text" name="favc"><br>
<input id="submit" type="button" name="submit" value="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
// click on button submit
$("#submit").on('click', function(){
// send ajax
$.ajax({
url: 'test.php', // url where to submit the request
type : "POST", // type of action POST || GET
dataType : 'json', // data type
data : $("#form").serialize(), // post data || get data
success : function(result) {
// you can see the result from the console
// tab of the developer tools
console.log(result);
},
error: function(xhr, resp, text) {
console.log(xhr, resp, text);
}
})
});
});
</script>
</body>
</html>
Both file are place in the same directory
The accepted answer here indeed makes a json from a form, but the json contents is really a string with url-encoded contents.
To make a more realistic json POST, use some solution from Serialize form data to JSON to make formToJson function and add contentType: 'application/json;charset=UTF-8' to the jQuery ajax call parameters.
$.ajax({
url: 'test.php',
type: "POST",
dataType: 'json',
data: formToJson($("form")),
contentType: 'application/json;charset=UTF-8',
...
})
You can use serialize() like this:
$.ajax({
cache: false,
url: 'test.php',
data: $('form').serialize(),
datatype: 'json',
success: function(data) {
}
});
Why use JQuery?
Javascript provides FormData api and fetch to perform this easily.
var form = document.querySelector('form');
form.onsubmit = function(event){
var formData = new FormData(form);
fetch("/test.php",
{
body: formData,
method: "post"
}).then(…);
//Dont submit the form.
return false;
}
Reference:
https://metamug.com/article/html5/ajax-form-submit.html#submit-form-with-fetch
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="joe#gmail.com" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.

Categories

Resources