Execute scripts AJAX returns - javascript

TIP: "you could simple send an json object / array from php to js, and execute every entry like "update_match('1');" using the eval() function, please stop sending js code that way"- Lucian Depold.
In the index.php, I have this code, which executes when the document is ready:
$.post('php/main.php', {elements: 1}, function(return_msg) {
alert(return_msg);
});
The respond I get is a bunch of scripts, as expected, with the expected values. However, they do not execute! How to make them execute?
Here is the response:
<script>jsfunction(37069);</script><script>updateTextbox('');</script><script>update_match('1', '19.30 Friday 15/5', '1');</script><script>update_player('1', '1', 'recoba', 'cmf', 'teo', '0', '0');</script><script>update_player('1', '2', 'nesta', 'cb', 'tsoulou', '0', '0');</script><script>update_player('1', '3', 'raul', 'cf', 'striker', '0', '0');</script><script>update_player('1', '4', 'samuel', 'cb', 'mafia', '', '1');</script><script>update_player('1', '5', 'deisler', 'cmf', 'free_kick', '1', '');</script><script>update_player('1', '6', 'ferdinard', 'cb', 'strong', '1', '');</script><script>update_match('2', 'Match 2', '0');</script>
When I had the PHP code that produced these scripts in the bottom of the index.php, all the js functions where called correctly. Because of this question though, I had to move the code to another .php file.

Do it this way:
In PHP...
$arrayOfCalls = array();
$arrayOfCalls[]="update_match('1')";
$arrayOfCalls[]="update_match('2')";
$dummy = array();
$dummy['calls'] =$arrayOfCalls;
echo json_encode($dummy);
And in Javascript...
$.post('php/main.php', {elements: 1}, function(return_json) {
return_json = JSON.parse(return_json);
return_json.calls.forEach(function(code){
eval(code);
})
});

You can append the result to your page :
$.post('php/main.php', {elements: 1}, function(return_msg) {
$('body').append(return_msg);
});
The code will be executed but I'm not sure if it's safe to do that.

The date delivered by the AJAX call is just data - or text. In order to interpret that as JavaScript, you must append it to the dom.
Two ways:
first, by appending the data directly:
$.post('php/main.php', {elements: 1}, function(return_msg) {
alert(return_msg);
$('body').append(return_msg);
});
but there's also a shorthand method:
$.getScript('php/main.php?elements=' + 1, function () {
// script loaded
});
Please read the docs, there are some caveats!

Related

Can you store js code on the fly in a variable and have js read it?

I'm not sure if what I'm trying to do is the correct/valid approach to what I'm trying to accomplish; essentially, I'm retrieving data from a db via an ajax call, I want this data to populate a js library where the layout is something like
data[
item{
name: 'name',
start_date: date,
end_date: date
},
item{
name: 'name',
start_date: date,
end_date: date
},
]
is there any way I can populate the code inside 'data' on the fly?
I was thinking with a loop to populate a variable which would hold the data and placing it like so
//this is hard coded, but the idea is that a loop would populate this with the necessary information
let items = "
item{
name: 'name',
start_date: date,
end_date: date
},
item{
name: 'name',
start_date: date,
end_date: date
}";
data[
items
]
Would this be a valid approach?
thanks in advance!
UPDATE:
For clarification, this what I have
$('#calendar').fullCalendar({
defaultDate: today,
eventLimit: true,
events: [
{
title: 'Some event',
start: '2022-08-31',
end: '2022-08-31'
},
{
title: 'Some event',
start: '2022-08-31',
end: '2022-08-31'
}
]
});
What im trying to achieve is something like this
let allEvents = "
{
title: 'Some event',
start: '2022-08-31',
end: '2022-08-31'
},
{
title: 'Some event',
start: '2022-08-31',
end: '2022-08-31'
}";
$('#calendar').fullCalendar({
defaultDate: today,
eventLimit: true,
events: [
allEvents;
]
});
Would this be possible?
So, closing this question, thanks to #DaveNewton for the insight, it really clarified what I was supposed to do; I apologize for the confusion, my thought process essentially revolved around 'echoing' or 'printing' code in php.
my approach was:
$.ajax({
type: "GET",
url: filethathandlesrequest.php,
data: {
data_to_be_sent: 'data',
},
success: function(response) {
response = JSON.parse(response);
eventsGotten = response.return_result;
//this is where I create the object
let eventsToDisplay = [];
for (let index = 0; index < eventsGotten.length; index++) {
const element = eventsGotten[index];
let singleEvent = {title: element.description, start: element.start_date, end: element.end_date};
eventsToDisplay.push(singleEvent);
}
if (response.return_code === 0) {
if ($('#calendar').exists()) {
loadScript(plugin_path + 'fullcalendar/fullcalendar.min.js', function() {
$('#calendar').fullCalendar({
defaultDate: today,
//editable: true,
eventLimit: true,
events: eventsToDisplay // <-- this is where I use it; and it works!
});
});
}
} else { //you can ignore this, this is just to not display anything if my ajax request fails
if ($('#calendar').exists()) {
loadScript(plugin_path + 'fullcalendar/fullcalendar.min.js', function () {
$('#calendar').fullCalendar({
defaultDate: today,
//editable: true,
eventLimit: true,
events: []
});
});
}
}
});
It seems you are asking if you can import data from a database and populate a JSON array in Javascript with it. The answer would be yes. In fact, I do this routinely to create Javascript front ends that can be quickly rendered and only talk to the database when necessary so you're not waiting on it. You can use Jquery ajax calls to retrieve and write data. I like to have local variables with JSON formatted data which I use to run the app. The app can quickly read and write changes to these JSON arrays. Keep in mind if the page is reloaded or fails all the data to that point will be lost and the user will have to start over so you need to store data to the database at strategic intervals. You can also use HTML localStorage to store data in the browser itself. I've found this an efficient way to build single-page Javascript apps without resorting to React or some of the other frameworks. It's not as efficient though, but easier to code and maintain.
The approach I would take is to define a particular DOM element as a parent / container for the DOM elements which will represent each item. Iterate over the items array in your ajax response, and create DOM elements with jquery for each item. Something along the lines of $('<div>${currentItem.name}>/div>').appendTo(containerDiv);

How do I replace an external javascript array on the Vue js array?

I'm still a beginner in Vue.js and I have a problem. I have this code:
data: function(){
return {
search: '',
zenes: [
{ id: '1', name: 'Jhon Snow', profile_pic: 'https://i.stack.imgur.com/CE5lz.png'},
{ id: '2', name: 'Deanerys Targarian', profile_pic: 'https://i.stack.imgur.com/CE5lz.png'},
{ id: '3', name: 'Jaime Lanister', profile_pic: 'https://i.stack.imgur.com/CE5lz.png'},
{ id: '4', name: 'Tyron Lanister', profile_pic: 'https://i.stack.imgur.com/CE5lz.png'}
]};
},
This code is really good but i would like to use in my application so I would like to change zenes:[....], to an external javascript code:
<script>var zenecim = <%- zenecim %></script>//these are big arrays thousands of items
<script>var zenesrc = <%- zenesrc %></script>
I would like to see like this or something like that:
zenes:[id:(this is the indexof the array),name:zenecim,src:zenesrc]
Thank you very much for the answer.
If you want to receive external data your choices are pretty much limited to either using a prop on a component or you can use an AJAX request with something like Axios for example.
Of course you can set window globals and access them but that is something you really don't want to be doing.
The context of your problem is missing here therefore I can not judge what would be the best pick here.

Refresh data in table after creating a record

In my Ui5 app I have added CREATE operation using oData. But when i am trying to create entry it is getting added in backend but in table it is showing NO DATA (refer image 1). but when I refresh the same page it is there (refer image 2). With single entry ,it is automatically getting refreshed 
problem is with Multiple entries.
Please refer the screenshot and code for clear view.
After Clicking CREATE button:
After Refreshing WebPage:
onCreate: function() {
var oModel = this.getView().getModel();
var contactEntry1 = {
ProductID: 'KT-1960',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'First batch entry',
},
contactEntry2 = {
ProductID: 'KT-1982',
TypeCode: 'AD',
SupplierID: '0100000001',
TaxTarifCode: 1,
Category: 'Notebooks',
MeasureUnit: 'EA',
CurrencyCode: 'EUR',
Name: 'Urvish',
Description: 'Second batch entry',
};
oModel.setUseBatch(true);
oModel.create('/ProductSet', contactEntry1);
oModel.create('/ProductSet', contactEntry2);
oModel.refresh(true);
},
Looks like that you use the asynchronous operation for create but think that they are synchronous.
In order to fix this out, you can send these 2 create in one $batch request, but use the createEntry method of ODataModel, in order to use the submitChanges method, the callback of which, will be called once two of items are successfully created on the backend side (the below code example should be relevant for v2.ODataModel):
var oTableItemsBinding = oTable.getBinding("items");
// define the group ID, which will be used later on
var aCurrentDeferredGroups = oModel.getDeferredGroups();
oModel.setDeferredGroups(aCurrentDeferredGroups.concat("createProductGroup"));
// create two entries one by one, specifying the 'groupId' parameter
oModel.createEntry("/ProductSet", {
properties: contactEntry1,
groupId: "createProductGroup"
});
oModel.createEntry("/ProductSet", {
properties: contactEntry2,
groupId: "createProductGroup"
});
// send 2 requests in one $batch, passing the name of the 'groupId'
oModel.submitChanges({
groupId: "createProductGroup",
success: function() {
// no need to call refresh() as the model already does it by default (See "refreshAfterChange")
}.bind(this)
});
If your service does not support $batch requests, then you can still use the create method, but make use of it's success callback to be sure that the entry has been persisted in the backend.

Unexpected behavior using Bootstrap-Table and Javascript in Django (inline editable)

I'm using bootstrap-table with inline editable plugin to create a bootstrap table for a list of laptop. My goal was to apply changes to my csv file after users make changes to the table like this example (Product Category: Laptop)
I have created a javascript function below to send Ajax data to my Django server.
// ajax to server
$(function () {
$( "#table" ).on("click" , 'button',function(event){
var selected_item = getSelectedRow(); //this will return selected row object
console.log(selected_item);
$.ajax({
type: "post",
url: '/update/',
data: {
'item': JSON.stringify(selected_item)
},
success: function (data) {
alert('success');
}
});
});
});
Below is the output from my console log
(pcategory has been changed to Laptop2)
However, when I try to get the data from Django. It gave me the output below, which (pcategory was not changed to Laptop2)
{'webcam': 'WebCam', 'lannum': '2', 'condition': 'Refurbished', 'video2': 'GM204M [GeForce GTX 970M]', 'memorybanks': '8G 2133MHz/8G 2133MHz/', 'cpus': '1', 'customernotes': '', 'lanmodels': 'Killer E2400 Gigabit Ethernet Controller/WLAN QCA6174 802.11ac Wireless Network Adapter/', 'internalnotes': '', 'pline': 'Alienware', 'sku': 'LEN-LT-TPEdge-03BV001', 'cddvd': '', 'hddcapacity': '0.0G', 'coresthreads': '4 | 8', 'sound': 'Sound-Yes', 'pmodel': '15 R2', 'resolution': '1230x1000', 'ptype': 'Minitower', 'grade': 'GradeB:R2-Ready for Resale', 'touchscreen': 'Yes', 'hddqty': '0', 'pcategory': 'Laptop', 'processor': 'i7-6700HQ 2.60GHz', 'memory': '16G', 'serialnum': 'BFYNM72', 'video1': 'GM204M [GeForce GTX 970M]', 'hddmodels': '', 'manufacturer': 'Alienware', 'motherboard': 'Alienware 15 R2', 'batch': '03BV', 'hddserialnum': ''}
My Django view function:
#csrf_exempt
def update_page(request):
file_path = os.path.join(CSV_BASE_DIR, CURRENT_BATCH, '{}.csv'.format(CURRENT_BATCH))
if request.method == 'POST':
item = json.loads(request.POST.get('item'))
pprint.pprint(item)
overwrite_csv(file_path,item)
else:
print('no data back!')
return HttpResponse('yes')
I noticed when I changed the input again. The value will get changed to laptop2. It seems like it didn't save the value in the way I expect it to be. I'm wondering is there any way my Django server would get the same value as soon as I click on the check mark?
Thank you all in advanced.
Make sure the data source is Same for both listing and updating.

Malformed request when creating billing plan

So I a using the node paypal-rest-sdk module and I'm trying to create a billing plan. Using the documentation here I made this JSON:
const billingPlanAttributes = {
name: 'Subscription',
description: 'Monthly subscription plan',
type: 'INFINITE',
payment_definitions: [{
name: 'Regular monthly infinite payments',
type: 'REGULAR',
frequency_interval: '1',
frequency: 'MONTH',
cycles: '0',
amount: {
currency: 'USD',
amount: '4.99',
},
}],
merchant_preferences: {
cancel_url: 'http://localhost:3000/subscribe/cancel',
return_url: 'http://localhost:3000/subscribe/return',
auto_bill_amount: 'YES',
},
};
But when using the paypal.billingPlan.create(... function I get the error 'MALFORMED_REQUEST', 'Incoming JSON request does not map to API request'. So I guess my JSON is not in the correct format or I'm missing something that is need.
The documentation has a charge_models key but it does not mention that it is required unlike other keys.
If you can point me in the right direction that would be great.
Edit: changed the return url and cancel url to include the full domain but still same error.
There could be more to this, but I noticed one thing wrong with your JSON. Remove commas for items last in a list. After 'amount' and 'merchant_preferences'. JSON is picky.
late answer, I know, but ran in exactly the same issue than you.
In the create function of the billing plan
public function create($apiContext = null, $restCall = null)
{
$payLoad = $this->toJSON();
$json = self::executeCall(
"/v1/payments/billing-plans/",
"POST",
$payLoad,
null,
$apiContext,
$restCall
);
$this->fromJson($json);
return $this;
}
I found out, that the toJSON method always returned false. Why the hell!?!
I did the same as you did and copied the complete sample code into my code. Then it worked as expected. Now I checked, what the difference was in to my code.
I realized, that I used an umlauts (ä,ü,ö) in the name and description of the billing plan. I changed the umlauts to
'ä' => 'ae',
'ö' => 'oe'
'ü' => 'ue'
Then it worked fine! Maybe someone else is running in this issue, too.

Categories

Resources