Local storage javascript variable to php - javascript

Thanks for your time in reading this post.
I am facing issues while passing javascript variable to php file.
Please look at the below code for your reference which i have written in checkout.php.
$.ajax({
type: "POST",
url: "checkout.php",
data: localStorage.getItem("simpleCart_items"),
success: function(data) {
console.log("result"+JSON.stringify(data))
My php code :
<?php $data=$_POST['data']; echo $data;?>
Redirect is happening but $data value is null.

The { data: data } is passed only to the first checkout.php call using POST method. When you redirect the user with window.location.href it has nothing to do with the previous call.
Depending on your use-case you could in the first call to checkout.php save data to session and the access it in the second call but it really depends what you're trying to do.
Edit: jQuery's data parameter is the entire payload you want to send to server. So if you were sending:
$.post({
data: {
message: 'Hello'
}
...
});
It'll be available in checkout.php as $_POST['message'] and not $_POST['data']['message'].

Related

how to use key/value pairs in ajax call for jquery data option

Ive been checking out how to add variables to a ajax request which I can use in my server side script. I checked this stackoverflow post here and checked the jquery api docs here for a ajax request. I am getting error variable in my code is not defined.
I have this line in my code
return $.ajax({
type: 'GET',
url: '/users/show',
data: {'currentusershow': variable},
});
I was wanting it to do something like this with the results so I can keep all my different script in the one file.
if ($.get("currentusershow")) {
// do something here
}
else if...
i am not sure how to add the value to my code?
Also my url does not work going to the show.js.erb where my code is kept.
You need to declare and assign some value to the variable before the request.
Also you need to change the method type from GET to POST.
var variable = 'some data';
/*$.ajax({
type: 'POST',
url: '/users/show',
data: {currentusershow: variable},
success: function (response) {
// Do something with respsone
},
error: function () {
alert("error");
}
});*/
$.get( "/users/show", {currentusershow: variable} )
.done(function( response ) {
//do something with the response here.
});
Mamun was kind of right here as I did not explain myself very well in my question but I thought I would post this and clarify my question with what I was trying to do. The ajax call should be
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentusershow: 'variable'},
});
where the key is currentusershow and the value variable is a string and leave out defining the variable else where in the code. That way the url comes through correctly to the server being /users/show?currentusershow=variable. And in my destination file add my ruby code there to use the variables. In my question that code was more a php type code as I did not know what I was doing at the time.

Sending data from javascript to php using via Ajax using jQuery. How to view the data back?

I know this question has been asked a lot as I have been googling since morning but I just can't think what's going on in my code.
I have a index.php (which is my website) that uses forms to receive information from user, then invokes a javascript file separately which in turn invokes another backend php file (this backend php file queries a database using mysql and does some stuff).
The problem is I am not sure what information is getting passed to the backend php from my js. I have just learnt jQuery and Ajax so I really don't know what is that small mistake I am making.
From my understanding, the backend php does its stuff and passes the value to javascript to be displayed on the web page. But my data is not getting sent / displayed. I am getting a error 500 internal server error.
Here are the pieces of code that are currently is question:
Javascript:
var data1 = {week:week, group:grp_name};
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
success : function(response){
alert ("success !");
},
error : function(response){
console.log(response);
alert("fail!");
}
})
});
PHP backend (remindUsers.php):
<?php
if (isset($_POST['week'])) {
$week = $_POST['week'];
}
if (isset($_POST['group'])) {
$group_name = $_POST['group'];
}
echo $week;
?>
I am ommiting out the sql code pieces because they work fine.
Edit: Now my status code is 200, response text is also ok . My response text shows a weird "enter' sign next to the actual response text expected. Is this normal ? And it is still going into the error block , not the success block of code.
I can not fully answer your question because I need more debug information about whats going on but theres 2-3 things about your code bugging me a little that might fix your bug.
First, use isset in your backend like this:
if (isset($_GET['your_input_name'])) {
$someData = $_GET['your_input_name'];
}
The isset part is very important here. Set it up and try it again. If you stop having a 500 error. Its probably because your data was never send to your backend or because your not checking the good input name.
Second, About input name. I can see in your code that you send:
var data1 = {week:week, group:grp_name};
So in your backend you should use the name of the value like this to retrieve your data:
$week = $_POST("week");
Third, I am not a json pro but maybe your json is not valid. Even if he is ok I suggest you build a "cleaner" one like this:
var data = [
{ 'name' : 'week', 'value' : week}
];
And finally, if you are using forms to send data to php then you can use something like that :
var myForm = $("#myForm").serializeArray();
$.ajax({
url: 'yourUrl',
type: "GET",
data: myForm,
dataType: 'json',
success: function(res){
//your success code
},
error: function(){
//your error code
}
});
I hope this helps.
You can't have these tags <body>,... in your PHP response over json.
It must be only:
<?php
$week = $_POST("data");
$json = json_decode($week);
echo json_encode($json);
?>
Remove the comment on
//data : {week :week}
And set a variable week with a valid value:
data : {week :week}
and so:
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php",
data : {week :week} ,
success : function(response){
console.log(response);
},
In order to see what is the shape of response.
You are doing a couple things wrong. First, you don't want to stringify your data before sending it to the server. You want to send JSON, so your commented line is the correct one. There is also a problem with the PHP. The data going to the server will look like:
{week: "Something"}
So in your PHP, you want to access the data like:
$_POST["week"];
USE THIS
PHP
$week = $_POST['data'];
$json = json_encode($week);
echo $json;
JS
$.ajax({
dataType: "json",
type: "POST",
url : "php/remindUsers.php"
//data : {week :week} ,
data: {data:{week:'week', group:'grp_name'}} ,
success : function(response){
alert ("success !");
},
error : function(response){
alert("fail!");
}
})
I would say wrap the php in a function and echo the json. Also its good to check if there was POSTed data, and if not return an error message. This is not tested, but will hopefully point you in the right direction.
<?php
function getJSON() {
if (isset($_POST["data"] && !empty($_POST['data']) ) {
$week = $_POST["data"];
$json = json_decode($week);
echo $json;
} else {
echo "There was a problem returning your data";
}
}
getJSON();
?>
Actually as I write this, I realized you could try these headers in your AJAX POST:
accepts: 'application/json',
contentType: 'application/json',
dataType: 'json'
Hope that helps.
It worked. I figured out the answer thanks to another SO post.
TIL : Even if server response is ok, the error condition will be triggered because the data returned to javascript from php is not json,since i had explicitly mentioned dataType: "json" in the ajax request.
Link here:
Ajax request returns 200 OK, but an error event is fired instead of success
Thanks folks for helping me and steering me in the right direction. Cheers!

jQuery AJAX reload specific div

I have the following code, as part of a code to add some value to a database.
After executing the $.ajax succesfully, I want a specific div (with class 'lijst') to be reloaded with the refreshed data.
$.ajax({
url: \"frontend/inc/functions/add_selectie.php\",
type: \"POST\",
data: ({ 'p_id' : p_id, 'v_id' : v_id, 'pd_id' : pd_id }),
cache: false,
success: function()
{
$(\".lijst\").hide().fadeIn('slow');
}
});
However, with this solution, only the div is refreshed, not the actual PHP variables that are specified in there. When I refresh my browser manually, the values are updated.
How can I refresh the div and also update the variables?
According to the jQuery.ajax documentation, the function signature of "success".
Type: Function( PlainObject data, String textStatus, jqXHR
jqXHR ) A function to be called if the request succeeds. The function
gets passed three arguments: The data returned from the server ...
So in other words:
success: function(data) {
$(".lijst").html(data).hide().fadeIn('slow');
}
Actually, the PHP variables specified in the html are worked at the sever part. PHP variables in the html have replaced by the string of there value when it is ready to be sent to the browser. And your ajax request will cause PHP to update database. So when you have sent the request and then refresh the page, PHP will replace the varables in the html again.
According to this above, your ajax request and the server repsonse are not aware of the PHP variables's existence. So you must update the content yourself.
Maybe you will do something like this:
success: function(data) {
$(".lijst").hide();
$(".title").html(data.title); // $(".title") may be a tag that surround a PHP variable
$(".content").html(data.content); // the same as $(".title")
$(".lijst").fadeIn('slow');
}

accessing jquery variable in PHP in same page

I want to access javascript variable in php of the same page.
I'm doing a AJAX call and I get a JSON data.
This AJAX call is being fired upon a dropdown change.
I wanted to run few PHP functions on the same in the AJAX function based on the dropdown value.
$.ajax({
type: "POST",
url: "data.php",
data: { dropdown1: dropdown1,
variable2: variable2
},
async: true,
dataType: 'json'
}).done(function(result) {
// chart functions
<?php
$dropdown_val = $_POST['dropdown1']
?>
})
Is it possible that I can send the form value inside of the page itself to PHP function?
Suggest me please...
Unfortunately this isn't possible. You'd have to run another AJAX call and put your PHP inside that. Alternatively, couldn't you put the PHP inside the data.php file and run it from within that?

Is it possible to send the JS variable to parameter of the php function

Is it possible the Javascript variable value to the php url parameter? please see following code and give a suggestion how to do this?
Html code:
foreach($rd as $data){
echo "<tr><td>".$data[role_name]."</td><td>".$data[role_description]."</td><td>Edit</td><td>".$ih->button_js(t('Delete'), "deleteRole('".$data['role_id']."')", 'left', 'error')."</td></tr>";
}
in this code i call JS function deleteRole?():
script:
function deleteRole(myvar) {
if (confirm('<?php echo $delConfirmJS ?>')) {
location.href = "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>";
}
}
In my controller page i receive the myvar as string not the value?
controller.php
public function delete($id){
echo $id;
exit;
$delete = roleinfo::delete($id);
$this->redirect('/role/add_role'); }
this echo print "myvar" only not a value? Please suggest me its write way or not ? else how to do this?
thanks
Kumar
You can't send or assign a JS variable directly to PHP function or variable, because of JS is a client side language and PHP is a server side language.
If you want to send you JS variable, one way is - you can send a ajax request to server, and then your variable will be available in php, and can use it.
Here is sample ajax format:
$.ajax({
cache: false,
url: base_path + '{file_name_where_you_want_to_receive_that_value}',
type: 'post',
data: {
myvar: myvar
},
success: function(data) {
// when you provided url procedd the req. then success will call.
}
})
And in [file_name_where_you_want_to_receive_that_value] assing that value to some variable and use it.
Do you have a form or smthg? I suppose the easiest way would be with a hidden field where you just modify the value via JS and send it to PHP with POST. Its not a clean or professional way, but easy to implement and does its job.
The most simple AJAX request you can make is the following (using jQuery for simplicity, you can search for how to do an AJAX request without jQuery):
function deleteRole(myvar) {
$.ajax({
url: "<?php echo $this->url('/role/add_role/', 'delete', 'myvar')?>",
}).done(function(data) {
console.log(data);
$( this ).addClass( "done" );
});
}
This will create a new request to the specified URL, and basically run the controller action. You will have the request response in the javascript variable data.
More info here.

Categories

Resources