I am new to jQuery.
I have to reload a div after sending some values to server using ajax.
My jQuery code is
selectionChanged: function () {
var $selectedRows = $('#PersonTableContainer').jtable('selectedRows');
$selectedRows.each(function () {
var record = $(this).data('record');
var columnname = record.columnname;
var datatype = record.datatype;
var columnlength = record.columnlength;
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
});
after this code is executed I want to reload a div
<div id="loadedtablecontainer"></div>
this div will get the selected data of 1st jtable .. and display it in this jtable.
So by using this div id I have to call or reload this div soon after above jQuery function got executed
Something like
$.post('meta?action=dataload', {
columnname: columnname, datatype: datatype, columnlength: columnlength
});
$("#loadedtablecontainer");
So I am assuming the Ajax call returns the new content, so set the html() in the callback.
$.post('meta?action=dataload',
{
columnname : columnname,
datatype:datatype,
columnlength:columnlength
},
function (data) {
$( "#loadedtablecontainer" ).html(data);
}
);
You have a callback parameter which returns your result from post. Use that to manipulate the data and form the HTML. Then simply append it
$.post('meta?action=dataload', {
columnname : columnname, datatype:datatype,columnlength:columnlength
},
function (result) {
// make your manipulations here, (Ex: var manipulatedHTML )
$("#loadedtablecontainer" ).append(manipulatedHTML );
}
);
If its a json
function(result) {
//result is your json
var manipulatedHTML = '<div class="result">'+result.value"+'</div>';
}
$("#loadedtablecontainer" ).append(manipulatedHTML )
Use a for loop if its a json array
function loadCustomerCorpPopup(id) {
$("#eBody").mask("${loading}");
$.ajax({
url : '${url}/customer/ajax_customer_corporate_popup',
data : {
customerCorporateId : id,
},
dataType : 'text',
cache : false,
success : function(data) {
$('#popupId').html(data);
$('#popupId').modal('show');
$("#eBody").unmask("${loading}");
}
});
}
You can use this way $('#popupId').html(data);
data can a html code or url.
Related
I have a JSON request using post method using ajax within this code
$(document).ready(function() {
$(document).on('submit', '#registration_check', function() {
var data = $(this).serialize();
$.ajax({
type: 'POST',
url: 'apidomain.com',
data: data,
success: function(data) {
$("#registration_check").fadeOut(500).hide(function() {
$(".result_1").fadeIn(500).show(function() {
$(".result_1").html(data);
});
});
}
});
return false;
});
});
the response will return 3 fields like name, email, phone on this element:
<div id="result_1"></div>
it's working nice so far, but want I plan to do is I want to display the alert or popup message if the ajax response found some of return value null. For example:
If JSON response return:
name: jhon, email: jhon#doe.com, phone: 123456789
user will redirect to the other page (done so far)
But if JSON response return
name: jane, email: jane#doe.com, phone:
The popup or alert will appeared, within text phone number empty.
If your data is a JSON object then you can do:
success: function(data) {
for (var i in data) {
if (!data[i]) {
alert(/* MESSAGE HERE */)
return;
}
}
// Your regular code here
}
You can make an associative array of your values in php file and echo it in the json format like
echo json_encode($array);
Then you will receive this in your ajax response like this
var objs = JSON.parse(data);
Then you can parse the values by keys like name, email and phone as you defined in associative array in your php file
console.log(objs.name);
console.log(objs.email);
console.log(objs.phone);
This is how you can parse the values individually. You can also apply conditions by your own way
First thing that comes to my mind: Do you need the JSON response in the document element or is it, that you dont know how to work with jQuery Ajax?
Anyway, this solution should help you in both cases:
$(document).ready(function()
{
$(document).on('submit', '#registration_check', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'apidomain.com',
data : data,
dataType: 'json', // tell jQuery, that the response data will be a JSON - it will be parsed automatically
success : function(data)
{
// now you have a parsed JSON object in the 'data' var
var show_alert = false;
if (data.phone === null || !data.phone.length) {
show_alert = true;
}
if (data.email === null || !data.email.length) {
show_alert = true;
}
if (show_alert) {
alert('here is the alert :)');
}
$("#registration_check").fadeOut(500).hide(function()
{
$(".result_1").fadeIn(500).show(function()
{
$(".result_1").html(JSON.stringify(data));
});
});
}
});
return false;
});
});
In my webpage I am using jQuery/Ajax to save form data. After save the data using php I am showing successful message like bellow :
if($sql){
$sql_result[] = "<div class='success'>updated</div>";
}
echo end($sql_result);
In Ajax return data I am checking a condition if message is contain updated then I will hide a html element but It's not working.
Here is my jQuery code:
function save_email (element, event) {
e = $(element);
event.preventDefault();
var formData = new FormData(e.parents('form')[0]);
$.ajax({
data : formData,
cache : false,
contentType: false,
processData : false,
url : 'save_email.php',
type : 'POST',
xhr : function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
success : function (data) {
$("#email_success").html(data);
//$("#email_success").show('slow').delay(3000).hide('slow');
if(data == "<div class='success'>updated</div>" ) {
$("#save_email_button").hide('slow');
$(".delete_ex_email_label").hide('slow');
}
},
});
}
Console log data
Updated:
alert(data) is showing this :
It's not uncommon to end up with extra whitespace in php text/html output
That is one reason it's easier to use json and check object properties , especially over comparing a complex string like you are doing.
However using trim() when comparing string results is generally a good idea
try
$.trim(data) === "<div class='success'>updated</div>")
I'm attempting to first make an AJAX request from a social API and append the results with a button inside the div that will save the corresponding item in the array to my firebase database. For example,
I have my AJAX request - I cut out about 75% of the actual code that isn't needed for the question.
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
dataTitle = vids[i].title;
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase()'>Save</button></div>";
$('#content').append( ncode )
And then I have my function that I want to save the 'title' of the object the button was appended with to the firebase database.
var dataTitle;
function saveToDatabase() {
ref.push({
title: dataTitle
});
}
The issue is that when the button is clicked it posts a random title from inside the array instead of the title of the item the button was appended with... How can I bind the buttons function to the correct dataTitle?
I'm not sure if that makes sense so please let me know if clarification is needed. Thanks in advance for any help you can provide!
This fails because you are iterating the entire list and assigning them to a global variable. The result is not random at all--it's the last item in the list, which was the last to be assigned to the globar variable.
Try using jQuery rather than writing your own DOM events, and utilize a closure to reference the video title.
function saveToDatabase(dataTitle) {
ref.push({
title: dataTitle
});
}
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data) {
console.debug(data); // console.debug not supported in all (any?) versions of IE
buildVideoList(data.response.items);
}
});
function buildVideoList(vids) {
$.each(vids, function(vid) {
var $img = $('<img></img>');
$img.attr('src', sanitize(vid.title));
var $button = $('<button class="btn">Save</button>');
$button.click(saveToDatabase.bind(null, vid.title));
$('<div class="tile"></div>')
.append($img)
.append($button)
.appendTo('#content');
});
}
// rudimentary and possibly ineffective, just here to
// point out that it is necessary
function sanitize(url) {
return url.replace(/[<>'"]/, '');
}
I actually just ended up passing the index to the function by creating a global array like so. It seems to be working fine... any reason I shouldn't do it this way?
var vids = []; //global
function foo() {
$.ajax({
type : 'GET',
url : url,
dataType : "jsonp",
cache: false,
success : function(data){
console.debug(data);
vids = data.response.items;
for(var i in vids) {
ncode = "<div class='tile'><img src='"+ vids[i].title "'/></a><button class='btn' type='button' onClick='saveToDatabase('+i+')'>Save</button></div>";
$('#content').append( ncode )
} //end ajax function
function saveToDatabase(i) {
ref.push({
title: vids[i].title
});
}
I have next select2:
siteSelector = $('#siteSelector').select2(
{
placeholder : "Select site ...",
ajax : {
type : 'GET',
dataType : 'json',
contentType : 'application/json',
url : {url_of_my_rest_service},
data : function(term, page) {
return {
startswith : term,
};
},
results : function(data, page) {
var items = data.content;
var res = {
results : []
}, i;
for (i = 0; i < items.length; i++) {
res.results.push({
id : items[i].id,
text : items[i].name
});
}
return res;
}
},
minimumInputLength : 3
});
How can I make that when I press a dropdown button some values will already be preloaded in there?
The best way to do it is to insert the data in the DOM before calling the ajax.
$(document).ready(function () {
//as many as you need, using loop or manually
$('#siteSelector').append("<option value='value1'>Value 1</option>")
//only then start select2 using the function you wrote
//siteSelector = $('#siteSelector').select2(......
})
As far as I know, the data attribute in select2 doesn't work well (or at all) with ajax calls. This method will work.
I have on the view list of images with checkbox in front each image. Checkbox is populated with image id so I can recognize which image is checked for manipulation.
When button is clicked I'm recognizing which images are checked and store each image id to the array of ints. These array I want to sent to the mvc3 controller but I have problem I'm getting error inside sent parameters (firebug). For example if two images are checked I got following:
undefined undefined
undefined undefined
here's the code
var imgList = [];
$('#deleteImgBtn').click(function () {
$('.imgCheckbox:checked').each(function () {
var id = $(this).attr('id');
imgList.push(id);
});
jQuery.ajaxSettings.traditional = true;
$.ajax({
url: '/property/deleteimages',
type: 'POST',
data: imgList ,
success: function(result){
alert("ok");
}
});
...
public ActionResult DeleteImages(int[] data)
{
return PartialView(data);
}
try
$.ajax({
url: '/Property/DeleteImages',
type: 'POST',
data: { data : imgList },
traditional : true,
success: function(result){
alert("ok");
}
});