How can I use jquery function-1 variable value, inside function-2? - javascript

I have 2 jQuery events occurring inside a form. There is one select element inside a form:
Event 1 is on select change. It's storing the selected option value in a variable:
$('#sm_name').change(function(){
var option_value = $('#sm_name option:selected').val();
console.log(option_value);
});
Event 2 is on form submit using $.ajax():
$("#fb_form").on('submit', function (e) {
e.preventDefault();
$("#message").empty();
$("#loading").show();
$.ajax({
url: "submit.php",
type: "POST", // Type of request to be send, called as method
data: new FormData(this), // Data sent to server, a set of key/value pairs (i.e. form fields and values)
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData: false, // To send DOMDocument or non processed data file it is set to false
success: function (data) { // A function to be called if request succeeds
}
});
});
How can I change the AJAX URL dynamically for each selected value from the select dropdown? Something like this:
url: "submit.php?id=" + option_value,

You can just read the value of the select within the submit handler:
$("#fb_form").on('submit', function (e) {
e.preventDefault();
$("#message").empty();
$("#loading").show();
$.ajax({
url: "submit.php?id=" + $('#sm_name').val(),
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function (data) {
// do something on request success...
}
});
});
Note the use of val() directly on the select element - you don't need to access the selected option to get the value.

You can directly get value from dropdown to submit form to the url which is selected in dropdown
url: "submit.php?id="+$('#sm_name').val()

This is not specific to jQuery, in JavaScript you can use a feature called closures to use variables from outer scope:
var outerScopeVariable = null;
function a() {
outerScopeVariable = 'hello world';
}
function b() {
console.log(outerScopeVariable); // will output 'hello world' if
// function a() has previously been called.
}

Related

jQuery: How to get input value within an ajax call?

I have a jQuery script, in which I need to load data from a CSV from an external URL.
At the same time, I need to combine the data from the CSV with data provided by a frontend user through an input field. My expected result would be that I'd be able to call the jQuery code for fetching the value from the user's entry into the input field. However, while this works when the code is placed outside the ajax call, it does not work inside.
At the same time, I can't place the code for fetching the user's input outside the ajax call, as I need to be able to utilize information from the loaded CSV together with the user input to perform a dynamic calculation.
My code is as below:
HTML:
<input type="text" id="my_input" value="12" maxlength="2">
Javascript:
$.ajax({
url: csv_url,
async: false,
success: function (csvd) {
var csv = $.csv.toObjects(csvd);
// XYZ done with the CSV data to populate various fields
$("#my_input").keyup(function () {
console.log(this.value);
// this does not result in anything being logged
});
},
dataType: "text",
complete: function () {}
});
Of course it will not work. You are telling the compiler to add the keyup event listener to input after the ajax call is successful. Which means it will not work until ajax call is completed successfully.
You need to put the keyup event listener outside and inside the ajax call just get the value like below:
let myInputValue = "";
$("#my_input").keyup(function () {
console.log(this.value);
myInputValue = this.value;
});
$.ajax({
url: csv_url,
async: false,
success: function (csvd) {
var csv = $.csv.toObjects(csvd);
// XYZ done with the CSV data to populate various fields
//And later use the myInputValue here
},
dataType: "text",
complete: function () {}
});
You have not give us enough info. if you only need the current value in the ajax call you can do like below:
$.ajax({
url: csv_url,
async: false,
success: function (csvd) {
var csv = $.csv.toObjects(csvd);
// XYZ done with the CSV data to populate various fields
let myInputValue = $("#my_input").val();//And later use the myInputValue here
},
dataType: "text",
complete: function () {}
});

Return PHP Variable to Jquery

I have a page called index.php where I have some forms where the user must input information.
On this page I have this JQuery functions.
else if (result == 3)
{
jQuery.get('sample.txt', function(data) {
alert(data);
});
}
where the file sample.text its shown on an alert.
But, I have a page called download.php. When the user click on "submit" at page "index.php" , its send to the page "download.php", the values sent using Ajax POST.
var formData = new FormData($('#form_principal')[0]);
$("#loading").show();
setTimeout(function() {
$.ajax({url: "/tkclientespdo/etiquetaslog/000/0000/download.php",
type: "post",
data: formData,
cache: false,
async:true,
contentType: false,
processData: false,
success: function(result)
on page "download.php" i have this variable :
$horaenvio = date("dmYGis");
after this variable i have a code :
echo 3;
that return the function at index.php .
but i wanna change 'sample.txt" for the variable "$horaenvio".
someone could help.
You can use localStorage and storage event or SharedWorker to store the value data at index.php, and get the value at download.php, then .append() data to the FormData object, then echo the proper POST value.

Image does not update when appending newly inserted row using jquery ajax

I want to insert data using ajax and show that newly inserted data in a div, but the record (i.e. image and name ) does not get updated it.
I don't want to reload page, the newly entered record should be shown without page reload, but it shows only the initial name and image.
I can't understand whats the problem. Please help. Following is the code i am using static data which is stored in a variable as an example:
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
d = new Date();
var img_name='amit.png'+'?'+d.getTime();
var s_name='Ashish';
$('#main').prepend('<img alt="client" id="p_img"><h1>'+s_name+'</h1>');
$('#p_img').attr("src", "image/Amit.png");
},
error: function (error)
{
}
});
Shouldn't the src attribute use the response/variable/generated file name?
Like this:
$('#p_img').attr("src", '/image/' + img_name);
Instead of this:
$('#p_img').attr("src", "image/Amit.png");
It can be two reasons :
the image you are prepending to the DOM is not yet in the DOM when you are trying to add the src
or the src is not existing (should be an absolute or relative path)
Try to prepend the image with the src
$('#main').prepend('<img alt="client" src="ABSOLUTE_OR_RELATIVE_PATH/image/Amit.png"><h1>Amit</h1>');
Also there is no need to create a variable s_name which you only use once.
you can done it easily by returing List of data and populating the div with ajax success result.
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
// in data you are getting your result ...
// now for ease split json format data and store in list
// m not sure about your formate so m assuming at first index it
//should be image URL so..
var res = data.split(",");
var imgSrc = res[0];
$('#main').prepend('<img alt="client" id="p_img"/>');
$('#p_img').attr("src", imgSrc);
},
error: function (error)
{
}
});

Can AJAX update a button argument?

Using AJAX, I'm able to extract a data value from a button click, but is it possible to ensure this value is passed on to an argument within another button on the same page?
test.html:
Activate
Fader
test.js:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
}
});
}
The php file connects to the database and extracts the most recent image number - it works fine and the alert box displays the correct value. So what would be the next step to ensure the "image_number" argument is updated with this 'data' value?
Cheers.
make a global variable like
windows.image_number = 0;
for AJAX function.
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
//update the global variable
windows.image_number = data;
}
});
}
Assuming that the image_number variable that you are passing to the function is a globally defined variable, you simply need to set the variable in your success callback:
function image_check() {
var request = $.ajax({
url: "current_image.php",
type: "GET",
dataType: "html",
success: function(data) {
alert(data);
// Assuming data holds the image number you want to use for next click
image_number = data;
}
});
}

Loading data into a field with jQuery AJAX

I have this code below which is called by running the getGrades function.
function getGrades(grading_company) {
// Set file to get results from..
var loadUrl = "ajax_files/get_grades.php";
// Set data string
var dataString = 'gc_id=' + grading_company;
// Set the callback function to run on success
var callback = showGradesBox;
// Run the AJAX request
runAjax(loadUrl, dataString, callback);
}
function showGradesBox(response) {
// Load data into grade field
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
function runAjax(loadUrl, dataString, callback) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: dataString,
dataType: 'html',
error: ajaxError,
success: function(response) {
callback(response);
}
});
}
Now as you can see I am passing the AJAX response data to the showGradesBox function; however I'm now not sure how to load it into the field.
I have seen example using .load() but it seems you have to use this with the URL all at once; the only other function I have come across that I could possibly use is .html(); but the description of it doesn't sound right!?
.html() should work ...
When .html() is used to set an element's content, any content that was in that element is completely replaced by the new content. Additionally, jQuery removes other constructs such as data and event handlers from child elements before replacing those elements with the new content.
function showGradesBox(response) {
// Load data into grade field
jQuery('#yourgradefieldID').html(response);
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
Assuming a field with ID grade_text and a return of a string from the PHP:
function showGradesBox(response) {
// Load data into grade field
jQuery('#grade_text').val(response);
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
This assigns a value of 'undefined' to your callback.
// Set the callback function to run on success
var callback = showGradesBox;
Try assigning the function to a variable named showGradesBox before your functions like this
var showGradesBox = function(response) {
// Load data into grade field
// Hide condition fields
jQuery('#condition').hide();
jQuery('#condition_text').hide();
// Show grade fields
jQuery('#grade_wrapper').show();
jQuery('#grade_text_wrapper').show();
}
function getGrades(grading_company) {
// Set file to get results from..
var loadUrl = "ajax_files/get_grades.php";
// Set data string
var dataString = 'gc_id=' + grading_company;
// Set the callback function to run on success
var callback = showGradesBox;
// Run the AJAX request
runAjax(loadUrl, dataString, callback);
}
function runAjax(loadUrl, dataString, callback) {
jQuery.ajax({
type: 'GET',
url: loadUrl,
data: dataString,
dataType: 'html',
error: ajaxError,
success: function(response) {
callback(response);
}
});
}

Categories