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.
});
});
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'
});
I'm trying to retrieve the data I submitted to an asynchronous ajax request should the back-end fail in some way. The data in 'myJSONData' is actually pulled off a queue (array) in memory and I need to put it back into the queue if any kind of error occurs.
e.g.
var myJSONData = {"parm1":"value1","parm2":"value"};
$.ajax({
type: "POST",
url: "/postData.ajax",
dataType: "json",
data: myJSONData,
success: function(jsonReply) {
// I need to refer to the posted data here (i.e. myJSONData)
},
error: function(xhr,ajaxOptions,thrownError) {
// I need to refer to the posted data here (i.e. myJSONData)
}
});
My code fires off a number of calls at various times, the trouble is that if I refer to myJSONData within the success or error blocks it contains the most recent value of that variable in memory, and not what was in the variable at the time of the ajax call.
Is there some other way to access the data associated with the particular instance of ajax call - something like $.ajax.data ?
You should be able to access it in your success and error functions :
success: function(jsonReply) {
var p1 = myJSONData.param1;
}
I have been working on this for a while and posted several related topics about it, but this is slightly different question. I have the following AJAX code with some html forms below it with in #container and .myselect is the class of a drop-down box. When I change the value in the box I want to be able to then use that value on other fields below the select. The AJAX code kinda works in that the alert shows the right value when changed but as you can see I have tried lots of success functions but no luck. The closest is
$('#reloadtest').html(data); which will show the value in my PHP and every time I change the value from then on it will change alot, but it reloads the page within the container.
Basically I want to know how I can reload the data but not the whole html/page so I can use the value of the drop down in my PHP.
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
type: "POST",
data: { orderidType : orderidVal },
success: function(data) {
//$('#container').reload('#container', function() {});
//$('#quoteselect').reload('#quoteselect', function() {});
//$('#container').load('orders.php #container', function() {});
//$('#quoteselect').load('orders.php #quoteselect', function() {});
//$('#testreload').reload('#testreload', function() {});
//location.href = "test2.php"
$('#reloadtest').html(data); //this allows me to use the variable but reloads the whole page within the page
}
})
});
});
If you are doing an ajax-request you have to allocate an URL where to send the request.
If you don't Request anything jQuery reloads the page. As you can see here in the jquery-api-docu the URL is the very first and most important parameter of the request.
$.ajax({
url: "/url/to/the/php/script.php",
success: function(data){
//do something ... with data parameter
}
});
would be the simple way of using ajax-request with javascript.
use two divs - one in which you can put ajax response and in other the remaining HTML code
it reloads your page because you have not specified what page to request.
use the code below and replace /path/to/script to your actual script path
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
cache: false,
async: true,
type: "POST",
url: '/path/to/script',
data: { 'orderidType' : orderidVal },
success: function(data) {
$('#reloadtest').html(data);
}
});
});
});
I have two datatables that I am merging together using Javascript and jQuery. I want to POST this data to a Rails controller action, but the results of the action will need to be displayed in another view, and I am a little tired of figuring out how to do a redirect to another action from an AJAX POST (It just refuses to display).
So now my question is, how can I change this code to actually post and do a redirect to another action?
My original code is:
submithash = {}
submithash['standard_id'] = $("#app_standard_id").val()
submithash['apps'] = apps
hash = { type: "POST", url: "create_all", data: submithash }
$.ajax(hash)
This worked GREAT in that it submitted correctly to my Rails controller action, but of course there does not appear to be a clean way to redirect from an Ajax submission and actually physically display an actual page to a user.
I tried:
$form = $("<form>").attr("method", "post").attr("action", "create_all")
$("<input type='hidden'>").attr("name", "standard_id").attr("value", $("#app_standard_id").val()).appendTo($form)
$("<input type='hidden'>").attr("name", "apps").attr("value", apps).appendTo($form)
$form.submit
but of course that refuses to work. It doesn't even do anything, which is a little odd.
If I understand you question correctly you wish to redirect your page to another url when your ajax call to "create_all" completes.
So you can use the success callback function like this:
hash = { type: "POST",
url: "create_all",
data: submithash,
success: function(data){
//Here you can write your redirection code
//this function will be called when ajax completes successfully
window.location = "url"//redirect url;
//or you can also start another ajax
}
};
$.ajax(hash);
Also check out the documentation for jquery.ajax() here
I ended up using this jQuery plugin:
(function($) {
$.extend({
getGo: function(url, params) {
document.location = url + '?' + $.param(params);
},
postGo: function(url, params) {
var $form = $("<form>")
.attr("method", "post")
.attr("action", url);
$.each(params, function(name, value) {
$("<input type='hidden'>")
.attr("name", name)
.attr("value", value)
.appendTo($form);
});
$form.appendTo("body");
$form.submit();
}
});
})(jQuery);
It builds a form on the fly with whatever you pass it, then appends it to the document. Then it does a regular POST (or GET, depending on what you call).
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.