OpenCart throws Invalid Token Session after deleting orders - ajax

I have written a bespoke Ajax call and function to delete missing orders in OpenCart 2.1.0.2. Although the function works as it should, and the orders are deleted, upon return from the controller, OpenCart logs me out and gives me an Invalid Token Session error, even though the passed token is correct.
Here's my ajax call on the order_list.tpl template:
$('#button-delete_missing').on('click', function(e) {
if (confirm('<?php echo $text_confirm; ?>')) {
var node = this;
$.ajax({
url: '<?php echo $store; ?>index.php?route=api/order/deleteMissing&token=<?php echo $_GET["token"] ?>',
dataType: 'json',
crossDomain: true,
beforeSend: function () {
$(node).button('loading');
},
complete: function () {
$(node).button('reset');
},
success: function (json) {
$('.alert').remove();
if (json['error']) {
$('#content > .container-fluid').prepend('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>');
}
if (json['success']) {
$('#content > .container-fluid').prepend('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + ' <button type="button" class="close" data-dismiss="alert">×</button></div>');
}
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});
}
});
This is exactly the same as the other calls on the page, except it's going to a different function in the controller:
public function deleteMissing() {
$this->load->language('api/order');
$json = array();
$this->load->model('checkout/order');
$this->model_checkout_order->deleteMissingOrders();
$json['success'] = $this->language->get('text_success');
if (isset($this->request->server['HTTP_ORIGIN'])) {
$this->response->addHeader('Access-Control-Allow-Origin: ' . $this->request->server['HTTP_ORIGIN']);
$this->response->addHeader('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
$this->response->addHeader('Access-Control-Max-Age: 1000');
$this->response->addHeader('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With');
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
Which, in turn, is the same as the delete function, just without the need for a specific order id. Here's the function in the model that actually does the delete:
public function deleteMissingOrders() {
$query = $this->db->query("SELECT order_id FROM " . DB_PREFIX . "order WHERE order_status_id = 0 OR order_status_id = null");
$rows = $query->rows;
$order_ids = array();
foreach($rows as $row) {
$order_ids[] = $row['order_id'];
}
if(!empty($order_ids)) {
foreach($order_ids as $order_id) {
$this->db->query("DELETE FROM `" . DB_PREFIX . "order` WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM `" . DB_PREFIX . "order_product` WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM `" . DB_PREFIX . "order_option` WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM `" . DB_PREFIX . "order_voucher` WHERE order_id = '" . (int)$order_id . "'");
$this->db->query("DELETE FROM `" . DB_PREFIX . "order_total` WHERE order_id = '" . (int)$order_id . "'");
}
}
}
The function gets all the null or zero ID order statuses and deletes all relevant data - this WORKS. I've tried it, and all the missing orders are deleted; it's just that when it comes back it throws a non-descript error (i.e. does not run the success part of the ajax call) and logs me out of the admin area.
If anyone can help with this I would be grateful. Maybe there's one thing I've missed, or something I haven't put in which is needed?

I I'm reading this correctly, your script doesnt seem to know what token is. Does it have a declaration? Because Jquery doesnt know what PHP knows.
Do something like
var token = <?php echo $_GET['token'] ?>;

Related

Laravel Ajax live search relationship

Laravel ajax live search does not work. In the console browser, he writes a 500 error. The problem is this relationships. If I do not use it relationship, the ajax live sarch is work. How do I edit my code to work?
Here the code, to be precise:
$contract->typzakazky->nazov_typu.
My model:
public function typzakazky()
{
return $this->belongsTo('App\ContractsType','contracts_type_id');
}
Controller:
public function index()
{
return view('contracts.index');
}
public function search(Request $request)
{
if ($request->ajax()) {
$output = "";
$contracts = DB::table('contracts')->where('nazov', 'LIKE', '%' . $request->search . "%")->get();
if ($contracts) {
foreach ($contracts as $key => $contract) {
$output .= '<tr>' .
'<td>' . $contract->poradove_cislo . '</td>' .
'<td>' . $contract->nazov . '</td>' .
'<td>' . $contract->typzakazky->nazov_typu. '</td>' .
'<td>' . $contract->datumodovzdania. '</td>' .
'</tr>';
}
return Response($output);
}
}
}
View:
...
<script type="text/javascript">
$('#search').on('keyup',function(){
$value=$(this).val();
$.ajax({
type : 'get',
url : '{{URL::to('search')}}',
data:{'search':$value},
success:function(data){
$('tbody').html(data);
}
});
})
</script>
<script type="text/javascript">
$.ajaxSetup({ headers: { 'csrftoken' : '{{ csrf_token() }}' } });
</script>
How to use it properly relationship in ajax? Very thank you.

Laravel Ajax does not get the value from the form to Controller

In Ajax code I have action = 'contact';, contact is used in route file:
Route::post('contact', array('uses' => 'FormsController#send', 'as' => 'post_form'));
In route file I have FormsController#send it is file php to send email:
$name = Input::get('name');
$getSubject = "Subject of my email";
$myEmail = 'myEmail#gmail.com';
$uid = md5(uniqid(time()));
$eol = "\r\n";
// header
$header = "From: " . $name . " <" . $email . ">\r\n";
$header .= "MIME-Version: 1.0" . $eol;
$header .= "Content-Type: multipart/mixed; boundary=\"" . $uid . "\"" . $eol;
$header .= "Content-Transfer-Encoding: 7bit" . $eol;
$header .= "This is a MIME encoded message." . $eol;
// message & attachment
$nmessage = "--" . $uid . "\r\n";
$nmessage .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
$nmessage .= "Content-Transfer-Encoding: 8bit" . $eol;
if($name != ''){$nmessage .= "Name: " . $name . "\r\n\r\n";}
// $nmessage .= "Wiadomość:\r\n" . $getMessage . "\r\n\r\n";
$nmessage .= "--" . $uid . "\r\n";
$nmessage .= "Content-Transfer-Encoding: base64\r\n";
$nmessage .= "--" . $uid . "--";
$send = mail($myEmail, $getSubject, $nmessage, $header);
Ajax directs to the controller file and bypasses the form, so the controller file does not download any data from the form, and the mail can not be sent. I have no idea how to pass data from the form to the controller file.
My Ajax:
const sendForm = function () {
action = 'contact';
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open('post', action, true);
xmlhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
const getMessageSend = document.querySelector("#messageSend");
getMessageSend.innerText = "Thank you for sending an email. You will receive an answer shortly.";
} else {
const getMessageSendError = document.querySelector("#messageSendError");
getMessageSendError.innerText = "An error occurred and the email was not sent.";
}
};
// xmlhttp.open("post", action, true);
// xmlhttp.send();
const token = document.querySelector('meta[name="csrf-token"]').content;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
xmlhttp.setRequestHeader('X-CSRF-TOKEN', token);
xmlhttp.send();
};
const sendMail = function() {
options.form.addEventListener('submit', function (e) {
e.preventDefault();
let validate = true;
const elementsRequired = document.querySelectorAll(":scope [formHr]");
[].forEach.call(elementsRequired, function(element) {
const type = element.type.toUpperCase();
if (type === 'TEXT') {
if (!validateText(element)) {validate = false;}
}
});
if (validate) {
sendForm();
// this.submit();
} else {
return false;
}
});
};
My form:
{!! Form::open(['action'=>['FormsController#send'], 'method' => 'post', 'class' => 'form', 'novalidate' => 'novalidate', 'files' => true]) !!}
<input type="text" name="name" placeholder="Name" formHr>
{!! Form::submit('Send', ['class' => 'submit-btn']); !!}
{!! Form::close() !!}
I found a solution. Help me this theme Submit form laravel using AJAX
I just add data to my code:
$.ajax({
type: "POST",
url: 'contact',
data: $(this).serialize(),
success: function () {
$("#messageSend").addClass("message-send");
$("#messageSend").text("Thank you for sending an email. You will receive an answer shortly.");
}
});
Remember to use full version Jquery!

Laravel passing data using ajax to controller

How do I pass the id from this ajax call to the TestController getAjax() function? When I do the call the url is testUrl?id=1
Route::get('testUrl', 'TestController#getAjax');
<script>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl',
type: 'GET',
data: { id: 1 },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
public function getAjax()
{
$id = $_POST['id'];
$test = new TestModel();
$result = $test->getData($id);
foreach($result as $row)
{
$html =
'<tr>
<td>' . $row->name . '</td>' .
'<td>' . $row->address . '</td>' .
'<td>' . $row->age . '</td>' .
'</tr>';
}
return $html;
}
In the end, I just added the parameter to the Route::get() and in the ajax url call too. I changed $_POST['id'] to $_GET['id'] in the getAjax() function and this got my response back
Route::get('testUrl/{id}', 'TestController#getAjax');
<script>
$(function(){
$('#button').click(function() {
$.ajax({
url: 'testUrl/{id}',
type: 'GET',
data: { id: 1 },
success: function(response)
{
$('#something').html(response);
}
});
});
});
</script>
TestController.php
public function getAjax()
{
$id = $_GET['id'];
$test = new TestModel();
$result = $test->getData($id);
foreach($result as $row)
{
$html =
'<tr>
<td>' . $row->name . '</td>' .
'<td>' . $row->address . '</td>' .
'<td>' . $row->age . '</td>' .
'</tr>';
}
return $html;
}
Your ajax's method is GET but in controller you use $_POST to get
value. This is problem.
You can you
$id = $_GET['id'];
But in Laravel, it have a pretty method to do this. It's here. You do not need to worry about the HTTP verb used for the request, as input is accessed in the same way for all verbs.
$id = Input::get("id");
If you want, you can filter request type to control exception. Docs here
Determine If The Request Is Using AJAX
if (Request::ajax())
{
//
}
#in your controller function
public function getAjax()
{
#check if request is ajax
if ($request->ajax()) {
//your code
}
return $your_data;
}

Show results from live search AJAX

I have a page that shows all results of my database, I have checkboxes and textboxes on the page wich I use to filter the results on the page.
The checkboxes are working, so when you check a textbox the results on the page are getting live filterd. Now I want the same for the textboxes but im stuck how to do it.
this is my code for the textboxes that im using that I also want to use for the textboxes.
<script>
function makeTable(data) {
var tbl_body = "";
$.each(data, function() {
var tbl_row = "";
$.each(this, function(k , v) {
tbl_row += "<td>"+v+"</td>";
})
tbl_body += "<tr>"+tbl_row+"</tr>";
})
return tbl_body;
}
function getEmployeeFilterOptions(){
var opts = [];
$checkboxes.each(function(){
if(this.checked){
opts.push(this.name);
}
});
return opts;
}
function updateEmployees(opts){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {filterOpts: opts},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
var $checkboxes = $("input:checkbox");
$checkboxes.on("change", function(){
var opts = getEmployeeFilterOptions();
updateEmployees(opts);
});
updateEmployees();
</script>
PHP
<?php
$pdo = new PDO('mysql:host=localhost;dbname=records', 'root', '***');
$select = 'SELECT *';
$from = ' FROM overboekingen';
$opts = (isset($_POST['filterOpts']) ? $_POST['filterOpts'] : FALSE);
if (is_array($opts)) {
$where = ' WHERE FALSE';
if (in_array("medewerker", $opts)){
$where .= " OR medewerker = 1 ";
}
if (in_array("medewerker1", $opts)){
$where .= " OR medewerker = 2 ";
}
if (in_array("medewerker2", $opts)){
$where .= " OR medewerker = 3 ";
}
if (in_array("medewerker3", $opts)){
$where .= " OR medewerker = 4 ";
}
if (in_array("medewerker4", $opts)){
$where .= " OR medewerker = 5 ";
}
if (in_array("medewerker5", $opts)){
$where .= " OR medewerker = 6 ";
}
if (in_array("medewerker6", $opts)){
$where .= " OR medewerker = 7 ";
}
if (in_array("medewerker7", $opts)){
$where .= " OR medewerker = 8 ";
}
if (in_array("medewerker8", $opts)){
$where .= " OR medewerker = 9 ";
}
if (in_array("medewerker9", $opts)){
$where .= " OR medewerker = 10 ";
}
if (in_array("medewerker10", $opts)){
$where .= " OR medewerker = 11 ";
}
else {
$where = false;
}
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
?>
I am not sure how your submit.php works, but I assume you can send keywords as "filterOpts" and the correct JSON is returned? If this is correct, you can make the AJAX call when the user changes the input field and send the value of the input each time:
The first block of code simple calls the updateEmployeesText function whenever the 'input' element is changed (basically whenever the user types). Note that we pass $(this).val as a parameter, which is the text inside the textbox.
$('input').change(function(){
updateEmployeesText($(this).val());
});
This block of code calls submit.php asynchronously. It passes the value of the textbox as a POST parameter. After submit.php has returned, the success function is executed and the table is updated.
function updateEmployeesText(val){
$.ajax({
type: "POST",
url: "submit.php",
dataType : 'json',
cache: false,
data: {text: val},
success: function(records){
$('#employees tbody').html(makeTable(records));
}
});
}
In your PHP you can now get that value using $val = $_POST['text']. This is the string you want to search for in the DB. I have outlined the steps below:
Establish PDO (already done)
Now use SELECT * FROM your_table WHERE your_field LIKE '% . $val . %' OR ... (you can keep going)
NOTE: the % at the start and end do a partial search, so anything before or after val will also be returned
Now execute the statement and get the array
Encode the array as JSON and return!
Hope this helps!
EDIT for PHP:
This block of code does everything as described above. Note the partial search used in the SQL LIKE statement. The % indicates wildcard characters before or after $val. For example, if the value was 'cat', the script would search for %cat% which would return results for bcat, cat, fcatr, fggcatrr, etc... Essentially anything containing cat. If you wanted a script that ended with cat you would use '%cat' (%$val) and if you wanted something that began with cat you would use 'cat%' (%$val).
$pdo = new PDO('mysql:host=localhost;dbname=records', 'root', '***');
$select = 'SELECT *';
$from = ' FROM overboekingen';
$val = $_POST['val'];
$where = "WHERE medewerker LIKE '%$val%';
$sql = $select . $from . $where;
$statement = $pdo->prepare($sql);
$statement->execute();
$results = $statement->fetchAll(PDO::FETCH_ASSOC);
$json = json_encode($results);
echo($json);
Don't know if I got your point, you want to have that ajax live feature on inputs as well as checkboxes ?
If so, I'd do something like
$('yourinputselector').keyup(function() {
var user_input = $(this).val();
if (user_input.length > 3) // or any min-chars number
{
// process your ajax request here
}
});

CI and GroceryCRUD DB update row

I use CI 2.1 and GroceryCRUD 1.3.3, i use this 2 function in my controller Admin, but i cant update value of row wher i have 2 values 0/1:
bolean from my view side by click on link or with AJAX (prefered)
function programs_management()
{
if($this->input->get("enable_recomandation"))
{
// $this->programs_management->recomandation((int)$this->input->get("programs"), ($this->input->get("recomandation")=="1")?"1":"0");
$data_for_update = array(
'recomandation' => ($this->input->get("recomandation")=="1")?"1":"0",
);
$this->db->update('programs',$data_for_update,array('program_id' => $this->input->get("programs")));
}
}
function enable_recomandation($value, $row = NULL)
{
// or For AJAX some solution need
// return "<form action='' method='post'>
// <input onClick='document.getElementById('row').value=this.value' type='radio' name='recom' value='activ'>Activ<br>
// <input onClick='document.getElementById('row').value=this.value' type='radio' name='recom' value='inactiv'>Inactiv
// </form>";
if($value=="1")
return '<a href="'.base_url().'/admin/programs_management/?recomandation=0&program_id='.$row->program_id.'" >Active</a>';
else
return '<a href="'.base_url().'/admin/programs_management/?recomandation=1&program_id='.$row->program_id.'" >Inactive</a>';
}
Or somebody can help with alternative, how to do this with AJAX ?
function programs_management()
{
if ($this->input->get("recomandation"))
{
// $this->programs_management->recomandation((int)$this->input->get("programs"), ($this->input->get("recomandation")=="1")?"1":"0");
$data_for_update = array(
'recomandation' => ($this->input->get("recomandation") == "y") ? "1" : "0",
);
$this->db->update('programs', $data_for_update, array('program_id' => $this->input->get("program_id")));
}
}
function enable_recomandation($value, $row = NULL)
{
if ($value == "1")
return '<a href="' . base_url() . 'admin/programs_management/?recomandation=n&program_id=' . $row->program_id . '" >Active</a>';
else
return '<a href="' . base_url() . 'admin/programs_management/?recomandation=y&program_id=' . $row->program_id . '" >Inactive</a>';
}

Resources