prestashop 1.6:how to write insert query in ajax.php - prestashop-1.6

I am just working prestashop in insert query.Below i have attached my ajax file.I have include all supported file but dataes is not inserted in this table.I don't know what is error?.Kindly check and help me.
include '../../config/settings.inc.php';
include '../../config/defines.inc.php';
include '../../config/config.inc.php';
$api=$_REQUEST['api_key'];
$install=$_REQUEST['installtion_id'];
$percentages=$_REQUEST['dep_per'];
$package=$_REQUEST['dep_plan'];
$res = Db::getInstance()->insert('pay4later_setting',array(
'api_key' => '$api',
'installtion_id' => '$install',
'deposite_percentage' =>'$percentages',
'package_plan' =>'$package',
));

Where did you kept your ajax request.Ok,No problem.
For example,
In prestashop i have sent my ajax request through configure.tpl file
configure.tpl
<head>
<script>
$(document).ready(function(){
$('#submit_label').click(function(){
var data = "welcome";
$.ajax({
type:"POST",
dataType:"JSON",
url:baseDir+'modules/anything/data.php',
data:{
ajax:true,
name:data,
},
success: function(html){
if(html.added)
{
$("#success").html(html.added);
}
}
});
});
});
And here i have using data.php as a php file
data.php
<?php
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');
if(isset($_POST['name']))
{
$label_name = $_POST['name']; or you can use Tools::getValue("name");
$connect_db = Db::getInstance()->insert('label', array(
'label_name' => pSQL($label_name),
));
$getin['added'] = 'Label created successfully';//here we have using JSON datatype so we need to create object and store some values.
echo json_encode($getin);
}
Thanks & Regards,
krishna.

Related

How to load and parse .xlsx file using fetch API and XLSX library

I'm importing these library:
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>
and trying to fetch & parse local file saved in my project folder:
fetch('Eshop_product_list.xlsx').then(res => {
return res.blob();
}).then(res => {
console.log('file:', res);
var workbook = XLSX.read(res, {
type: 'binary'
});
});
But I can't get it working. I've tried different combinations of XLSX type arguments with res.blob(), res.text(), res.bufferArray() but everytime it is throwing an error.
What is the correct way?
Try to use res.arrayBuffer() instead of res.bufferArray()
Replaced in your example:
fetch('Eshop_product_list.xlsx').then(res => {
return res.arrayBuffer();
}).then(res => {
console.log('file:', res);
var workbook = XLSX.read(new Uint8Array(res), {
type: 'array'
});
});

Select2 cannot choose elements inside input

I'am struggling with select2.
I have an ajax call that returns me a json. The json is formated like that (from server):
public function get_groups()
{
$result = array();
$sql = "SELECT * FROM auth_groups ";
foreach ($this->db->query($sql)->result() as $row){
$tmp = array("id" => $row->id ,"label" => $row->name );
array_push($result, $tmp);
}
header('Content-type: application/json');
echo json_encode($result);
}
Then from my javascript i have :
$('#group_choice').select2({
minimumInputLength: 2,
ajax: {
url: "/bonsejour/extranet/ajax/resources/get_groups",
dataType: 'json',
data: function (term, page) {
return {
term:term
};
},
results: function (data, page) {
var results = [];
$.each(data, function(index, item)
{
results.push({id:item.ID, text:item.label});
});
return {
results: results
};
}
}
});
Where #group_choice is an input text.
When i type some text inside the input box it does shows all the elements coming from the json. But when i try to select an element nothing happens. How can i select the elements inside the input ?
Thanks
Refer http://ivaynberg.github.io/select2/#documentation
formatSelection: formatSelectionMethod,
function formatSelectionMethod(row) { return row.text;}
I hope you will find it helpful.
Please refer to Select2 Ajax Method Not Selecting,
and take the correct value:
id: function(data){return {id: data.id};},
or
id: function(data){return data.id}

How to check files already uploaded in Uploadify JQ plugin?

I have to prevent users adding files which is already added in the server in 'uploadify' jquery plugin.
There is a grid which shows files which are already added, so I'm planning to get the files name collection from the grid and check it when on select function for preventing to add the already uploaded files.
Is there any better or easy way to do this?
Please help in finishing the code.
Will the above logic work ?
var uploadQueue = new Array();
jQuery().ready(function ($) {
debugger;
$.ajax({
type: "POST",
async: false,
url: ROOT + "Documents/DocumentAJAXController",
data: { "ID": $('[id="ID"]').val() },
success: function (result) {
}
});
$("#SubmitButton1").hide();
$("#fileuploader").fileUpload({
'uploader': "#Url.Content("~/Scripts/FileUpload/uploader.swf")",
'cancelImg': "#Url.Content("~/Content/Images/clearBtn.png")",
'buttonText': 'Browse Files',
//'buttonImg' : "#Url.Content("~/Content/Images/attachDoc.png")",
'script': "#Url.Content("~/Documents/Upload/")",
'folder': "#Url.Content("~/Documents/")",
//'fileDesc': 'Documents Files',
'fileExt': '*.pdf;*.doc;*.ppt;*.xls',
'multi': true,
'auto': false,
onError: function (a, b, c, d) {
},
'onSelect': function (event, queueID, fileObj) {
// uploadQueue.push(queueID);
},
'onAllComplete': function(event,data){
alert("Uploaded successfully");
$('.popupClose').click();
}
});
This functionality is built into the latest version of uploadify.
Uploadify provides for a checkScript handler in the settings that you pass to uploadify.
If you point this at an appropriate server script it will not allow files that already exist.
A sample script called check-exists.php is provided in the uploadify zip.

Submit array param with jQuery ajax/load

public ActionResult DoSomething(string[] arr, bool someBool, int someInt) { }
trying to call the above method from jQuery:
var test = [];
test.push('dog');
test.push('cat');
$container.load('MyController/DoSomething',
{ 'arr[]': test, 'someBool': true, 'someInt': 1 },
function(response, status, xhr) {
// ...
});
the array paramater is null, other params are fine. What am I doing wrong?
Chrome developer tools shows form data being submitted as
arr%5B%5D%5B%5D:dog
arr%5B%5D%5B%5D:cat
someBool:true
someInt:1
not sure whats going on there but doesn't look right to me
If you are using jquery 1.4 you might need to set the traditional parameter to true in order to be compatible with the default model binder format in ASP.NET MVC:
var test = [];
test.push('dog');
test.push('cat');
$.ajax({
url: 'MyController/DoSomething',
type: 'GET',
traditional: true,
data: { arr: test, someBool: true, someInt: 1 },
success: function(result) {
$container.html(result);
}
});
or if you prefer the .load() method:
var data = { arr: test, someBool: true, someInt: 1 };
$container.load('MyController/DoSomething', $.param(data, true),
function(response, status, xhr) {
// ...
});
Just remove []
{ 'arr': test, 'someBool': true, 'someInt': 1 },
Posted values (checking with Firebug).
arr[] dog
arr[] cat
someBool true
someInt 1
Example on jsFiddle
can you see if this problem is similar to yours:
Passing an nested arrays to asp.net mvc using jQuery's $.ajax
Even i was facing error, in passing array from HTML page to aspx page.
my requirement was to load the aspx page in a DIV tag of the html page. on the page load i need to pass these JS array values to aspx page load.
i used below method.
$('#<divTagID>').load("Targetpage.aspx",{"Arr":JSArrValues});
In aspx page load event i can access this values as:
string results = Response["Arr[]"];
Thanks to JQuery API documentation enter link description here and stackoverflow

Sending String Data to MVC Controller using jQuery $.ajax() and $.post()

There's got to be something I'm missing. I've tried using $.ajax() and $.post() to send a string to my ASP.NET MVC Controller, and while the Controller is being reached, the string is null when it gets there. So here is the post method I tried:
$.post("/Journal/SaveEntry", JSONstring);
And here is the ajax method I tried:
$.ajax({
url: "/Journal/SaveEntry",
type: "POST",
data: JSONstring
});
Here is my Controller:
public void SaveEntry(string data)
{
string somethingElse = data;
}
For background, I serialized a JSON object using JSON.stringify(), and this has been successful. I'm trying to send it to my Controller to Deserialize() it. But as I said, the string is arriving as null each time. Any ideas?
Thanks very much.
UPDATE: It was answered that my problem was that I was not using a key/value pair as a parameter to $.post(). So I tried this, but the string still arrived at the Controller as null:
$.post("/Journal/SaveEntry", { "jsonData": JSONstring });
Answered. I did not have the variable names set correctly after my first Update. I changed the variable name in the Controller to jsonData, so my new Controller header looks like:
public void SaveEntry(string jsonData)
and my post action in JS looks like:
$.post("/Journal/SaveEntry", { jsonData: JSONstring });
JSONstring is a "stringified" (or "serialized") JSON object that I serialized by using the JSON plugin offered at json.org. So:
JSONstring = JSON.stringify(journalEntry); // journalEntry is my JSON object
So the variable names in the $.post, and in the Controller method need to be the same name, or nothing will work. Good to know. Thanks for the answers.
Final Answer:
It seems that the variable names were not lining up in his post as i suggested in a comment after sorting out the data formatting issues (assuming that was also an issue.
Actually, make sure youre using the
right key name that your serverside
code is looking for as well as per
Olek's example - ie. if youre code is
looking for the variable data then you
need to use data as your key. –
prodigitalson 6 hours ago
#prodigitalson, that worked. The
variable names weren't lining up. Will
you post a second answer so I can
accept it? Thanks. – Mega Matt 6 hours
ago
So he needed to use a key/value pair, and make sure he was grabbing the right variable from the request on the server side.
the data argument has to be key value pair
$.post("/Journal/SaveEntry", {"JSONString": JSONstring});
It seems dataType is missed. You may also set contentType just in case. Would you try this version?
$.ajax({
url: '/Journal/SaveEntry',
type: 'POST',
data: JSONstring,
dataType: 'json',
contentType: 'application/json; charset=utf-8'
});
Cheers.
Thanks for answer this solve my nightmare.
My grid
..
.Selectable()
.ClientEvents(events => events.OnRowSelected("onRowSelected"))
.Render();
<script type="text/javascript">
function onRowSelected(e) {
id = e.row.cells[0].innerHTML;
$.post("/<b>MyController</b>/GridSelectionCommand", { "id": id});
}
</script>
my controller
public ActionResult GridSelectionCommand(string id)
{
//Here i do what ever i need to do
}
The Way is here.
If you want specify
dataType: 'json'
Then use,
$('#ddlIssueType').change(function () {
var dataResponse = { itemTypeId: $('#ddlItemType').val(), transactionType: this.value };
$.ajax({
type: 'POST',
url: '#Url.Action("StoreLocationList", "../InventoryDailyTransaction")',
data: { 'itemTypeId': $('#ddlItemType').val(), 'transactionType': this.value },
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlStoreLocation').get(0).options.length = 0;
$('#ddlStoreLocation').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlStoreLocation').get(0).options[$('#ddlStoreLocation').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you do not specify
dataType: 'json'
Then use
$('#ddlItemType').change(function () {
$.ajax({
type: 'POST',
url: '#Url.Action("IssueTypeList", "SalesDept")',
data: { itemTypeId: this.value },
cache: false,
success: function (data) {
$('#ddlIssueType').get(0).options.length = 0;
$('#ddlIssueType').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlIssueType').get(0).options[$('#ddlIssueType').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again");
}
});
If you want specify
dataType: 'json' and contentType: 'application/json; charset=utf-8'
Then Use
$.ajax({
type: 'POST',
url: '#Url.Action("LoadAvailableSerialForItem", "../InventoryDailyTransaction")',
data: "{'itemCode':'" + itemCode + "','storeLocation':'" + storeLocation + "'}",
contentType: "application/json; charset=utf-8",
dataType: 'json',
cache: false,
success: function (data) {
$('#ddlAvailAbleItemSerials').get(0).options.length = 0;
$('#ddlAvailAbleItemSerials').get(0).options[0] = new Option('--Select--', '');
$.map(data, function (item) {
$('#ddlAvailAbleItemSerials').get(0).options[$('#ddlAvailAbleItemSerials').get(0).options.length] = new Option(item.Display, item.Value);
});
},
error: function () {
alert("Connection Failed. Please Try Again.");
}
});
If you still can't get it to work, try checking the page URL you are calling the $.post from.
In my case I was calling this method from localhost:61965/Example and my code was:
$.post('Api/Example/New', { jsonData: jsonData });
Firefox sent this request to localhost:61965/Example/Api/Example/New, which is why my request didn't work.

Resources