Executing JavaScript returned from a .post [duplicate] - javascript

This question already has an answer here:
Evaluating scripts in an ajax response
(1 answer)
Closed 8 years ago.
I want JavaScript to execute the data that is returned from a post. I have found several similar threads but nothing that has cleared it up for me. eval() throws an unexpected identifier error.
The post:
$.post("./save.php",
{
'images_key' : images_array,
'userid_key' : $('#userid').val(),
'avatar_key' : $('#avatar_name').val()
},
function( data )
{
$( "#responseText" ).val( data );
eval(data);
}
);
The post is returning:
$('.frame').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data (base-64 string)
$('#img_val').val(canvas.toDataURL('image/png'));
//Submit the form manually
document.getElementById('myForm').submit();
}
});
Any ideas?
Thanks!
MORE INFO:
On button click I'm calling this function:
function saveCSS() {
var id_data = $(".frame div img").map(function() {
return $(this).attr("id");
}).get();
var title_data = $(".frame div img").map(function() {
return $(this).attr("title");
}).get();
var width_data = $(".frame div img").map(function() {
return $(this).css("width");
}).get();
var height_data = $(".frame div img").map(function() {
return $(this).css("height");
}).get();
var top_data = $(".frame div:has(img)").map(function() {
return $(this).css("top");
}).get();
var left_data = $(".frame div:has(img)").map(function() {
return $(this).css("left");
}).get();
var zindex_data = $(".frame div:has(img)").map(function() {
return $(this).css("z-index");
}).get();
var images_array = [];
$.each(id_data, function (index, value) {
images_array.push(value);
images_array.push(title_data[index]);
images_array.push(width_data[index]);
images_array.push(height_data[index]);
images_array.push(top_data[index]);
images_array.push(left_data[index]);
images_array.push(zindex_data[index]);
});
$.post("./save.php",
{
'images_key' : images_array,
'userid_key' : $('#userid').val(),
'avatar_key' : $('#avatar_name').val()
},
function( data )
{
// $( "#responseText" ).val( data );
// console.log(data);
eval(data);
}
);
}
The file save.php contains:
.
.
.
echo "
$('.frame').html2canvas({
onrendered: function (canvas) {
$('#img_val').val(canvas.toDataURL('image/png'));
document.getElementById('myForm').submit();
}
});
";
.
.
.
console.log(data) logs the echo as per expected however, in Chrome's console, when I execute saveCSS(), I see:
function( data )
{
// $( "#responseText" ).val( data );
// console.log(data);
eval(data);
**Uncaught SyntaxError: Unexpected Identifier**
}
);
I'm afraid I do not understand why I'm getting the error.

In order to execute the dat that is returning you have to eval it e.g.
$.post("./save.php",
{
'images_key' : images_array,
'userid_key' : $('#userid').val(),
'avatar_key' : $('#avatar_name').val()
},
function( data )
{
$( "#responseText" ).val( data );
eval(data);
}
);
That said unless you absolutely trust the code you are receiving from the server, I wouldn't recommend executing the data as it could lead to a XSS vulnerability in your site.

Related

Using promises response in calendar function ( which required data from ajax call )

Ajax call in promise :
var promise = new Promise(function(resolve, reject) {
jQuery.ajax({
url:'<?php echo site_url();?>/MyController/ajax_cal',
type:'POST',
dataType: "JSON",
success:function(results) {
resolve(results);
//reject(Error(request.statusText)); // status is not 200 O K, so reject
}
});
});
Respose from promise
promise.then(function(data) {
alert(data); // this is working fine BUT i want to use this in calendar function
}, function(error) {
console.log('Promise rejected.');
console.log(error.message);
});
Calander javascript code :
<!-- Calander Module starts-->
var calendar = $('#calendar').calendar({
console.log(data); /// want to use the data from ajax call on promises
events_source: data , // here
view: 'month',
tmpl_path: '<?php echo base_url();?>asserts/bootstrap_calender/tmpls/',
tmpl_cache: false,
day: '2017-02-14',
onAfterEventsLoad: function(events) {
if(!events) {
return;
}
var list = $('#eventlist');
list.html('');
$.each(events, function(key, val) {
$(document.createElement('li'))
.html('' + val.title + '')
.appendTo(list);
});
},
onAfterViewLoad: function(view) {
$('.page-header h3').text(this.getTitle());
$('.btn-group button').removeClass('active');
$('button[data-calendar-view="' + view + '"]').addClass('active');
},
classes: {
months: {
general: 'label'
}
}
});
(function($) {
$('.btn-group button[data-calendar-nav]').each(function() {
var $this = $(this);
$this.click(function() {
calendar.navigate($this.data('calendar-nav'));
});
});
$('.btn-group button[data-calendar-view]').each(function() {
var $this = $(this);
$this.click(function() {
calendar.view($this.data('calendar-view'));
});
});
$('#first_day').change(function(){
var value = $(this).val();
value = value.length ? parseInt(value) : null;
calendar.setOptions({first_day: value});
calendar.view();
});
$('#language').change(function(){
calendar.setLanguage($(this).val());
calendar.view();
});
$('#events-in-modal').change(function(){
var val = $(this).is(':checked') ? $(this).val() : null;
calendar.setOptions({modal: val});
});
$('#format-12-hours').change(function(){
var val = $(this).is(':checked') ? true : false;
calendar.setOptions({format12: val});
calendar.view();
});
$('#show_wbn').change(function(){
var val = $(this).is(':checked') ? true : false;
calendar.setOptions({display_week_numbers: val});
calendar.view();
});
$('#show_wb').change(function(){
var val = $(this).is(':checked') ? true : false;
calendar.setOptions({weekbox: val});
calendar.view();
});
$('#events-modal .modal-header, #events-modal .modal-footer').click(function(e){
//e.preventDefault();
//e.stopPropagation();
});
}(jQuery));
<!-- Calander Module ends-->
i have want to get the dynamic data (json format ) in "calendar events_source field" . i have use a ajax call but i came to know that the variable are inaccessible outside the ajax call . i than use promises than i was successfully to alert the variable outside the ajax call But i am still unable to access it in the "calendar events_source field" . i don't know what is wrong and how i can use it .
One way to solve it is to create your calendar element after you have data (in then block). I would probably do it so that I build UI then trigger fetching and in then() function I would call onAfterEventsLoad with the received events since it seems to build the the calendar.

How to combine two similar scripts and run it with slight variations

I have the following two scripts:
The first one, on grabs a keyword from input#search and populates a dropdown#search-results with the results from the ajax call for that keyword.
$(document.body).on( 'keyup', '#search', function ( e ) {
//e.preventDefault();
value = $(this).val(); //grab value of input text
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(result, function(k, v) {
$('#search-results').append('<li>' + v['Name'] + '</li>');
});
}
});
});
The second script, grabs the value of the clicked dropdown result, does the same action as the first script only this time the ajax result is used to populate fields located on the page.
$(document.body).on('click','#search-results > li', function ( e ) {
//e.preventDefault();
value = $( this ).text(); //grab text inside element
jQuery.ajax({
url : ajaxsearch.ajax_url,
type : 'post',
data : {
action : 'search_client',
key : value,
},
success : function( response ) {
response = jQuery.parseJSON(response);
//console.log(response);
$.each(response, function(k, v) {
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
}
});
});
Is there a way to combine the second script into the first one so not to make the second ajax call, but be able to populate the fields on the page with the results from the first ajax call depending on the clicked result in the dropdown list?
If the text you insert from v['Name'] into the list item in the first script is the exact same thing you want to use elsewhere in the page in the second script, you can reduce the code way, way down. After all, if you already have the value you want, there's no need to go search for it again.
//first function, just the relevant bits...
$.each(result, function(k, v) {
var newItem = $('<li>' + v['Name'] + '</li>');
$.data(newItem, "value", v);
$('#search-results').append(newItem);
});
//second function, the whole thing
$(document.body).on('click','#search-results > li', function ( e ) {
e.preventDefault();
var v = $.data($( this ), "value"); //grab object stashed inside element
$('#clientID').val( v['ClientId'] );
$('#denumire').val( v['Name'] );
$('#cui').val( v['CUI'] );
$('#regcom').val( v['JRegNo'] );
$('#adresa').val( v['Address'] );
$('#iban').val( v['IBAN'] );
$('#banca').val( v['Bank'] );
$('#telefon').val( v['Phone'] );
$('#pers-contact').val( v['Contact'] );
});
This should let you store the entire result object into the list item, then retrieve it later. If you have some elements in that list that you're not putting there with searches, you'll have to do some more work to get their relevant data too.

Getting data from datatable then passing it to php with ajax

I am using jQuery DataTables, I can get data from selected row using this code
var str = $.map(table.rows('.selected').data(), function (item) {
return item[5]+" "+item[0]
});
where item[5] is id, item[0] is a string.
I want to split return string for passing id and string.
the error founded in ajax code specifically in
data : {}
where is the problem in this code.
<script>
$(document).ready(function() {
var table = $('#liveSearch').DataTable();
$('#liveSearch tbody').off('click', 'tr').on( 'click', 'tr', function () {
if ( $(this).hasClass('selected') ) {
$(this).removeClass('selected');
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
} );
$('.example3-1').on('click', function () {
if ((table.rows('.selected').data().length) > 0) {
var str = $.map(table.rows('.selected').data(), function (item) {
return item[5]+" "+item[0]
});
console.log(str);
$.confirm({
confirmButtonClass: 'btn-info',
cancelButtonClass: 'btn-danger',
confirm: function () {
$.ajax({
type: 'post',
url: 'delete.php',
data: {
str1 : str.substr(0,str.indexOf(' ')),
str2 : str.substr(str.indexOf(' ')+1)
},
success: function( data ) {
console.log( data );
}
});
table.row('.selected').remove().draw(false);
}
});
}
});
} );
CAUSE
You're only allowing only one row selected. But you're using $.map which returns Array not a string as you expect. There is no sense in using $.map for just one row.
SOLUTION
Use the following code instead to get data for selected row and produce the string needed.
var rowdata = table.row('.selected').data();
var str = rowdata[5] + " " + rowdata[0];
It could be simplified further:
var rowdata = table.row('.selected').data();
// ... skipped ...
$.ajax({
// ... skipped ...
data: {
str1: rowdata[5],
str2: rowdata[0]
}
// ... skipped ...
});
NOTES
The solution would be different if you allow multiple row selection.

jQuery $.post not executing, how to fix

I am working on a Plugin for WordPress and am having issues with the js code below executing the $.post.
The js is called, form validation takes place, the form inputs are serialized into post data correctly, the $.post just doesn't execute.
The form is being posted from the Admin, currently I can't get the .submit action to work so am using .click to execute the js function. This may be related to the issue, I am not sure... The form will load without submitting if I use the .submit action, versus using the .click action... never had this issue before and it is pretty frustrating to say the least.
Here is the code:
jQuery(document).ready(function($) {
$("#edit_member_submit").click( function() {
// define
var numbers = /^[0-9]+$/;
var referrer_id = $("#referrer_id").val();
// Validate fields START
if( !referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
// Define a data object to send to our PHP
$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null) {
value = this.value;
} else {
value = '';
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
};
var data = $("#edit_member_form").serializeObject(); //the dynamic form elements.
//alert(JSON.stringify(data));
data.action = "edit_member_info"; //the action to call
data._ajax_nonce = custajaxobj.nonce; // This is the name of the nonce setup in the localize_script
// Define the URL for the AJAX to call
var url = custajaxobj.ajaxurl;
//alert( JSON.stringify( data ) );
//alert( JSON.stringify( url ) );
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
return false;
});
});
Seems like the last section is having issues:
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
$.post( "ajax/test.html", function( data ) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(data);
});

Callback never called on Jquery.post();

I'm having some trouble using JQUERY Post function.
I have 2 functions that call JQUERY Post function.
Both of them is working fine, but the callback function is never called (handleLike).
When I call handleLike manually, it's works perfect.
(Even if handleLike has just an alert inside, the callback function is not called)
Could you please help me with this thing?
<script type="text/javascript">
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
if (v_cb.class == 'map'){
var elemento = $('#maplike');
}else{
var elemento = $('#commentlike'+v_cb.id);
}
if (!(elemento.hasClass('disabled'))){
elemento.addClass("disabled");
var likes = elemento.find('font').text();
likes++;
elemento.find('font').html(likes);
}
}
$('#maplike').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
var JSONObject= {
"mensagem":"Testando Json",
"id":86,
"class":"map"
};
handleLike(JSONObject);
alert("Teste");
$.post(
'/cmap/maps/like',
{ id: id },
handleLike,
'json'
);
}
});
$('[id*="commentlike"]').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
$.post(
'/cmap/comments/like',
{ id: id },
handleLike,
'json'
);
}
});
});
</script>
Diagnostic, not solution
Rationalizing and adding an error handler, you should get something like this :
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
var elemento = (v_cb.class && v_cb.class == 'map') ? $('#maplike') : $('#commentlike'+v_cb.id);
if (!elemento.hasClass('disabled')){
var f = elemento.addClass("disabled").find('font');
f.html(++Number(f.text()));
}
}
function ajaxError(jqXHR, textStatus, errorThrown) {
alert('$.post error: ' + textStatus + ' : ' + errorThrown);
};
$('#maplike').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/maps/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
$('[id*="commentlike"]').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/comments/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
});
untested
Barring mistakes, there's a good chance the error handler will inform you of what's going wrong.
I follow the Kevin B tip and use $ajax method.
It was a parseerror. Sorry.
The return of v_cb was not a json, it was a html. I correct my return, and everything was ok.

Categories

Resources