Loading data into a field with jQuery AJAX - javascript

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

Related

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

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.
}

Cannot write in text box while it's autosaving using tinymce-4 plugin

I am using a plugin to autosave a textbox. However, when the autosave function is called, the text box cannot be typed into. I want users to be able to continue typing while the auto save is posted via AJAX.
tinymce.PluginManager.add('jsave', function(editor) {
// Get the form element into a jQuery object.
var $form = $(editor.formElement);
// Settings for initialization.
var settings = {
// Interval to execute the function. Default is 15000 (ms 1000 = 1 second).
//seconds: editor.getParam('jsave_seconds') || 2000,
seconds: 2000,
// This is our url that we will send data. If you want to have two different links,
// one for ajax and one for manual post this setting is pretty useful!
url: editor.getParam('jsave_url') || $form.attr('action'),
// This is the callback that will be executed after the form is submitted
callback: editor.getParam('jsave_callback')
};
$('.form_header,#attachbox').change(function (){
tinymce.get('mail_body').isNotDirty=0;
$("#save_status").html("Not saved");
});
var interval = setInterval(function() {
// Quit the function if the editor is not dirty.
if (!editor.isDirty()){
return;
}
// Update the original textarea
editor.save();
// Create a data string from form elements.
ds =$form.serialize();
// $form.find(':input').each(function (i, el) {
// $el = $(el);
// if($el.attr('name')!=null)
// ds[$el.attr('name')] = $el.val(); }
// );
$("#save_status").html("Saving");
$.ajax({
url: settings.url,
type: $form.attr('method'),
data: ds,
dataType:"json",
async:false,
success: function(msg) {
if (settings.callback){
//editor.setContent(msg.draft_body);
$("#save_status").html("Saved");
settings.callback(msg);
}
else{
$("#save_status").html("Saving error");
console.log(msg);
}
}
});
}, settings.seconds);
}); //vsk.me/en/28/adding-an-autosave-plugin-to-tinymce-2#sthash.jsOruJSd.dpuf
I have solved this problem:
just change form async:false, to async:true, in ajax calling part.
$.ajax({
url: settings.url,
type: $form.attr('method'),
data: ds,
dataType:"json",
async:true,
success: function(msg) {
if (settings.callback){
//editor.setContent(msg.draft_body);
$("#save_status").html("Saved");
settings.callback(msg);
}
else{
$("#save_status").html("Saving error");
console.log(msg);
}
}
});
Why don't you just disable it while doing the ajax call and enable again on ajax call ends?
You have a reference to enable/disable the field via JavaScript here:
make readonly/disable tinymce textarea
That way you could use the complete attribute on your Ajax call to enable the field again after either succes or error response like this:
var interval = setInterval(function() {
// Quit the function if the editor is not dirty.
if (!editor.isDirty()){
return;
}
// Update the original textarea
editor.save();
// Create a data string from form elements.
ds =$form.serialize();
$("#save_status").html("Saving");
tinyMCE.get('textarea_id').getBody().setAttribute('contenteditable', false);
$ajax({
url: settings.url,
type: $form.attr('method'),
data: ds,
dataType:"json",
async:false,
success: function(msg) {
if (settings.callback){
//editor.setContent(msg.draft_body);
$("#save_status").html("Saved");
settings.callback(msg);
}
else{
$("#save_status").html("Saving error");
console.log(msg);
}
},
error:function(){
//DO ERROR STUFF
},
complete:function(){
tinyMCE.get('textarea_id').getBody().setAttribute('contenteditable', true);
}
});

How to connect to the Parse Javascript API? (502 error)

I am building a chatroom-type app using the Parse Javascript API. The task is to get some data from Parse, display it, add user input to the messages, and send it right back to parse.
The problem is I am not being able to see the data from parse, and receive a 502 error. I am a bit newer to javascript, so any advice on how to accomplish this, or any mistakes you may see in my code, would be fantastic. I also commented out my code the best I could. Thanks for the help.
Here is my code;
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages')
//fetches data from parse
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success: console.log("Success"),
function message(a) {
my_messages.append('<ul>' + a +'</ul>'); //adds ul 'text' to messages
};
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
function(message){
window.location.reload(1) //refresh every 3 seconds
});
});
});
</script>
you have syntax error in both of your success functions of $.ajax calls. In the first ajax call you have places console.log, which should be inside the success callback. In the second one u haven't even added success: callback.
Try below updated code
$(document).ready(function(){
delete Chat.display;
delete Chat.send;
delete Chat.fetch;
var my_messages = $('ul.messages');
var myChat = function() {
$.ajax({
url: "https://api.parse.com/1/classes/chats",
dataType: "json",
success:function message(a) {
console.log("Success")
$.each(a,function(i,item){
my_messages.append('<ul>' + item.username +'</ul>'); //adds ul 'text' to messages
});
}
});
};
myChat(); // call mychat
$('button.send').on('click', function() { // when user clicks send
// send post to
$.ajax({
type: "POST",
url: "https://api.parse.com/1/classes/chats",
data: JSON.stringify({text: $('input.draft').val()}), // stringify the text on value input.draft
success:function(message){
window.location.reload(1) //refresh every 3 seconds
}
});
});
});

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

How to bring ajax search onkeyup with jquery

My Script to call ajax
<script language="javascript">
function search_func(value)
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
</script>
HTML
<input type="text" name="sample_search" id="sample_search" onkeyup="search_func(this.value);">
Question: while onkeyup I am using ajax to fetch the result. Once ajax result delay increases problem occurs for me.
For Example
While typing t keyword I receive ajax result and while typing te I receive ajax result
when ajax time delay between two keyup sometime makes a serious issue.
When I type te fastly. ajax search for t keyword come late, when compare to te. I don't know how to handle this type of cases.
Result
While typing te keyword fastly due to ajax delays. result for t keyword comes.
I believe I had explained up to reader knowledge.
You should check if the value has changed over time:
var searchRequest = null;
$(function () {
var minlength = 3;
$("#sample_search").keyup(function () {
var that = this,
value = $(this).val();
if (value.length >= minlength ) {
if (searchRequest != null)
searchRequest.abort();
searchRequest = $.ajax({
type: "GET",
url: "sample.php",
data: {
'search_keyword' : value
},
dataType: "text",
success: function(msg){
//we need to check if the value is the same
if (value==$(that).val()) {
//Receiving the result of search here
}
}
});
}
});
});
EDIT:
The searchRequest variable was added to prevent multiple unnecessary requests to the server.
Keep hold of the XMLHttpRequest object that $.ajax() returns and then on the next keyup, call .abort(). That should kill the previous ajax request and let you do the new one.
var req = null;
function search_func(value)
{
if (req != null) req.abort();
req = $.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg){
//Receiving the result of search here
}
});
}
Try using the jQuery UI autocomplete. Saves you from many low-level coding.
First i will suggest that making a ajax call on every keyup is not good (and this why u run in this problem) .
Second if you want to use keyup then show a loading image after input box to show user its still loading (use loading image like you get on adding comment)
Couple of pointers. Firstly, language is a deprecated attribute of javascript. In HTML(5) you can leave the attribute off, or use type="text/javascript". Secondly, you are using jQuery so why do you have an inline function call when you can do that with jQuery too?
$(function(){
// Document is ready
$("#sample_search").keyup(function()
{
$.ajax({
type: "GET",
url: "sample.php",
data: {'search_keyword' : value},
dataType: "text",
success: function(msg)
{
//Receiving the result of search here
}
});
});
});
I would suggest leaving a little delay between the keyup event and calling an ajax function. What you could do is use setTimeout to check that the user has finished typing before then calling your ajax function.

Categories