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'
});
Related
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 have an application that after performing a search, returns me multiple "fieldsets" with some hidden inputs (via AJAX!).
I want to use these inputs to send information to the server (again) via AJAX.
The names of these inputs are automatically listed with a prefix:
"video_url_1", "video_url_2", etc.
When the user clicks the button, the value of "video_url_1" or "video_url_2" will be sent via AJAX depending on the button to which it has clicked. To solve this I got the name of the button that was clicked and then I cut the name so that I only have one number, this number I put in a variable and then use it in the "data" section of AJAX.
I did the test by sending a locally stored input and it worked but when trying to send the inputs that were previously obtained by an ajax, it does not work.
What can be wrong? This is my code:
$(document).ajaxComplete(function(){
$('a.report_video').click(function() {
var idbutton = $(this).attr('id');
var idreport = idbutton.replace('report_video_', '');
//I'm still not using these variables, can they be used to pass the input data to ajax?
var videourl = $("#video_url_" + idreport).val();
var videoid = $("#video_id_" + idreport).val();
var videoserver = $("#server").val();
///////////
$.ajax({
type : 'POST',
url : 'https://example.com/script/script.php',
data : $($("#video_url_" + idreport)).serialize(), //It doesn't work
//For example, data: $("#server").serialize()
//Work fine, this input is stored locally.
beforeSend: function(){
$('#video_report_' + idreport).html('<img src="'+pluginUrl+'./assets/img/loading.svg" />');
}
}).done(function(data) {
$('#video_report_' + idreport).html(data);
});
return false;
});
});
Edit:
I just did some tests as suggested by Kevin B and I see that the problem I have is in the syntax when trying to send two dynamic ID's by Ajax.
The problem is that I do not know how to write them correctly, I know that is the problem because when I tried to send them separately they did work...
data : $($("#video_id_" + idreport), $("#video_url_" + idreport)).serialize(),
I'm not sure I completely understand your problem, but this might help.
You call your second AJAX call in the .success() method of the first AJAX call. Essentially chaining the responses.
$('#btn').click(function() {
$.ajax({
type: "POST",
url: 'someURL',
data: someData
}).done(function(firstCallData) {
// This OPTIONAL method fires when the AJAC call succeeded
// You can also put another AJAX call in here with the data returned from the first call
$.ajax({
type: "POST",
url: 'someURL',
data: firstCallData
}).done(function(data) {
// Do something with second AJAX call with data
}).fail(function(data) {
// Second AJAX call failed, handle error
});
}).fail(function(data) {
// This OPTIONAL method fires when the first response failed
}).always(function(data) {
// This OPTIONAL method fires regardless if the first call succeeded or failed.
});
});
I have a situation,I need to add lot of text to server (via ajax & php).Each is happeening by clicking on a add button.In order to reduce round trip.I am planning to give a save all button so once I store everything in client side and I can save all together to database via ajax so only one round trip.
I have 6 input fields and needs to save this info everytime
My planning
Store everything in a JavaScript hidden variable and itreate this in php side and save it.
I will have to store lot of text in hiden field.Is my approach correct ? any better way ?
You dont need to store it on hidden fields, just make a JSON object containing the data you want and then send it to the server throught ajax.
You can create the JSON object this way:
var jsonObject = {'name': $('#name').val(), 'city': $('#city').val()};
And then you send it to PHP throught AJAX:
$.ajax({
type: 'POST',
url: 'some.php',
data: jsonObject,
dataType: 'json'
}).done(function() {
alert('success');
}).fail(function() {
alert('error');
}).always(function() {
alert('complete');
});
I'm taking an input from user named as category. On every key up i want to perform an ajax request to search if category with the similar name exists or not. If yes, then a there is a blank div below that input which i want to fill with the similar name categories.
So i created a form. Used ajax via jquery but i'm not receiving the response.
This is the jquery ajax code that i'm using
$("#category").keyup(function () {
$.ajax({
url: "categories/categoryajaxrequest",
type: "get",
data: {
category: $("#category").val()
},
success: function (response) {
$("#category_suggestion").html(response);
}
});
});
This is the route part which is used as url in ajax request
Route::get('categories/categoryajaxrequest', array('as' =>'categoryajaxrequest', 'uses' =>'CategoryController#categoryAjaxRequest'));
and this is the controller part
//app/controllers/CategoryController.php
....
public function categoryAjaxRequest(){
echo "working";
}
So, the input text has an id of "category" and below the input, there is a div with an id of "category_suggestion". At every keyup on the input, i expect it to perform an ajax request and show "success" in div . But it's not doing anything.
However, if i go directly to "/categories/categoryajaxrequest" on my browser, it outputs "working".
Try putting the action directly in the url: property of the $.ajax() method, then no route is needed:
Laravel gives us the liberty to do that. The curly braces {{ }} are used in views. As the JavaScript stuff is usually called in a view, it is legitim to do it that way.
The URL::action part is described in the docs as follows:
To generate a URL to a controller action, we may use the URL::action
method or the action helper method:
$url = URL::action('FooController#method');
$url = action('FooController#method');
So the combination of the template system & the URL::action gives us the possibility of doing it this way:
$("#category").keyup(function () {
$.ajax({
url: "{{URL::action('CategoryController#categoryAjaxRequest')}}",
type: "get",
data: {
category: $("#category").val()
},
success: function (response) {
$("#category_suggestion").html(response);
}
});
});
I can't find a decent example of this anywhere.
Basically have a dropdown list, each option value is the productID and text is the Product name.
I want to post all the selected option values to an action method that will return the respective images on document ready. Image data will the be passed to a function which will update the DOM and then execute the same function everytime a different option from dropdown list is selected to retrieve and change the selected options/product image only.
The action method will return the image for this option/value to the client in an AJAX response, I also want to return the product description too.
Should the response data-type be JSON or do I have to return it in some other way i.e HTTP response with image MIME type?
Something like the below collects all the selected values in an array:
$(document).ready(function () {
var arr = new Array();
$('select option').each(function () {
arr.push($(this).val());
});
// This below will post it off:
$.ajax({
type: "POST",
url: "/System/GetProductImages",
data: { arr: arr },
traditional: true,
success: function (data) {
mydata = data;
OnSuccess(data) // <--- The function that will load/update the images
},
dataType: "json" //<--- ?
});
});
I am not sure how to form the AJAX request correctly so I can request both an image and some text, or is it best to make separate calls when requiring different data types? Maybe I can pack them all in into an array of some sort? Also not to sure how the function that will update the DOM with the retrieved images will look.
I would say that your response should be JSON having and Image ID(a value to identify your image from DB) and Product description. Then using that construct dynamic image elements in HTMl and set their src tag to a URL by passing that image ID as parameter and on server side there should be a handler for your request(like servlet, which reads the Image ID and fetches image stream and returns as response). So, browser make a request for each image and get it rendered on browser. hope it will help you!
You can retrieve the new data using the change event on the select box:
$(document).ready(function(){
$('select').change(function(){
$.ajax({
type: "POST",
url: "/System/GetProductImages",
dataType: 'json',
data: { 'id': $('select').selectedIndex.val() },
traditional: true,
success: function (data) {
mydata = data;
OnSuccess(data) // <--- The function that will load/update the images
}
});
});
});
Additionally, if you're more comfortable with PHP, you could echo out the results from the PHP script and call the load function on change of the select option like so:
/* JQuery code */
$(document).ready(function(){
$('select').change(function(){
$.load("/System/GetProductImages", function(){
// The script to run when a successful load operation takes place
});
});
});
/* PHP Code */
echo "<script>$('tag name').html('value you want to set'); $('img').attr('src','new image src');</script>";
Though I'm not sure calling the script from within PHP is the best solution. You should also keep in mind that the Content-Type response header should be set to "application/json".
If you're using PHP, you can use the json_encode function to return a JSON result. You can read more about the PHP JSON options here - http://php.net/manual/en/function.json-encode.php
Hope this helps.