I am using $.ajax to submit a form, I want to add a key-value pair to the submission that are not part of the form input and it is common for all my forms.
So i planned to move common part to ajaxsetup.
I want receive these in Action as two parameters like ModelData, TokenKey
My html code
<form id="frm">
#Html.TextBoxFor(m => m.Name)
<input type="button" value="Test" onclick="AjaxPost(); return false;" />
</form>
My Java Script
$(function () {
$.ajaxSetup({ data: { 'TokenId': 'TokenId Value'} });
});
function AjaxPost() {
var frm = $("#frm");
$.ajax({
url: '/Home/Index',
type: 'POST',
data: frm.serialize(),
success: function () { }
});
}
This is not working! If i removed data in AjaxPost function TokenId is posting,
Otherwise its not.
I think this would be a good solution:
$.ajaxPrefilter(function(options, originalData, xhr){
if (options.data)
options.data += "&TokenId=TokenValue";
});
this will affect all ajax calls. Check out the codepen DEMO
When you use the jQuery serialize() function, it simply turns your form into a string in the format a=1&b=2&c=3. So you can certainly apply this function to two forms and concatenate the result, with an & between them, and use the result in your ajax call. You'd want some checks to make sure neither string is empty when you do the concatenation.
$.post(url,{key:value,data:frm.serialize},function(){
//do somehting
})
i usually do this its simple and easy, and you can add as many key:value pairs you want...
You can add a hidden field to your form with the name of TokenId and required value. Or you can modify data like below.
data : fir.serialize()+"&TokenId=TokenId+Value";
Note: You have to Encode your data before append like above
Related
I want to pass select2 multiple select values to database using ajax in my laravel project. Before using ajax, I passed the values using get requests. All values are shows as url parameters, but when it checks with a request -> all() it gets the token value and the last value only, other values are not shown. Why are some other values missing? How can I get all values? I also want to store them in a database. Additionally how can I send those values using ajax.
full URL example:
http://127.0.0.1:8000/send_services?_token=oo6hLRavd6mPczbsgjwQ8RXSNUohhktO5NyNGxCN&services_select=6&services_select=8&services_select=7
Here is my ajax request(send data using ajax instead of normal form submission):
$('#submit-service').click( function() {
var terms = $("#service-select").val();
$.ajax({
type: "GET",
url: '/send_services',
data: terms
})
.done(function(result) {
console.log(result);
})
.fail(function(error) {
console.log(error);
});
});
I want to send this data mainly using ajax.
you just need to add array in name attribute of select tag
for e.g
<select multiple="" name="multiple_values[]" id="service-select">
Sending values using ajax and GET is the same, you simply use the URL:
$.ajax({
type: "GET",
url: '/send_services?data1=value1&data2=value2&data3=value3'
});
Is it possible to pass an array that is populated via checkboxes to another page via AJAX POST and navigate to that page?
The current scenario is I have a table with checkboxes that allows the user to select the checkboxes to pay for multiple items. The issue is passing that multiple ids to the payment page. Are there any suggestions as to how I can do it?
This is what I have so far:
function pay(input){
var id = input;
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/Pay'); ?>",
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success: function(data){
//what do i fill here
}
});
}
Or is there an alternate method of doing this?
I will break this question down into 2 questions:
Is it possible to pass an array that is populated via checkboxes to
another page?
Why yes use square brackets in the input name to make it an array.
<input type="checkbox" name="id[]" value="2">
<input type="checkbox" name="id[]" value="6">
in PHP you can access the selected item ids like this:
$selectedItemIDs = $_POST['id'];
// $selectedItemIDs is now [2, 6] if both checkboxes were selected.
Can I pass an array to another page via AJAX POST and navigate to that
page?
IIRC this is not possible without using a dirty workaround. JavaScript and jQuery do not provide this functionality.
To find the workaround you have to realize that what you are trying to do is simply navigate to a different page, with POST parameters.
Don't forms do exactly that? Yes, they do!
The dirty workaround i was talking about is of course a hidden form where you fill all needed information with JS / jQuery and submit it. Here is a stackOverflow post about this
In your situation though, I would just use the form that you already have (with the multiple checkboxes), since you can easily pass an array of checkbox-values with a form.
The data parameter is not a string when making a POST request. Save all of your form data to a variable and assign that variable to the "data" element of the POST call. You can do this like so:
var myform = $('form').serialize(); // This will save all the form's data to the variable myform
and then
data: myform, // This will send what myform contains via POST
Inside "success" you get to parse the information from the POST response.
After that you can redirect using:
window.location.href = 'http://yourlink.here'; //this will redirect you to another page
Through an array you can post it to ajax
var check_box_array = [];
$("input:checkbox[name=type]:checked").each(function(){
check_box_array.push($(this).val());
});
and then
$.ajax({
method: "POST",
url: "<?php echo site_url($this->data['controller'].'/Pay'); ?>",
data:{check_box_data:check_box_array},
beforeSend: function () {
$('.loading').show();
},
success: function(data){
//what do i fill here
}
});
I need to retrieve data from server using jQuery AJAX on HTML form then store the response data in a php string variable. So far my code is:
<form method="post" name="myform" id="myform" action="https://domain.com/cgi-bin/cgi.exe">
<input name="exec" value="viewproduct" type="hidden">
<input name="customer" value="customer_name" type="hidden">
<input name="sku" value="sku_number" type="hidden">
<input name="submit" type="button">
</form>
<div id="results"></div>
<script type="text/javascript">
jQuery("#myform").submit(function(e){
var postData = jQuery(this).serializeArray();
var formURL = jQuery(this).attr("action");
jQuery.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
jQuery('#results').html(data.toString());
},
error: function(jqXHR, textStatus, errorThrown)
{
alert('fail');
}
});
e.preventDefault();
});
jQuery(document).ready(function() {
jQuery("#myform").submit();
});
</script>
But I still haven't see any result. If I just use the form normally without any js code, then I'll get the raw response data from the server/database directly on the browser. How can I save that raw response data on the browser into a string variable in php?
Change your submit() handler to include this in the first line:
jQuery("#myform").submit(function(e){
e.preventDefault(); // <---
....
and/or add return false; to the end of it.
If that stops it from reloading but doesn't show anything in your #results div, troubleshoot by changing your success() in the AJAX to use this:
jQuery('#results').html(data.toString());
If that shows something, go to your server code and split up your data into individual properties that your Javascript can separate and use individually (or combine it all into one big string if you want).
.html() takes an input of String, not an object (which data is in this case).
You won't be able to store the Javascript value into a PHP variable because PHP runs on the server and returns a response to the browser where Javascript runs on the browser. What you could do is call your script with AJAX and then set your form values with jQuery using
$("input[name=customer]").val(data);
You could either have an AJAX call for each input or you could parse out the return string to get each value. The first may be more straight forward.
If the action is becoming an issue, remove the entirely and just add an onClick to the submit button that calls a function that makes the AJAX calls.
Hope this helps!
I am struggling with the post() method.
I've been reading several posts on here and the jquery forums, and just trying to get a simple piece of code working is proving difficult. My ultimate goal is to pass a div #exportData and all it's children to test.php.
I started with:
$.post("ajax/test.php", $("body").html());
To my mind this should return the entire contents of the current page to test.php (unless test.php requires a holding div or element to receive the content). Currently it only returns the blank page.
I then tried looking at the parameters for post() if I need to manipulate these:
$.ajax({
type: 'POST',
url: ajax/test.php,
data: data,
success: success,
dataType: dataType
});
Also declared a variable:
var data = {
html: #exportData
};
That bit failed of course. I don't know how to define the data in the parameters, or if this is the right place to do it.
Although I would have thought if:
$.post("ajax/test.php", $("body").html());
would have worked then presumably I can substitute "body" for any class, id or selector I like.
Also does the submit button need certain parameters to tie it to the post function. At the moment it is purely:
<input type="submit" id="submit" value="send" name="submit">
Sorry this is such a basic question.
You could do
var html = $("body").html();
var data = {
html: html
};
$.post("ajax/test.php", data);
as the second parameter of $.post() is an object wich contains the data you want to send to the server.
To send the data you could do:
<input type="submit" id="submit" value="send" name="submit">
js
$('input#submit').click(function(e){
//prevent submitting the form (if there is a form)
e.preventDefault();
var html = $("body").html();
var data = {
html: html
};
$.post("ajax/test.php", data);
});
server side you receive the data
$html = $_POST['html']
$.post() expects an object to be passed to transfert data along with the post request:
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [, dataType] )
url: A string containing the URL to which the request is sent.
data: A map or string that is sent to the server with the request.
success(data, textStatus, jqXHR): A callback function that is executed if the request succeeds.
dataType: The type of data expected from the server. Default: Intelligent Guess (xml, json, script, text, html).
var content = $ ('body').html(),
data = { content: content };
$.post('ajax/test.php', data);
Sending html in the post doesn't sound like a good idea. All elements type of input or select will be empty in the Html. You would need to use .serialize in order to get the values.
$('#submit').submit(function () {
$.ajax({
type: 'POST',
url: 'ajax/test.php',
data: {
html: $('body').html()
}
});
});
I have an AJAX call which dynamically generates a HTML form. This form contains a number of elements including inputs, selects, textareas, checkboxes as well as etc.
I need to write some javascript (jquery available) to get all the fields in this form and submit them to an AJAX script. I won't know how many or what fields are there (only a basic idea) as it all depends on what the user does.
Any ideas how to do this? Lets say my form name is 'ajaxform'
As everyone said, use jQuery serialize. One other note is to override your form submit (if needed) via jQuery live method:
//Override form submit
$("form").live("submit", function (event) {
event.preventDefault();
var form = $(this);
$.ajax({
url: form.attr('action'), // Get the action URL to send AJAX to
type: "POST",
data: form.serialize(), // get all form variables
success: function(result){
// ... do your AJAX post result
}
});
});
var string_ready_to_be_posted = $("#formId").serialize();
http://api.jquery.com/serialize/
You can use jQuery's .serialize():
var data = $('#ajaxform').serialize();
var action = $('#ajaxform').attr('action');
$.post(action, data, function(data) {
...
});
var string_ready_to_be_posted = $('form[name="ajaxform"]').serialize();
As addon for using NAME-selector instead of ID