I'm developing a small application in javascript using jquery but i've a small problem.
i've this function
function cercahq(urlvalue) {
$.ajax({
type: "POST",
url: "data.php",
data: "do=urlget&url=" + urlvalue,
dataType: "html",
success: function(msg) {
var data = eval('(' + msg + ')');
$("#searchbar").css({'background-color': '#C33'});
// creates element
var insertform = document.createElement('form');
insertform.id = "insertform";
var insertbutton = document.createElement('button');
var insertbuttonlabel = document.createTextNode('Insert');
insertbutton.appendChild(insertbuttonlabel);
insertform.appendChild(insertbutton);
$("#searchbar").append(insertform);
$(insertbutton).click(function(event, data) {
event.preventDefault();
alert(data.title);
});
stampa(msg)
},
error: function()
{
alert("Error");
}
});
}
This function gets json data from a php script and pass it to a function (stampa) that evals it and print it in the page, but i need to create a button outside the stampa function that tells me a value from the json...
So inside the success event i've insered another eval to grab the ajax msg and create the variable data that should be passed to a button element that i've created inside a form called insertform.
The point is: how to pass the "data" variable to the click function from an element created inside an ajax request success function?
The 'data' variable should be accesible inside click function through closure, no need to pass it there. By passing it as parameter you override it as closure with 'undefined' value. So just remove it from parameters:
$(insertbutton).click(function(event) {
event.preventDefault();
alert(data.title);
});
Related
I have 3 files for showing data from myAdmin and it shows no error but after I put function around .ajax, to re-use it, I cannot pass button id to PHP. " Undefined index: btnId"
What seems wrong?
HTML file, written in PHP (below looped in for code)
print"<button class='refresh' data-name='$btnId' id='$btnId'>{$btnId}</button>";
print "<table id='$idForShowNewData' class='showNewData'></table>";
show.js
$(document).ready(function(){
$('.refresh').click(function(){
$(function showTable() {
$.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $(this).data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
showTable();
});
});
PHP file that get's data from myAdmin. Getting id like below is at the top of the script.
$gotBtnId = $_POST['btnId'];
this in showTable refers to window object and not the button whose data-name you want to send in the request.
If you want showTable to be invoked when the page is loaded and also be registered as a listener for click events to the refresh button, declare it as follows:
const $refreshBtn = $('button.refresh');
function showTable() {
$.ajax({
url: "show.php",
type: "POST",
data: {
"btnId": $refreshBtn.data("name")
},
success: function(data) {
//more code
},
error: function(xhr,XMLHttpRequest,errorThrown){
//more code
}
});
});
$(function() {
showTable();
$refreshBtn.click(showTable);
});
I have an AJAX function which gets called every time the enter key is pressed. I have a set of javascript variables that get passed into the data of the AJAX function. Previously, these JS variables were equal to elements in the HTML (the contents of a text area). Now I want these JS variables to be equal to the values of JS variables outside the function.
function stream()
{
var line_Number = $('#lineNumber').val();
var post_code = '#lineText';
var post_id = $('#Streamid').val();
if (post_code != ''){
$.ajax({
url: "post-code.php",
method: "POST",
data: {lineText: post_code, lineNumber: line_Number},
dataType: "text",
success: function(data){
if(data != ''){
$('#Streamid').val(data);
}
$('#autoStream').text("Sending data");
setInterval(function(){
$('#autoStream').text('');
}, 100);
}
});
}
}
Another function then calls the AJAX function
And here are the JS variables which I want to access and pass into the AJAX function
var text;
var lineNumber;
var lineText;
var numOfSpaces;
function update(e) {
text = //code
lineNumber = //code
lineText = //code
I didn't show the code for each variable as I felt it might unneccesarily complicate this.
If I understand your question, you have these options:
1- Use a hidden HTML element:
<input type="hidden" id="someVariable">
where yout want to initialize in your script (JQuery):
$('#someVariable').val(myVar)
and in script in ajax function (JQuery):
var myVar = $('#someVariable').val()
2- You know var scope if it is declared outside a function in javascript, is hole document (window).
3- Pass the arguments to your ajax functio. e.g:
function stream(firstVariable, secondOne, ...)
Hi you can create a json array and pass it as parameter of your ajax function,
this way you avoid to write unnecessary code, example:
let params = {
"line_number": $('#lineNumber').val(),
"post_code" : '#lineText',
"post_id" : $('#Streamid').val()
};
function stream(params)
{
if (params.post_code != ''){
$.ajax({
url: "post-code.php",
method: "POST",
data: data,
dataType: "text",
success: function(data){
if(data != ''){
$('#Streamid').val(data);
}
$('#autoStream').text("Sending data");
setInterval(function(){
$('#autoStream').text('');
}, 100);
}
});
}
}
Hope it helps
I have an AJAX call, as below. This posts data from a form to JSON. I then take the values and put them back into the div called response so as to not refresh the page.
$("form").on("submit", function(event) { $targetElement = $('#response'); event.preventDefault(); // Perform ajax call // console.log("Sending data: " + $(this).serialize()); $.ajax({
url: '/OAH',
data: $('form').serialize(),
datatype: 'json',
type: 'POST',
success: function(response) {
// Success handler
var TableTing = response["table"];
$("#RearPillarNS").empty();
$("#RearPillarNS").append("Rear Pillar Assembly Part No: " + response["RearPillarNS"]);
$("#TableThing").empty();
$("#TableThing").append(TableTing);
for (key in response) {
if (key == 'myList') {
// Add the new elements from 'myList' to the form
$targetElement.empty();
select = $('<select id="mySelect" class="form-control" onchange="myFunction()"></select>');
response[key].forEach(function(item) {
select.append($('<option>').text(item));
});
$targetElement.html(select);
} else {
// Update existing controls to those of the response.
$(':input[name="' + key + '"]').val(response[key]);
}
}
return myFunction()
// End handler
}
// Proceed with normal submission or new ajax call }) });
This generates a new <select id="mySelect">
I need to now extract the value that has been selected by the newly generated select and amend my JSON array. Again, without refreshing the page.
I was thinking of doing this via a button called CreateDrawing
The JS function for this would be:
> $(function() {
$('a#CreateDrawing').bind('click', function() {
$.getJSON('/Printit',
function(data) {
//do nothing
});
return false;
});
});
This is because I will be using the data from the JSON array in a Python function, via Flask that'll be using the value from the select.
My question is, what is the best way (if someone could do a working example too that'd help me A LOT) to get the value from the select as above, and bring into Python Flask/JSON.
So right now I have a form that is saved in AJAX when submitted.
$(document).ready(function () {
$("#dispatchForm").on("submit", function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr("action") || window.location.pathname,
type: "POST",
data: $(this).serialize(),
success: function (data) {
$("#form_output").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
I then have it where the result is shown in a variable and put into a textbox on the page when the submit button is clicked, via this code.
$(function () {
$("#dispatchSumbit").on("click", function () {
var text = $("#textarea");
var local = $("#dispatchForm").serialize();
text.val(text.val() + time +" - Dispatched to \n" + local);
});
});
However it shows the whole array which is like this:
I want it to just say "[Time] - Dispatched to Test"
Thanks for the help in advance!
$("#dispatchForm").serialize() is for creating a name=value&name=value&... string for all the inputs in the form, which can be used as the data in an AJAX request. If you just want a single value, use
var local = $("#dispatchForm [name=dispatchLocal]").val();
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);
}
});
}