<table>
<tr data-id="1">
<input type="text" name="name_1" value="abc">
<input type="text" name="value_1" value="1">
Edit
</tr>
<tr data-id="2">
<input type="text" name="name_2" value="def">
<input type="text" name="value_2" value="2">
Edit
</tr>
<tr data-id="3">
<input type="text" name="name_3" value="ghi">
<input type="text" name="value_3" value="3">
Edit
</tr>
</table>
function load_edit_row(input) {
var ID = $(input).parent().attr('data-id');
var dataString = [];
$("tr[data-id="+ID+"] :input").each(function(e){
dataString.push(this.value);
});
$.ajax({
type: 'POST',
url: 'update-row.php',
data: dataString,
success: function(itemJson) {
},
dataType: 'json'
});
}
Error post data key and data value, how to fix it?
You could use JSON.stringify(dataString) to encode your array in JavaScript, and then use $array=json_decode($_POST['string']); in your PHP script to retrieve it.
function load_edit_row(input) {
var ID = $(input).parent().attr('data-id');
var dataString = [];
$("tr[data-id="+ID+"] :input").each(function(e){
dataString.push(this.value);
});
var string = JSON.stringify(dataString);
$.ajax({
type: 'POST',
url: 'update-row.php',
data: 'string='+string,
success: function(itemJson) {
}
});
}
Try something like:
function load_edit_row(input) {
var ID = $(input).parent().attr('data-id');
var dataString = [];
$("tr[data-id="+ID+"] :input").each(function(e){
dataString.push(this.value);
});
$.ajax({
type: 'POST',
url: 'update-row.php',
data: {data:dataString},
success: function(itemJson) {
},
dataType: 'json'
});
}
<table>
<tr id="1">
<input type="text" name="name_1" id="1-data1" value="abc">
<input type="text" name="value_1" id="1-data2" value="1">
Edit
</tr>
<tr data-id="2">
<input type="text" name="name_2" id="2-data1" value="def">
<input type="text" name="value_2" id="2-data2" value="2">
Edit
</tr>
<tr data-id="3">
<input type="text" name="name_3" id="3-data1" value="ghi">
<input type="text" name="value_3" id="3-data2" value="3">
Edit
</tr>
</table>
Now the JS:
function load_edit_row(input) {
var dataString = [];
dataString.push($("#"+input+"-data1").val());
dataString.push($("#"+input+"-data2").val());
});
$.ajax({
type: 'POST',
url: 'update-row.php',
data: dataString,
success: function(itemJson) {
},
dataType: 'json'
});
}
You can't simply send a javascript 0-indexed array to POST's Form Data and expect receive it correctly on server side.
Use JSON.stringify(dataString) formatting dataString to a json string and then assign the json string value to a named key like:
var dataString = JSON.stringify(dataString);
$.ajax({
type: 'POST',
url: 'update-row.php',
data: {namedKey: dataString}
success: function(itemJson) {
}
});
On server side, use json_decode decode json back to array :
$data = filter_input(INPUT_POST, 'namedKey');
$dataArr = json_decode($data, true);
Related
I need to send my Front-end data to my server. To do that I create code something like this. But I can't find out send my data to the server using ajax (multipart/form-data)
My HTML Part -
<form id="frmCustomer">
<div>
<label class="form-label" for="customerID">Customer ID</label>
<input class="form-control" id="customerID" name="id" type="text">
</div>
<div>
<label class="form-label" for="customerName">Customer Name</label>
<input class="form-control" id="customerName" name="name" type="text">
</div>
<div>
<label class="form-label" for="customerAddress">Customer Address</label>
<input class="form-control" id="customerAddress" name="address" type="text">
</div>
<div>
<label class="form-label" for="customerSalary">Customer Salary</label>
<input class="form-control" id="customerSalary" name="salary" type="text">
</div>
<div class="form-group">
<label for="inputNICImageCreateAccount"> <i class="tags icon"></i> Image Of Your NIC</label>
<input class="form-control-file" id="inputNICImageCreateAccount" type="file" name="file">
</div>
<div class="btn-group mt-3">
<button class="btn btn-primary" id="btnSave" type="button">Register Customer</button>
<button class="btn btn-info" id="btnSearch" type="button">Search</button>
<button class="btn btn-danger" id="btnRemove" type="button">Remove</button>
<button class="btn btn-warning" id="btnGetAll" type="button">Get All</button>
</div>
</form>
My Ajax Part -
$("#btnSave").click(function () {
let customerID = $("#customerID").val();
let customerName = $("#customerName").val();
let customerAddress = $("#customerAddress").val();
let customerSalary = $("#customerSalary").val();
let NICImage = $('#inputNICImageCreateAccount').val();
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_END_war_exploded/ee/maven/customer",
contentType: 'multipart/form-data',
async: true,
data:,
success: function (data) {
console.log(data)
}
})
})
$("#btnSave").click(function () {
let customerID = $("#customerID").val();
let customerName = $("#customerName").val();
let customerAddress = $("#customerAddress").val();
let customerSalary = $("#customerSalary").val();
let NICImage = $('#inputNICImageCreateAccount').val();
var data = new FormData();
data.append('customerID',customerID);
data.append('customerName',customerName);
data.append('customerAddress',customerAddress);
data.append('customerSalary',customerSalary);
data.append('NICImage',NICImage);
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_END_war_exploded/ee/maven/customer",
contentType: 'multipart/form-data',
async: true,
data:data,
processData: false,
success: function (data) {
console.log(data)
}
});
});
keys setting with FormData should match with your API endPoint parameter names.
to pass data in JSON format rather the Formdata,
$("#btnSave").click(function () {
let customerID = $("#customerID").val();
let customerName = $("#customerName").val();
let customerAddress = $("#customerAddress").val();
let customerSalary = $("#customerSalary").val();
let NICImage = $('#inputNICImageCreateAccount').val();
var formData = {
customerID : customerID,
customerName : customerName,
customerAddress : customerAddress,
customerSalary : customerSalary
};
$.ajax({
method: "POST",
url: "http://localhost:8080/Back_END_war_exploded/ee/maven/customer",
contentType: 'application/json',
async: true,
data : JSON.stringify(formData),
processData: false,
success: function (data) {
console.log(data)
}
});
});
type:'post',
url:url,
dataType:'json',
data:new FormData($('#frmCustomer')[0]),
processData: false,
contentType: false,
cache:false,
async:false,
I have an upload mechanism which looks like that in the View:
<div method="post" enctype="multipart/form-data">
<input type="hidden" id="ProjectId" name="ProjectId" value="#Model.ProjectId"/>
<input type="hidden" id="Name" name="Name" value= "" />
<input type="hidden" id="Id" name="Id" value="" />
<div class="col-md-10">
<div class="form-group">
<input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
<input type="submit" value="Upload" id="UploadInputFileButton" onclick="UploadInstallIntructions();"/>
</div>
</div>
</div>
This is my uploadinstructions() method, which gets called when the user pushes the 'Upload'button.
script>
function UploadInstallIntructions() {
var name = document.getElementById('SoftwareVersionName').value;
var id = document.getElementById("Id").value;
var iFormFile = document.getElementById("ChooseInputFile").files[0];
$.ajax({
type: "POST",
url: '#Url.Action("UploadInputFile", "SoftwareVersion")',
data: { projectId: #Model.ProjectId, Name: name, Id: id, inputFile: iFormFile},
cache: false,
success: function (response) {
window.location.href = response;
}
});
return data;
}
</script>
So this is a simple ajax call that calls a method on my controller with the specified arguments. My problem is that the last argument which should be the file data, of IFormFile type, so that I can work with it in my controller, doesn't get set. Is there a better way I can bind my IFormFile object in my view? Normally just the line :
input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
should have worked to bind the IFormFile.
Edit: Not a duplicate of how to append whole set of model to formdata and obtain it in MVC, because my question was not about binding with FormData, but IFormFile not automattically getting created from the View.
Once i have done upload a image file like this..
$('input[type="file"]').ajaxfileupload({
'action': 'uploadFile.jsp',
'cache': false,
'onComplete': function(response) {
$('#upload').hide();
BootstrapDialog.show({
title: 'Alert!',
message: 'Image Upload Successfully',
buttons: [{
label: 'Ok',
action: function(dialog) {
dialog.close();
}
}]
});
var img_src = "../profilepic/" + response;
setTimeout(5000);
$("#image").attr("src", img_src);
},
'onStart': function() {
$('#upload').show();
}
});
<input type="file" name="datafile" accept="image/*"/><br/>
<div id="upload" style="display:none;">Uploading..</div>
If you wish to upload files like this, visit this link for
jQuery.AjaxFileUpload.js
Try below code:
<form name="UpdateInstall" id="UpdateInstall" method="post" enctype="multipart/form-data">
<input type="hidden" id="ProjectId" name="ProjectId" value="#Model.ProjectId"/>
<input type="hidden" id="Name" name="Name" value= "" />
<input type="hidden" id="Id" name="Id" value="" />
<div class="col-md-10">
<div class="form-group">
<input type="file" asp-for="InputFile" value="test" name="inputfile" onchange="ChooseInputFileButtonChanged(this);" id="ChooseInputFile"/>
<input type="submit" value="Upload" id="UploadInputFileButton" onclick="UploadInstallIntructions();"/>
</div>
</div>
</form>
<script>
function UploadInstallIntructions() {
var formData = new FormData($("#UpdateInstall")[0]);
$.ajax({
type: "POST",
url: '#Url.Action("UploadInputFile", "SoftwareVersion")',
data: formData,
processData: false,
contentType: false,
success: function (response) {
window.location.href = response;
}
});
return data;
}
</script>
I have multiple forms and I want all of them to be processed by a single jquery script, of course I have php functions that work correctly, I tried them separately.
This is my script:
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
My form looks like this
<form id="contacto" name="contacto" method="post" onsubmit="proceso_form('contacto', 'cargando')">
<input type="text" name="name"class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
I think my problem is that I can't put my script in the onsubmit, but honestly I have no idea.
Your html must look like
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form(this, 'cargando')">
...
</form>
And inside the function:
function proceso_form(form, id_div_error){
var $form = $(form);
var url = "my_url.php?form="+$form.attr('id'); //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $form.serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
By passing this to the function you passing the whole form reference.
Hope it will help.
First, it should be:
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
The return keyword there is important.
Next, data: $(this).serialize(), //ID form should be:
data: $('#'+type_form).serialize(), //ID form
So, your script should look like this:
<script type="text/javascript" src="/path/to/jquery.min.js"></script>
<form id="contacto" name="contacto" method="post" onsubmit="return proceso_form('contacto', 'cargando')">
<input type="text" name="name" class="form-control">
<input type="text" name="phone" class="form-control">
<input type="email" name="email" class="form-control">
<textarea style="height:100px;margin-bottom:0px" name="messaje" class="form-control"></textarea>
<input style="margin-top:5px" type="submit" class="btn btn-block" value="SEND">
</form>
<div id="cargando"></div>
<script>
function proceso_form(type_form, id_div_error){
var url = "my_url.php?form="+type_form; //functions
var response = document.getElementById(id_div_error);
response.innerHTML="<img src='img/loader.gif' style='margin-right: 5px;'/>Loading ..."; //
response.style.display='block';
$.ajax({
type: "POST",
url: url,
data: $('#'+type_form).serialize(), //ID form
success: function(data)
{
if (data==1){
window.location.reload();
}else{
response.innerHTML=data; // show PHP response.
}
}
});
return false;
};
</script>
It seems like i cant get to serialize my form. I do get the first alert with lol, but not the second alert with pdata. Does anyone see whats wrong? Im trying to use ajax to send the data in the form. Down below is the script and the html code.
<html>
<head>
<script>
function dologin(event) {
event.preventDefault();
alert("lol");
var pdata = $('#form').serialize();
alert(pdata);
$.ajax({
type: 'POST',
data: pdata,
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
};
</script>
</head>
<body>
<h1>Logg inn</h1>
<form id="form" onsubmit="dologin()">
<div class="form-group">
<label for="email">Epost</label>
<input type="email" class="form-control" name="login" value="" placeholder="Epost">
</div>
<div class="form-group">
<label for="password">Passord</label>
<input type="password" class="form-control" name="password" value="" placeholder="Passord">
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="remember_me">
Husk meg
</label>
</div>
<button type="submit" class="btn btn-default">Logg inn</button>
</form>
<div class="login-help">
<p>Glemt passordet? Trykk her for å endre det.</p>
</div>
</body>
</html>
The problem with your code is, you are accessing event argument wheres there is no parameter passed to the function, so its triggering an error and submitting the form as normal form submission.
If you like to keep your implementation u can modify your code like bellow:
function dologin() {
alert("lol");
var pdata = $('#form').serialize();
alert(pdata);
$.ajax({
type: 'POST',
data: pdata,
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
return false;
};
and modify this line
<form id="form" onsubmit="dologin()">
to
<form id="form" onsubmit="return dologin()">
or can use the following way
$(document).ready(function() {
$('#form').submit(function(e){
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
url: 'LINK',
success: function(data) {
//console.log(data);
alert("YAY");
},
error: function() {
//console.log(data);
alert("NAY");
}
});
});
});
And form tag should be then:
<form id="form">
I don't know what is going on here tonight, but I can't seem to get AJAX working. When the form is submitted, it refreshes the page with the values in the URL. I'm using a validate plugin that has a submit handler, but it still refreshes. I've used this method before and have had no problems. Take a look at the page here and let me know what you think:
http://www.jacobsmits.com/demos/jquery_ajax.html?firstName=&lastName=&email=&message=&contactSubmit=
<div class="demo_content" style="display:none">
<form id="contact_form">
<span class="inputSpan">
<input value="" class="input input1" title="First name" id="firstName" name="firstName" type="text" />
</span>
<span class="inputSpan">
<input value="" class="input input2" title="Last name" id="lastName" name="lastName" type="text" />
</span>
<span class="inputSpan">
<input value="" class="input input2" title="Email" id="email" name="email" type="text" />
</span>
<span class="inputSpan">
<textarea type="text" id="message" name="message" title="Message" class="input textArea" ></textarea>
</span>
<span class="inputSpan">
<input type="submit" name="submit" class="button" id="submit_btn" value="Send" />
</span>
<div id="contact_ajax_wrap">
<div id="contact_ajax_gif" style="display:none;"><img src="http://www.jacobsmits.com/images/main/ajax-loader-black.gif" width="32" height="32" /></div>
<div id="contact_ajax_success" style="display:none">Thanks! I'll get back to you shortly.</div>
</div>
</form>
<script type="text/javascript">
//This script will handle the email form
$(window).load(function() {
$('#contact_form').placeholderRX({textColor: '#999', hoverColor: '#FBFBFB', addClass: 'yourFormInputText'});
});
$(".button").click(function() {
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({
type: "POST",
url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
data: dataString,
success: function(result) {
if(result == "Success"){
alert("Success");
}else{
alert("Fail");
}
}
});
});
</script>
You need to cancel the default behaviour of the submit button(submit the form not ajax).
It can be done with preverntDefault() on the event object or with return false;
$(".button").click(function(e) {
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({
type: "POST",
url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
data: dataString,
success: function(result) {
if(result == "Success"){
alert("Success");
}else{
alert("Fail");
}
}
});
return false; /// <=== that was missing.
e.preventDefault(); /// Or this.
});
There is a submit event, so better listen to this event instead of the click button:
$("#contact_form").submit(function(e) {
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({
type: "POST",
url: "http://www.jacobsmits.com/demos/scripts/contact_form.php",
data: dataString,
success: function(result) {
if(result == "Success"){
alert("Success");
}else{
alert("Fail");
}
}
});
return false; /// <=== that was missing.
e.preventDefault(); /// Or this.
});
you need to cancel the default behaviour of submit button
$(".button").click(function(e) {
e.preventDefault();
//rest of your code here
var dataString = "fname=" + $("#firstName").val();
alert(dataString);
$.ajax({