I have an Opencart website, I am currently trying to use ajax at the frontend to pass data to php controller in the backend, but I am unable to get the value from the request in backend
here is the frontend ajax code:
$.ajax({ url: 'index.php?route=checkout/cart/addAll',
type: 'post',
data: 'product_list= test' ,
dataType: 'json',
success: function(json) {});
at the backend controller, I am trying to retrieve variable "product_list" but it is not working
$products = $this->request->post['product_list'];
$logger->write("products to add to cart is"+ strval($products));
the last statement keeps printing 0 to the log file
any help with this ? what is wrong here?
I also tried
$products = json_decode($this->request->post['product_list'], true);
with same results
Ok, fixed, Ajax was not the issue, it was accessing the variable from server side, so I used $_POST
instead of $this->request->post and it is working fine
So I just did this
in file catalog/view/theme/defaulttemplate/common/home.twig I add this code at the end of the file
$(document).ready(function() {
$.ajax({url:'index.php?route=checkout/cart/addAll',
type: 'post',
data: 'product_list= test' ,
dataType: 'json',
success: function(json) {}
});
});
and in file catalog/controller/checkout/cart.php on line 479 I add this
public function addAll(){
print_r($this->request->post);
}
And I see this in my console http://joxi.ru/krDlvPdfKGejar
All I did was correct your js code. hope this helps.
Related
I'm having a problem trying to implement an AJAX request into a pre-existing website that I didn't create.
I have no problems sending the data to PHP as a GET request, however POST requests and trying to access $_FILES is returning null.
Here is the AJAX:
var someData = 'test';
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
data: ({someData}),
success: function(data) {
console.log(data);
}
});
PHP:
<?php echo json_encode($_POST['someData']); ?>
I believe the cause of the issue might lie within the htaccess file or be related to some other redirect that is in place on the site. This website was built by a past staff member at the company, and I've had this same problem using AJAX POST with several other sites built by them.
As changing from POST to GET works fine I don't think there is any problem with my very simple code.
Is there some way I can test if the data is going missing due to a redirect, or could there be some other cause?
First check the browser dev tools ctr+shift+J and see if there is a redirect. If not then
You need to set your datatype to json and depending on what version of JQUERY you are using you might have to use "type" instead of "method" if your JQUERY version < 1.9.0
var someData = 'test';
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "json",
data: ({someData}),
success: function(data) {
console.log(data);
}
});
PHP code:
header("Content-Type: application/json", true);
If that doesnt work then make sure your URL is absolutely correct. No extra slashes or spaces.
I have managed to figure this out, there is a 302 redirect in place for all .php extetensions to a url without the extension. There was also an error in my code.
Changing the URL in the AJAX to "post-data" without the .php extension allows me to see $_POST in PHP.
My other problem with not being able to access files came down to the way I was trying to send FormData with AJAX.
My original code to do this was:
var someData = 'test';
var fData = new FormData();
fData.append("images", $("input[name='fileUpload']").prop("files")[0]);
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
contentType: false,
processData: false,
data: ({someData, fData}),
success: function(data) {
console.log(data);
}
});
The problem being that you can't send FormData and other variables at the same time. Instead I have to append my other data to the FormData:
var someData = 'test';
var fData = new FormData();
fData.append("images", $("input[name='fileUpload']").prop("files")[0]);
fData.append("someData", someData);
$.ajax({
url: "post-data.php",
method: "POST",
dataType: "JSON",
contentType: false,
processData: false,
data: fData,
success: function(data) {
console.log(data);
}
});
I'm using jstree on a project and attempting to save my tree to a database.
I'm obtaining the tree data as follows:
var tmp = $('#tree').jstree(true).get_json();
console.log(tmp);
This produces a JSON object in the console as I'd expect:
However when I post this to a PHP script using jquery...
$.ajax({
type: 'POST',
url: '/saveTree',
data: {'tree': tmp},
success: function(msg) {
console.log(msg);
}
});
... It is showing a PHP array of my data:
The script which I have at /saveTree displays the POST data in the tree array post key:
var_dump($this->request->data['tree']);
I assumed since the data I'm posting to the script is in JSON format I'd need to json_decode() it at the other end? If not, why not?
I've also tried adding dataType: 'json', in the ajax request but that makes no difference.
What's happening here?
Please note the PHP script at /saveTree is running in CakePHP 2.x so the line of PHP above is equivalent to var_dump($_POST['tree']) in regular PHP.
If you want send the data as string you can JSON.stringify(tmp);
tmp = JSON.stringify(tmp);
$.ajax({
type: 'POST',
url: '/saveTree',
data: {'tree': tmp},
success: function(msg) {
console.log(msg);
}
});
I am using codeigniter. When I update database values using website UI, it gets updated in database but on user interface it shows old values only. After refreshing page it shows updated values.
Please suggest solution on the same.
Thanks.
You need to use AJAX. Something like this:
data = {"slug" : slug};
$.ajax({
url: '', //url of controller where you would update the code using model
method: 'POST', //method
data: data, //data to be updated
dataType: 'json',
contentType: 'json'
})
.done(function(res){ //Upadte html; Note the data in 'res' variable is the data which your above 'url' would echo
})
.fail(function(res){//handle here if error occured
});
Hope this is a good starting point for you to learn AJAX. I would have helped you more if you provide us with some code.
I have tried tons of thing to get json data from another url with jQuery. I have working code in php, but dont have any idea how to do it in jquery.
PHP:
$skin = rawurlencode($market_hash_name);
$skin2 = str_replace('%0A', '', $skin);
$link = "http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=".$skin2;
$json2 = file_get_contents($link);
$obj2 = json_decode($json2);
$mediumPrice = $obj2->median_price;
Example of jQuery that i have tried:
$(document).ready(function () {
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
});
Typically a easy way around that is to create a Proxy, that is just a fancy word for saying have something else send and receive the data between the end points.
This can be as simple as using ajax to a PHP file on your server, from that PHP file using CURL to your endpoint, back to the output through echoing the return of the CURL script.
That way you can get around the restrictions on JavaScript. You mention
I have working code in php
So it should be relatively trivial to pipe the ajax call through that code and back.
Ok so instead of doing this
$.ajax({
type: 'GET',
url: 'http://steamcommunity.com/market/priceoverview/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'jsonp',
success: function (data) {
alert(data.median_price);
}
});
Do this
$.ajax({
type: 'GET',
url: 'http://yoursever.com/proxy.php/?country=EU¤cy=3&appid=730&market_hash_name=AWP%20%7C%20Worm%20God%20(Factory%20New)',
dataType: 'json',
success: function (data) {
alert(data.median_price);
}
});
Then in proxy.php or whatever you chose to name it, use your working php code to make the call then simply return that data to the client through JSON as per normal AJAX. Then you are technically calling the remote sever using PHP and don't have the cross domain issue. But because you are using your sever as a Proxy you can still do it in real time.
I'm using the $.ajax call to send data to a PHP page:
$.ajax({
type: 'POST',
url: "ajax_more.php",
data: "userid=1"
});
In ajax_more.php I'm trying to read the value of the userid:
$user_id=$_POST['userid'] ;
However, I'm getting an error as PHP doesn't find a value for the index userid.
What am I doing wrong?
UPDATE
I'm sending another ajax variable in the same manner:
$.ajax({
type: "POST",
url: "ajax_more.php",
data: "lastmsg="+ ID,
cache: false,
success: function(html){
$("div#listednotes").append(html);
$("#more"+ID).remove();
}
});
and it is working fine, so using <?php print_r( $_POST ) ?>, the return value is:
Array ( [lastmsg] => 38 ).
You might have used some .htaccess redirection such as removing or adding the "www" to all web requests. Any change on those affects your POST request parameters.
To get this solved, assure you enter your Ajax url as it should be according to your .htaccess rules.
$.ajax({
type: 'POST',
url: "ajax_more.php",
data: {"userid" :1}
});
I cut and pasted your code exactly and it works. So it doesn't look like you are doing anything wrong in the code provided. If you are running other code before checking the $_POST array, that code could be altering its contents or unsetting it.
Your data should be in Key value pairs. and not the way you specified it.
So:
data: "userid=1"
is wrong, should be:
data: {"something" : "value"}