How to make a request to delete a row in DB? - php

I have read everything on this topic - and still in a fog.
I made a CRUD functional, and the question is - how to test/ how to use delete or update functions?
In my routes.php there is a one string:
Route::resource('templates', 'Vendor\App\Controllers\TemplateController');
In controller destroy and update functions are implemented.
So i'm trying to test delete. When a send DELETE request - i've got a error
RouteCollection->methodNotAllowed(array('GET', 'HEAD', 'POST'))
As far as i googled, method must be POST, but one of the form fields - named _method must have the value DELETE So i use the postman for testing, and got the same error:
What am i doing wrong? how to make a delete request?

You are doing the right request, but to the wrong URL. As noted in the corresponding docs, the URL for the DELETE request should be /templates/{id}. Try it eg. with templates/1

Related

Deleting a file on server by DELETE form method

I am trying to delete a file on my server using DELETE method in my html form.
I have a file ,and url to that file is :
http://example.com/file2.php
I am using the following code for deleting the file :
<form action="file2.php"method="DELETE">
<input type="submit"value="delete file">
</form>
When I press "delete file" button I get redirected to "file2.php" but it is not deleting the file.
Server is receving the request header in GET method :
GET /file2.php HTTP/1.1
instead of DELETE :
DELETE /file2.php HTTP/1.1
Does someone know why the delete method is not working? or how can I delete my file using DELETE method?
Most browser do not support DELETE as method parameter for <form ...>. Indeed it's not even part of the HTML specification:
The method and formmethod content attributes are enumerated attributes with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET method.
The keyword post, mapping to the state POST, indicating the HTTP POST method.
And here is some kind of explanation:
It seems that we currently do not understand how PUT and DELETE will be useful for HTML forms.
For DELETE, it's indeed easy to create a useful request. However, server implementations usually respond with 200 and a minimal response body ("deleted") or 204 (no content). So it's not clear how this can be used in a web application.
For PUT, it seems there's no real use case as long as the web page doesn't have full control over the payload, and also can set the content type.
Please consider removing this feature until there's a clearer understanding about what it's good for.
Frameworks like laravel provide method spoofing:
<input type='_method' value='DELETE' />
This will override the method of the request and will - for example - call a destroy function:
Route::delete('/items/{id}', 'ItemController#destroy');
If you don't use a framework, you can try to mimic this behaviour:
if($_SERVER['REQUEST_METHOD'] === 'DELETE' || (isset($_REQUEST['_method'] && $_REQUEST['_method'] === 'delete') {
...
}
Mozilla only specifies only GET and POST
I have 2 recommendations:
Use a POST to send data to your PHP code and handle it from there
Don't actually delete stuff that simple. Create some function that will just say it is deleted till after you are really sure it has to be gone

http bad request, can't find the bad character(s)

Hello i'm using cakephp and i need to update the status throug an action method
the method in the controller is this
function setEstado($id, $id_usuario, $estado,$vars) {
i'm using serialize to get all the fields of the form (when i update the status i need to update all the changes done, so... This is my request
OrdenesReparaciones/setEstado/36725/46/6/_method=PUT&data%5BOrdenesReparacion%5D%5Bguardando%5D=&data%5BOrdenesReparacion%5D%5Bid%5D=36725&data%5BOrdenesReparacion%5D%5Bidusuarioa%5D=46&data%5BOrdenesReparacion%5D%5Bcliente_id%5D=14915&data%5BOrdenesReparacion%5D%5Bnumero%5D=220498&data%5BOrdenesReparacion%5D%5Btipo%5D=Presupuesto&data%5BOrdenesReparacion%5D%5Bnro_orden_anterior%5D=&data%5BOrdenesReparacion%5D%5Bfecha%5D=19-08-2015&data%5BOrdenesReparacion%5D%5Bfecha_prometido%5D=20-08-2015&data%5BOrdenesReparacion%5D%5Bfecha_asignado%5D=31-08-2015&data%5BOrdenesReparacion%5D%5Bcliente%5D=EDUARDO+DO+CAMPO&data%5BCliente%5D%5Bdireccion%5D=&telefono=&celular=099668032&email=&data%5BOrdenesReparacion%5D%5Barticulo%5D=MARTILLO&data%5BOrdenesReparacion%5D%5Bmodelo%5D=MD+908&data%5BOrdenesReparacion%5D%5Bmarca_id%5D=120&data%5BOrdenesReparacion%5D%5Bmarcass%5D=120&data%5BOrdenesReparacion%5D%5Bimportador%5D=R.+BALAGUER+S.A.&data%5BOrdenesReparacion%5D%5Bimportadors%5D=R.+BALAGUER+S.A.&data%5BOrdenesReparacion%5D%5Bdetalle_marca%5D=NEO&data%5BOrdenesReparacion%5D%5Bfecha_compra%5D=00-00-0000&data%5BOrdenesReparacion%5D%5Blugar_compra%5D=&data%5BOrdenesReparacion%5D%5Bnro_comprobante%5D=&data%5BOrdenesReparacion%5D%5BPrecio_compra%5D=&data%5BOrdenesReparacion%5D%5Bdesperfecto%5D=&data%5BOrdenesReparacion%5D%5Baccesorios%5D=&data%5BOrdenesReparacion%5D%5Bserie%5D=&data%5BOrdenesReparacion%5D%5Barea_id%5D=4&data%5BOrdenesReparacion%5D%5Bsub_taller%5D=0&data%5BOrdenesReparacion%5D%5Bsubtaller_id%5D=&bitacora_add=&data%5BOrdenesReparacion%5D%5Bpresupuesto_taller%5D=R-C%2C+R-M%2C+INTERRUPTOR%2C+ASEGURAR+TROMPA%2C+2+RULEMANES%2C+CARBONES%2C+AROS+DE+COMPRESION%2C+LIMPIEZA%2C+LUBRICACION%2C+AJUSTE%2C+REPARAR+CONEXIONES&respuestos=&data%5BOrdenesReparacion%5D%5Bmonto%5D=0.00&data%5BOrdenesReparacion%5D%5Brecibo_sena_id%5D=0&data%5BOrdenesReparacion%5D%5Bprecio_asignado%5D=4700.00&data%5BOrdenesReparacion%5D%5Brecibido_por%5D=22&data%5BOrdenesReparacion%5D%5Bvino_por%5D=22&data%5BOrdenesReparacion%5D%5Btipo_envio%5D=25&data%5BOrdenesReparacion%5D%5Bnro_remito%5D=&data%5BOrdenesReparacion%5D%5Bcant_llamados%5D=0&data%5BOrdenesReparacion%5D%5Bobservaciones%5D=5%25+26-08-2015+09%3A07%3A28+MAT+-+Bitacora+taller%3A+R-C%2C+R-M%2C+INTERRUPTOR%2C+ASEGURAR+TROMPA%2C+2+RULEMANES%2C+CARBONES%2C+AROS+DE+COMPRESION%2C+LIMPIEZA%2C+LUBRICACION%2C+AJUSTE%2C+REPARAR+CONEXIONES++++++26-08-2015+09%3A05%3A46+MAT+-+Cambio+precio%3A+4700.00++26-08-2015+09%3A01%3A52+MAT+-+Cambio+precio%3A+3200.00++19-08-2015+11%3A41%3A09+JORGE+-+Asignada+a+sector%3AINDUSTRIAL++19-08-2015+11%3A41%3A08+JORGE+-+Accesorios%3A+++19-08-2015+11%3A41%3A02+JORGE+-+Maquina%3A+MARTILLO++19-08-2015+11%3A40%3A39+JORGE+-+Se+cambiĆ³+tipo+de+orden+a+PRESUPUESTO+++++++++++++++++++++19-08-2015+11%3A40%3A13+SANTIAGO+-+Orden+creada++26-08-2015+09%3A07%3A28+MAT+-+CONFIRMADA&data%5BOrdenesReparacion%5D%5Bdestino%5D=&data%5BOrdenesReparacion%5D%5Balerta%5D=
it have the following pattern Controller=OrdenesReparaciones action=setEstado id=36725 id_usuario=46 estado=6 vars=_method...
i have the following error
Bad Request
Your browser sent a request that this server could not understand.
I just don't know which is the special char that is damaging my request, i already replace %2F which is '/' with '-' in the dates values, but i can't see here which character should i replace, please, any ideas or advices will mean a lot for me.

KnockoutJS - Sending a form containing the value of a javascript object results in a timeout

I have a problem that occurs when I try to send a form, if a particular field type is present, the page returns a time out.
I'm using KnockoutJS's mapping plugin to map an object coming from the server. I'm able to modify the object and I want to send it back.
To do so, I created a computed function that returns the result of ko.toJSON to which I pass this particular object. Then, this value is put in an hidden input to be sent back to the server:
<input type="hidden" name="a" data-bind="value: exportToJSON()" />
When I'm sending the form with this input field, I get an error 7:
Error 7 (net :: ERR_TIMED_OUT): The operation timed out.
Here's a JSFiddle representing my code
http://jsfiddle.net/etiennenoel/4EXSy/17/
I suspect that the problem is caused because the data in the field sent via POST is not escaped ?
Update 1
Someone suggested to use ko.mapping.toJSON. However, doing that results in an empty string, see it here: http://jsfiddle.net/etiennenoel/4EXSy/18/
Update 2
Now, results input is not empty, thanks to #abc123: http://jsfiddle.net/etiennenoel/4EXSy/19/.
However, I still get a timeout when sending the POST Data. You can see the POST data that is sent when I send my form in my code: http://pastebin.com/hNRm4zdZ
Update 3
I'm using symfony2 and I'm starting to think that the problem might be linked to something in symfony2 since when I copy and paste the form on a simple .html file, the data gets sent...
Update 4
I deleted Symfony2 dev.log, clicked on the button to send the form, got the time out error and unfortunately, the log is still empty.... Also, all the php and apache logs do not show anything...
Update 5
I finally decided to test my symfony website on another server and it works on this other server... Now this is getting weird, why isn't it working in my local server ? I'm using MAMP Pro as a local server
You are returning ko.mapping.toJSON(self.playersEvaluation) you cannot access a property of knockout without calling the function since it is actually a function.
To get it to return proper JSON please do the following:
function appViewModel() {
var self = this;
self.playersEvaluation = ko.observableArray();
self.exportToJSON = ko.computed(function() {
return ko.mapping.toJSON(self.playersEvaluation())
}, this);
}
JSFiddle: http://jsfiddle.net/abc123/WReza/1/
To use Console Easily: http://jsfiddle.net/abc123/WReza/1/embedded/result/
Luckily since you are using the ko.mapping plugin this will work because it does the following:
All properties of an object are converted into an observable. If an update would change the value, it will update the observable.
Arrays are converted into observable arrays. If an update would change the number of items, it will perform the appropriate add/remove actions. It will also try to keep the order the same as the original JavaScript array.
Taken from ko.mapping

No element found FF - Error visible in firebug

I'm creating a global high score table. The JavaScript sends the username and score to the PHP through some AJAX functions and POST. The PHP script then takes the variable, and compares the score values to the file on the server. It then puts the new score where it should go on the score table, and rewrites the file.
I had it working last night, but now, when I call the function, it displays my code instead, and firebug gives the error, "No element found". I'm not sure what I did between then and now, but I just can't figure this one out.
This is my first time using PHP and AJAX, so I'm not sure where or what the error is.
Any help would be appreciated!
The exact error:
Timestamp: 4/13/2013 1:59:18 PM
Error: no element found
Source File: file:///C:/wamp/www/ajax.php
Line: 84, Column: 3
Source Code:
?>
If I cannot help you solve this issue, I will delete this answer, but I wanted to post it like this so you can better read my suggestions.
Start by changing your HandleResponse function to this:
function HandleResponse(response)
{
console.log(response);
document.getElementById('ResponseDiv').innerHTML = response;
}
and post the result that appears above the error, in firebug.
What we are doing here is adding a way for us to see if any data was actually returned from the AJAX request. A call to console.log tells the browser to print the given argument to the console (in your case, firebug).
UPDATE 1
In your comments, you stated that nothing displayed when you logged the value of response. This means that you received nothing back from the server (in terms of data, at least).
My next suggestion is that you change the call to MakeRequest to the following:
<input type='button' id="test" onclick='MakeRequest("*");' value='Global Highscore Table'/>
Like before, leave the console.log line in the HandleResponse method, and post the result that appears above the error in firebug.
Here, we are setting your MakeRequest to make a request that passes a wild-card query parameter. At the time of this suggestion, I did not realize that the requested file expected two arguments, nor that passing a wild-card would error the script. However, this was still a good thing to do, as we found a new error, which tells us that the request is being received.
UPDATE 2
Now, cut and paste everything from your "ajax.php" file to your notepad or another, similar application. Then, set the following to be the only content of the "ajax.php" file:
<?php echo "Request received and response sent"; ?>
Again, post the result of the console.log.
Here, we are taking a step back from fixing the complex code, and we are going back to the basics. All we want to do, here, is verify that we can both send the request and receive a response.
If "Request received and response sent" is successfully returned as the response of the request, then we know that the error lies in ajax.php, and not in the request. If it is not, we know that there is a problem with the request (be it a server issue or the request, itself). If the latter is the case, there could still be a problem with ajax.php, but we must first fix the request.
UPDATE 3 (final solution)
Issue was found to be due to not correctly running on the local server.

AJAX & PHP:GET parameters causing Flickr api key error

I'm trying to send a URL with aFLickr API key to fetch results for a given photo tag. The Ajax code should return the XML to my browser. However the URL structure with parameters seems to cause a problem in my setup:
**the HTML file:**
...
url="api.flickr.com/services/rest/?method=flickr.photos.search&api_key=75564008a468bf8a284dc94bbd176dd8&tags=paris"
request.open("GET","xmlget.php?url=" + url + nocache, true)
...
**the 'xmlget.php' file:**
...
echo file_get_contents($_GET['url']);
...
error: code="100" msg="Invalid API Key (Key has invalid format)">
the link works fine if tested in the adress bar so there must be a breakdown somewhere when the URL is processed.
i tried wrapping it into encodeURI but no luck :(
Note: related post
You need to use encodeURIComponent instead of encodeURI to actually get that string encoded.
May I make 2 suggestions?
just pass the search parameters to xmlget.php and do the rest there even if it means having to pass a service type if you are using that generically
I don't remember what all a Flickr api key gets you, but it's generally a bad thing to post anything called an "api key" in public. In addition to the question, that includes sticking it in javascript that an end user can access.

Categories