How can I call the desired function via jquery? - prestashop

It is necessary that when you click on the button, a request is made via ajax and the desired row in the database is deleted.
I have the code:
$(".remove_order_submit").click(function(){
$.ajax({
url: "/modules/ps_customercedula/ps_customercedula.php",
method: "post",
data: {
method: 1,
id_order_remove: {$hook_name}
},
success: function(data){
}
});
});
});
How to write php so that if post method = 1 then call the function
public function displayAjax()
{
$db = \Db::getInstance();
if ($this->errors)
die(Tools::jsonEncode(array('hasError' => true, 'errors' => $this->errors)));
if(Tools::getValue('method')=='1')
{
$db = \Db::getInstance();
$result = $db->delete('log', 'id_log = 2');
}
}

You can't use direct address of main PHP file of your module.
In admin side: you can use the configuration page of your module(getContent method) or in the better choice, you can create custom adminController in your module
In front side: you have to create frontController in your module

Related

Shopify app with proxy extension PUT requests not working

I have managed to created an app proxy using this guide:
https://shopify.dev/tutorials/display-data-on-an-online-store-with-an-application-proxy-app-extension#handling-proxy-requests
I wanted to update the customer record using a form. On submission of form the below func would be invoked.
jQuery(function($) {
$('#enrollFormID').submit(function() {
var fname = $(FirstName).val();
var lname = $(LastName).val();
var emailID = $(email).val();
var pass = $(password).val();
event.preventDefault();
var data = jQuery(this).serialize();
console.log(data);
data = "form_type="+data;
$.ajax({
url: '/apps/subpath',
type: 'PUT',
data: data,
dataType: 'json',
success: function (data) {
console.info(data);
}
});
return true;
});
});
In the backend app, the below url is getting hit when the form gets submitted, but am not able to retrieve the form data values.
router.put('/test', async (ctx) => {
.....
}
Get request works fine, but with Put request am not able to retrieve the form data from the ajax call.
Can someone help me on this?

Calling MVC5 action using AXIOS and ValidateAntiForgeryToken

I am trying to call a controller method marked with [ValidateAntiForgeryToken] from my UI using Axios.
I have successfully called the same action by using Jquery ajax
Working AJAX Code.
First i get the token from my form
var addAntiForgeryToken = function (data) {
data.__RequestVerificationToken = $("[name='__RequestVerificationToken']").val();
return data;
};
amd then i call my method
$.ajax({
type: "POST",
url: "http://localhost:40428/controller/action",
data: addAntiForgeryToken({ }),
success: function (response) {
}
});
The above successfully calls the following method in my controller
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Test_Get()
{
ViewBag.Search = true;
return View("Index");
}
What i have already tried with axios is the following
axios({
method: 'post',
url: 'http://localhost:40428/Meeting_Notes/Test_Get',
data: addAntiForgeryToken({})
});
I have also tried setting the headers manually but I still cannot get it to work.
After searching around for a bit I found a simple solution. First create the controller and decorate it with HttpPost and ValidateAntiForgeryToken
[HttpPost]
[ValidateAntiForgeryToken]
public void Test_Axios(int id) { }
Then before calling the controller using axios add the following interceptor for the headers. This will define the header as default for all axios api calls
axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
then retreive the token
var token = document.querySelector('token, input').getAttribute('value');
then use the qs library to stringify the call with the token (Be careful! it's Qs and not qs!)
var request = Qs.stringify({ id: 22, __RequestVerificationToken: token });
if you don't wanna pass any parameters then you can just use the following
var request = Qs.stringify({ __RequestVerificationToken: token });
then just call the controller method
axios({
method: 'post',
url: "/controller/Test_Axios",
data: request
});
And you are done! You can now start calling mvc 5 controller, decorated with the [ValidateAntiForgeryToken] attribute.

Why page url changes after PUT method in Web API?

I am using Web API in a MVC Website. This is my Update action in the API controller:
public HttpResponseMessage PutProduct(int Id, ProductModel model)
{
HttpResponseMessage response = null;
if (ModelState.IsValid)
{
model.ProductId = Id;
if (model.Update())
response = Request.CreateResponse(HttpStatusCode.Created);
}
return response;
}
I call it using JQ AJAX from a partial view which is loaded in the Index.cshtml page. The code works fine and the index page does not get called again, instead, the new list is populated in the partial view itself. I am not calling Index page again. But after the response, the page url changes to show like this:
http://localhost:54820/Products/Index?ProdName=Chicken+Soup&Category=Chinese&Price=20
This is my AJAX:
function updateprod(product) {
$.ajax({
url: uri + '/' + product.ProductId,
type: 'put',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(product),
statusCode: {
201: function (data) { //accepted
loadlist();
}
}
})
.fail(function (xhr, textStatus, err) {
alert(err);
});
}
I want the URL to be like this, like what it was initially:
http://localhost:54820/Products/Index
Can anyone help ?
You should look at the response headers.
It seems that your response has a location header used by the user-agent to redirect to URL indicated in the response.
Besides that you should use 201 status-code for created resources, for update is better to use 200 (OK), how you can read in the w3c docs.
Hope it helps.

Calling POST as URL ASP.NET web api

I want to know how to test POST by typing in the url.
Here's my route Config
config.Routes.MapHttpRoute(
name: "myWebApi",
routeTemplate: "api/mywebapi/{action}/{ID}/{DeptID}",
defaults: new { Controller = "mywebapi", ID = #"\d+", DeptID = #"\d+" }
);
programmatically this is how I call POST
I have 3 text boxes and a button. When user clicks on the button the below program gets called
function parseform(button) {
var id = $("#ID").val();
var deptid = $("#DeptID").val();
var name = $("#Name").val();
var inputdata = {
id: id,
deptid: deptid,
name: name
}
if (button.attr('value') === "POST") {
postdata(inputdata);
} else {
console.log("ERROR");
}
}
function postdata(inputdata) {
$("#response").text("Posted");
$.ajax({
type: "POST",
dataType: "json",
url: "api/mywebapi/Post/",
contentType: "application/json",
data: JSON.stringify(inputdata),
xhrFields: {
withCredentials: true
},
success: function (data, status, xhr) {
$("#response").text(status+" - "+data)
},
error: function (xhr, status, error) {
var json = jQuery.parseJSON(xhr.responseText);
$("#response").text(status)
}
});
}
In the controller
[System.Web.Http.AcceptVerbs("POST")]
public void Post([FromBody]mywebapi value)
{
saves to database
}
Here's what I tested
http://localhost:222/api/mywebapi/Post/new newwebapi ({"id":"1","deptid":"2","name":"testing"})
I get error. How to test this?
thanks
R
Since it's a POST request, you can't test it in your browser by typing in an address (those are GET requests, which contain no body).
To test these types of things you can use something like Postman
or Rest Console (if you're using chrome), there's tons of these types of things in whatever your browsers extension store is called.
Some tools you can use are something like Fiddler
this will let you see what the requests and responses look like, and you can change/modify them as well, though it's probably a bit harder to use than something like PostMan or Rest Console (also more powerful)

How to get the response after a POST request in CasperJS

I have this very simple code to read the response from a server endpoint after a post request. Actually I'm saving a data to a database and wait for a response before going to next step
casper.open('http://example.com/ajax.php, {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
});
on ajax.php file I'm trying to echo the POST request in a simple way.
this will let me know easily if I'm getting the right response from the server.
echo json_encode($_POST);
I tried these snippets but I'm unable to get the response.
casper.on('page.resource.received', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('http.status.200', function(resp){
this.echo(JSON.stringify(resp, null, 4));
});
casper.on('resource.received', function(resp) {
this.echo(JSON.stringify(resp, null, 4));
});
I've been facing the same problem POSTing a query to ElasticSearch and I could not retrieve the results.
As far as I can understand if you want to retrieve the data echoed by your script the solution could be this:
this.echo(this.page.content);
or
this.echo(this.page.plainText);
in your function.
For example (my case with ElasticSearch):
/*
* SOME VAR DEFINITIONS HERE
*/
casper.start();
casper.then( function() {
// the next var is very specific to ElasticSearch
var elasticQuery = JSON.stringify (
{
'size' : 20,
'query' : {
'filtered' : {
'filter' : { 'term' : { 'locked' : false } }
}
},
'sort': { 'lastScrapeTime': { 'order': 'asc' } }
}
);
var elasticRequest = {
method: 'POST',
data: elasticQuery
}
this.thenOpen( <<YOUR URL>>, elasticRequest, function (response) {
// dump response header
require('utils').dump(response);
// echo response body
this.echo(this.page.content);
// echo response body with no tags added (useful for JSON)
this.echo(this.page.plainText);
});
}
);
casper.run();
As Roberto points out. You can use this.page.content to show the response. But you need to add the function(response) in your script. For example:
casper.open('http://example.com/ajax.php', {
method: 'POST',
data: {
'title': '<title>',
'unique_id': '<unique_id>'
}
}, function(response){
if(response.status == 200){
require('utils').dump(this.page.content);
}
});
If you want to unit test a REST API, CasperJS is not necessarily the right tool.
CasperJS allows to observe a web browser which is running a web page.
So a more typical approach would be to use CasperJS to load a page that would call your REST API and you would assert the page behavior is correct (assuming the page would make something observable according the AJAX call response).