The following is my form
<form id="form1">
<table>
<tr><td >Name:</td><td class="CommentsRight"><input type="text" name="txtName" style="width:90%" /></td></tr>
<tr><td >Email: (Optional)</td><td class="CommentsRight"><input type="text" Name="txtEmail" style="width:90%" /></td></tr>
<tr><td >Comment: </td><td class="CommentsRight"><textarea type="text" style="width:90%" Name="txtMessage" TextMode="MultiLine" Rows="10"></textarea></td></tr>
<tr><td ></td><td class="CommentsRight"><input type="submit" width="100" ID="cmdSubmit" onclick="javascript: SubmitComment();" /> <input type="button" ID="cmdCancel" Text="Reset" value="Reset" onclick="document.getElementById('form1').reset();" /></td></tr>
</table>
</form>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>
function SubmitComment()
{
alert($("txtName").val());
$.ajax({
type: "POST",
url: "#(Request.RawUrl)",
data: '{txtCode: "' + $("#txtName.value") + '" }',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { alert('success'); } ,
failure: function (response) {
alert(response.d);
}
});
}
The alert is bringing back undefined all the time for the alert, i'm a beginner to Ajax/Jquery. I've tried #txtName, I've tried input also but it doesn't return any value I put into the txtName, what am I do wrong. I want to then extend data so i pass all the input strings into the data.
In short,
How do I get the value of txtName.text
How do I build up the data string so it contains separated data values
Your help most appreciated.
Try the following:
<input type="text" name="txtName" style="width:90%" />
Into
<input type="text" name="txtName" id="txtName" style="width:90%" />
javascript: SubmitComment();
Into
javascript: SubmitComment(e);
function SubmitComment()
{
Into
function SubmitComment(e)
{
e.preventDefault();
alert($("txtName").val());
Into
alert($("#txtName").val());
data: '{txtCode: "' + $("#txtName.value") + '" }',
Into
data: {txtCode: $("#txtName").val() }, // Send particular data
(or)
data: $("#form1").serialize(), // Send inside form all data
You can not use $("txtName") as you did it. jQuery will not know what to select. There is no class/id or any other selector. Rather use $("input[name=txtName]").val() or give the txtName a class or id (like i did in my example below).
If you want to send the form now in a nice Json you need to serialize it:
var data = $("#form1").serialize();
https://jsfiddle.net/gahapv4t/
you have written wrong code in data parameter in ajax request. you can pass object of paramater then jQuery take care of it to convert into Raw POST data or Query string.
function SubmitComment()
{
alert($("txtName").val());
$.ajax({
type: "POST",
url: "#(Request.RawUrl)",
data: {txtCode: $("#txtName").val()},
dataType: "json",
success: function (data) { alert('success'); alert(JSON.stringify(data)) } ,
failure: function (response) {
alert(response.d);
}
});
Look you can do it in many ways. According to your markup you can try to get value of txtName in following way
$("input[name=txtName]").val();
Or you can add an id with the input field in following way
<input name="txtName" id="someid">
And finally to get value use following code
$("#someid").val()
$("input[name=txtName]").val() is to get the value by name.
$("#id").val() is to get value by its id.
$(".class").val() is to get value by class name.
I think that you have the answer to your first question.
use $("#txtName').val() for receive the value of the field,
you can achieve your second question in multiple ways:
Using the .serialize() function
like Marcel wrote you can create a variable data where you serialize the form and pass it to the $.ajax function like this:
var data = $("#form1").serialize();
$.ajax({
type: "POST",
url: "#(Request.RawUrl)",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { alert('success'); } ,
failure: function (response) {
alert(response.d);
}
});
2. Using FormData Object
Update your function intercepting a submit event to your form, create a FormData Object and pass your form like this:
$("#form1").submit(function(e){
e.preventDefault();
var formdata = new FormData($(this)[0]);
$.ajax({
type: "POST",
url: "#(Request.RawUrl)",
data: formdata,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function () { alert('success'); } ,
failure: function (response) {
alert(response.d);
}
});
});
Whit this method you can also insert custom data to pass:
formData.append('action', 'customAction');
formData.append('id', 123);
formData.append('mydogname', 'Jo');
3. Using post() function
This is one of the simpliest way to send post data using Ajax (Documentation ). It's also easy to customize and use Jquery Logics.
$( "#form1" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
data = $form.serialize();
var posting = $.post( "#(Request.RawUrl)", data );
posting.done(function( data ) {
alert(data);
});
});
I hope this will help you.
Related
I am submitting a form that will need to go to 2 different locations. The form is hidden and auto filled with the jquery .val method. How would I write the ajax to submit this in 2 different locations? Am I able to do this if I don't have access to my server side settings?
Here is the Form I am submitting
<form action="x" method="post" class="form-inline">
<input type="hidden" name="players_name" class="form-control" id="playersFullName_submit">
<input type="hidden" name="players_email"class="form-control" id="playersEmail_submit">
<input type="hidden" name="players_score" class="form-control" id="playersScore_submit">
<input type="hidden" name="redirect_url" class="form-control" id="redirectURL_submit" value="x">
<input id="submit endGame" type="submit" class="btn btn-default" value="Submit Your Score">
</form>
Here is my jquery filling it out
$(function () { // fill form fields
$('#playersFullName_submit').val(playersFullName);
$('#p_name').append(playersFullName);
$('#playersEmail_submit').val(playersEmail);
$('#dateSubmitted').val(submitDate);
});
Here is how I think I need to set it up
$.ajax({
type: "POST",
url : "url1.com",
data: {},
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: {},
success: function(msg){
// get response here
}
});
Would I need to enter anything into data, or will it pull it from my <form>?
You need to get the form data and inject it into the AJAX calls in the data property. You can do this with JQuery's serialize() method:
// Get your reference to the form:
var theForm = document.getElementsByTagName("form")[0];
$.ajax({
type: "POST",
url : "url1.com",
data: $(theForm).serialize(), // <-- Inject serialized form data
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: $(theForm).serialize(), // <-- Inject serialized form data
success: function(msg){
// get response here
}
});
b/c you are submitting ajax not form, you need to prevent form form action submitting, declare you server side route in ajax instead.
$('#submit_btn').on('click', function(e) {
e.preventDefault(); // you need this so the form don't submit
$.ajax({
type: "POST",
url : "url1.com",
data: {},
success: function(msg1){
var msg1;
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: {},
success: function(msg2){
var msg2;
}
});
});
$.ajax({
type: "POST",
url : "url1.com",
data: $('.form-inline').serialize(),
success: function(msg){
// get response here
}
});
$.ajax({
type: "POST",
url : "url2.com",
data: $('.form-inline').serialize(),
success: function(msg){
// get response here
}
});
In case you have to find yourself having to send to many urls...
var theForm = document.getElementsByTagName("form")[0],
urls = ['url1.com','url2.com', ....];
$.each(urls, function(index,value){
$.ajax({
type: "POST",
url : value,
data: $(theForm).serialize(),
success: function(msg){
// get response here
}
});
});
I have a basic messaging service on a web Node / Express web app, and I'm trying to submit the form via Ajax, using the FormData object.
If I submit the form without AJAX, then everything works fine, but with AJAX the req.body. are all undefined.
On the server, I need to look for the data somewhere other than req.body when using AJAX??
Creating the FormData object:
var ajaxData = new FormData;
ajaxData.append('newMessage', $('.new-message').val()) // I've console.logged these, and their values are correct
ajaxData.append('senderId', $('[name="senderId"]').val())
ajaxData.append('senderName', $('[name="senderName"]').val())// I've console.logged these, and their values are correct
ajaxData.append('recipientId', $('[name="recipientId"]').val())
ajaxData.append('recipientName', $('[name="recipientName"]').val())// I've console.logged these, and their values are correct
And this is the POST request:
$.ajax({
url: $form.attr('action'),
type: $form.attr('method'),
data: ajaxData,
dataType: false,
cache: false,
contentType: false,
processData: false,
complete: function() {
console.log('message created');
},
success: function(data) {
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.statusText);
console.log(textStatus);
console.log(errorThrown);
}
});
EDIT
Thanks to G. Mansour for his answers below. In case anyone else gets here, the issue was the line:
contentType: false,
I tried this line at some point, which also doesn't work
contentType: 'application/json',
But when I remove the line entirely, everything is working as normal... If anyone can tell me why this line was breaking everything, I'd be interested to know.
This is the html part
<form id="form" action="" method="post">
<input type="text" name="msgID" id="msgID">
<input type="text" name="senderId" id="senderId">
<input type="text" name="senderName" id="senderName">
<input type="text" name="recipientId" id="recipientId">
<input type="text" name="recipientName" id="recipientName">
<input type="submit" name="dsq" value="dsqdsq">
</form>
this is the JavaScript part
<script type="text/javascript">
$(document).ready(function(){
$("#form").submit(function(){
$.ajax({
url: "test.php",
data: $("#form").serialize(),
type: "POST",
dataType: 'json',
success: function (e) {
console.log(JSON.stringify(e));
},
error:function(e){
console.log(JSON.stringify(e));
}
});
return false;
});
});
</script>
And this is the php code
<?php
die(json_encode(array("status"=>true)));
?>
Hope that will helps you.
I checked your code it says that's
Illegal invocation
So i'll give a solution you can use
data: $form.serialize(),
dataType: 'json',
And then you can catch your returned result by
console.log(JSON.stringify(e));
Wish that helps. If you have some errors i can help you.
I have a script to fetch data and load it in a div, the code works fine and display the user id list if I don't use any form value and if I don't use type="POST", but it doesn't work (no result and no console error message) when I use $_POST values :
HTML :
<form name='newUser' id="searchForm" method="POST">
<input type="text" name="look_for" id="look_for">
<input type="text" name="lookage_from" id="age_from">
<input type="text" name="age_to" id="age_to">
</form>
fetchusers.php
$look_for = $_POST['look_for'];
$age_from = $_POST['age_from'];
$age_to = $_POST['age_to'];
$array = getProfilePicsList($look_for,$age_from,$age_to); //a function that select * from ...
echo json_encode($array);
jquery code:
$("#searchForm").submit(function(event)
{
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
return false;
});
In your ajax request, you are missing the data. just add this:
data: $("#searchForm").serialize(),
Example:
$.ajax({
type: 'POST',
url: 'models/fetchUsers.php', //the script to call to get data
dataType: 'json', //data format
data: $("#searchForm").serialize(),
success: function(data) //on recieve of reply
{
$.each($(data), function(key, value) {
$('#itemContainer').append(value.user_id);
});
}
});
Without using data param, you can't get the values in $_POST array.
Some References:
https://api.jquery.com/jquery.post/
http://www.w3schools.com/ajax/ajax_xmlhttprequest_send.asp
The following form is what I use:
<form id="form-attachment" action="" method="post" enctype="multipart/form-data">
<input name="attachment" type="file" />
<input type="submit" />
</form>
This is what I do with jQuery:
$('body').on('submit', '#form-attachment', function(e) {
e.preventDefault();
var data = $(this).serialize();
console.log('fine', data);
var url = 'imageupload.php';
$.ajax({
type : "POST",
url : url,
data : data,
success : function(response) {
console.log('success: ' + response);
},
complete : function(response) {
console.log('complete: ', response);
},
error: function(response) {
console.log('error: ', response);
}
});
});
And this is my imageupload.php file:
$response = array();
$response["c"] = isset($_FILES["attachment"]);
echo json_encode($response);
And this is result on console on submit():
success: {"c":false}
So, what is wrong? Why my file is not visible at all?
You can use FormData object, as shown below..
$('body').on('submit', '#form-attachment', function(e) {
var data = new FormData(jQuery('#form-attachment')[0]);
jQuery.ajax({
type: "post",
contentType: false,
processData: false,
url: jQuery(this).attr('action'),
dataType: "json",
data: data,
success: function (r) {
// Success Handeling
}
});
});
NOTE:- No need to append anything as other answer suggests.
This method shall pass all the input fields just like they would in a normal http form POST method.
Use FormData object.
Here's the example how to send file via jQuery ajax request:
$(document).on('change', 'input[type=file]', function() {
formData = new FormData;
formData.append('file', $(this)[0].files[0]);
$.ajax {
url: '/upload-url',
data: formData,
type: 'post',
processData: false,
contentType: false,
success: function(data) {
console.log(data);
}
}
});
In your case you should serialize form first, append serialized data to the formData object. Then get file (or files) from a file field and append it to the same formData object. And finally send the formData object via ajax.
Here is mycode
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('', $("#browseimg"+elem).prop('files')[0]);
var startdate=$("#from_date"+elem).val();
var enddate=$("#to_date"+elem).val();
$.ajax({
url: "addpackage/",
type:"post",
contentType:false,
data:{startdate:startdate,enddate:enddate,packageid:elem,img:dataimg},
success: function(data) {
}
});
}
I tried post method ajax to upload image and input field data without form. In ajax call it showing [object object]. How to post image with input field without form in jquery ajax?
You can do it like following. Hope this will help you.
function addPackage(elem)
{
var dataimg = new FormData();
dataimg.append('startdate', $("#from_date"+elem).val());
dataimg.append('enddate', $("#to_date"+elem).val());
dataimg.append('packageid', elem);
dataimg.append('img', $("#browseimg"+elem)[0].files[0]);
$.ajax({
url: "addpackage/",
type:"post",
cache : false,
contentType : false,
processType : false,
data: dataimg,
success: function(data) {
}
});
}
You can try this:
Your JS Code:
<script type="text/javascript">
var data = new FormData(document.getElementById("yourFormID")); //your form ID
var url = $("#yourFormID").attr("action"); // action that you mention in form action.
$.ajax({
type: "POST",
url: url,
data: data,
enctype: 'multipart/form-data',
processData: false, // tell jQuery not to process the data
contentType: false, // tell jQuery not to set contentType
dataType: "json",
success: function(response)
{
// some code after succes from php
},
beforeSend: function()
{
// some code before request send if required like LOADING....
}
});
</script>
Dummy HTML:
<form method="post" action="addpackage/" id="yourFormID">
<input type="text" name="firstvalue" value="some value">
<input type="text" name="secondvalue" value="some value">
<input type="file" name="imagevalue">
</form>
in addpackage php file:
print_r($_POST);
print_r($_FILES);