Codeigniter AJAX passing array to another page via POST - javascript

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
}
});

Related

Pass javascript string variable to another page and get the variable in PHP with AJAX

I basically don't seem to understand sending a variable to another page.
I've tried PHP sessions, javascript cookies and ajax POST and GET.
I'm trying to send the innerHTML of a div, with the data created by a jQuery call,
a variable called savedartists. It displays correctly in the console.log on the sending page but the $_POST['savedArtists']
is undefined in the receiving page. I have spent hours looking at different posts on this site but I haven't been able to get it to work.
Any help is appreciated.
<input class="et_pb_button et_pb_button_0 et_pb_bg_layout_light" onClick="savequote();" type="button" id="savedchoices" value="Commander la prestation" >
<script>
function savequote() {
var savedartists = document.getElementById('selectedList').innerHTML;
console.log(savedartists);
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
}
});
}
</script>
On the receiving page (example.com/artiste/mise-en-relation/)
<?php
if(isset($_POST['savedArtists']))
{
$uid = $_POST['savedArtists'];
echo $uid;
} else {
echo 'zit!';
}
?>
Thanks for your time
Capturing as an answer for future readers...
Fundamentally what's happening here is that two requests are being made to the target page. The first one is the AJAX request:
$.ajax({
type: "POST",
url: 'example.com/artiste/mise-en-relation/',
data: { savedArtists : savedartists },
success: function(data) {
//...
}
});
This is a POST request which contains the data you expect, and works just fine. However, the result of this request is being ignored. That result is available in the success callback, but the code doesn't do anything with it:
console.log("success!");
location.href = "example.com/artiste/mise-en-relation/";
Instead, what the code is doing is performing a redirect. This creates a second request to that same page (though it's essentially irrelevant that it's the same page). This is a GET request and contains no data to send to the server.
At its simplest, you should either use AJAX or redirect the user. Currently you're mixing both.
I want to redirect to the other page.
In that case AJAX is the wrong tool for the job. You may not even need JavaScript at all, unless you want to modify the elements/values of a form before submitting that form. But if all you want is to POST data to another page while directing the user to that page, a plain old HTML form does exactly that. For example:
<form method="POST" action="example.com/artiste/mise-en-relation/">
<input type="text" name="savedArtists">
<button type="submit">Submit</button>
</form>
In this case whatever value the user enters into the <input> will be included in the POST request to example.com/artiste/mise-en-relation/ when the user submits the form.

Laravel not getting all request data

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'
});

Searchfuntion working with ajax calls in Symfony2

I am coding some basic crud application in Symfony2 where I want to implement some type of search function on a certain page.
The idea is that I want to launch a search query by entering something in an inputfield which is going to fire an ajaxcall (I could not think of anything better). The response of that ajaxcall has to be a kind of popup list with clickable items that is placed into another field on the initial page when clicking an item.
I have two questions:
Is there a better approach than ajax and how can I resolve the problem of the 'popup list' thing.
Second: I can make post ajaxcalls in Symfony2 with this kind of code:
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "post",
success: function(data) {
//some things here
}
But I thought it is a bit strange to use post and I wanted to use get.. Apparently this is not working as I can not retrieve my data in the controller..
EDIT: I forgot to post my controller where I am handling the ajax call, here is the code:
public function testGetAction(Request $request)
{
$data = $request->request->get('data');
$em = $this->getDoctrine()->getManager();
$entity = $em->getRepository('EuropsimProductBundle:SimProfile')->find($data);
return new Response($entity); }
This is working fine with method: "post", but failing when I try to use "get".
I also read about typeahead and this is really close to what I meant, the thing is I want a custom little popup or something because the ajax is supposed to return an array of objects with multiple attributes that has to be shown and where mulitple items are selectable. You can see it as two steps where you first launch the searchquery which bring you to a kind of popup or something where you can select the desired rows for further use on the page.
Thanks in advance!
Hicy
You have to use method $request->query:
For GET method:
$data = $request->query->get('data');
For POST method:
$data = $request->request->get('data');
This really is not much a Symfony2 related question... but...
This code is javascript, if you want to use GET just change method to GET,
var data = 'test';
$.ajax({
url: "{{ path('test_oost') }}",
data: { data: data },
method: "get",
success: function(data) {
//some things here
}
Then in Symfony create the route test_oostand do whatever you want on the controller to send "data" in the response.
Then on te success method process this data accordingly and create the needed view.
EDIT: Based on your new edit, you have an error accessing your data parameter, you should use query instead request
$data = $request->query->get('data');

Post form serialized data with additional parameter through ajaxsetup

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

How to submit a dynamically generated form to AJAX?

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

Categories