How to assign javascript value to php variable without using cookie - javascript

I am recieving data form controller in ajax. Then I should assign it to php variable but without using cookies. How to do it?
My code:
$.ajax({
url: '/controller/action',
type: 'post',
data: {
id: id,
},
success: function(data){
if (data) {
//here I should assign data to php variable
}
if (!data) {
console.log('no data');
}
}
});

try using this demo code
<script>
if (data) {
var a =data;
<?php $abc = "<script>document.write(a)</script>"?>
}
if (!data) {
console.log('no data');
}
</script>
<?php
echo $abc;
?>

you can create a link with JavaScript that includes a GET variable. ones clicked php gets involved
code:
http://example.org/index.php?q1=blablabla
Php code:
if(isset($_GET['q1']) {$ff = $_GET['q1']}

Related

Passing value to php from local storage using Ajax

I.m want to pass the values from js to php that is stored in local storage
js
let cartItems = localStorage.getItem("productsInCart");
var jsonString = JSON.stringify(cartItems);
$.ajax({
url:"read.php",
method: "post",
data: {data : jsonString},
success: function(res){
console.log(res);
}
})
php
<?php
print_r($_POST)
?>
on .php im getting just "array ()"
using #reyno's method with all the code in the same file called 'store_user_order.php'
<?php
if(isset($_POST["data"])) {
print_r($_POST["data"]);
} else {
?>
<button>SEND</button><br/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.3/jquery.min.js"> </script>
<script>
const cartItems = localStorage.getItem("productsInCart");
const jsonString = JSON.stringify(cartItems);
$("button").click(function() {
$.ajax({
url: 'store_user_order.php',
method: 'post',
data: {
data: jsonString
},
success: function(res) {
$('body').append(res);
},
error: function(err) {
$('body').append(err);
}
});
})
</script>
<?php } ?>
This should work if you have items in the localstorage
While testing, for checking values use method: "get", make sure that your test values aren't huge - you will see submitted values in the address bar.
For testing (php + MySQL) I always use this method:
success ? changes() : errors_list();`
I don't use js, so deal with syntax yourself, please.
on .php im getting just "array ()"
You received an empty $ _POST array - nothing was sent.
Because there was nothing to send, or there was an error sending

How to get Variable in php when passing through javascript?

I am passing my variable through an AJAX request in javascript. How to assign this the value of this variable to a new variable in the tabs.php file?
JS code
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",});
success: function(data) {
console.log(data);
}
});
Output of console is nothing.
You don't need to assign it. Your value will be accessible on tabs.php by the _POST array as it $_POST['m_count'].
I also strongly suggest you to test if the array variable m_count is set to avoid eventual php error when m_count is missing by doing the following:
if (isset($_POST['m_count']))
{
# If possible set the content type header to json app.
# header('Content-Type: application/json');
$message = "m_count value is equal to: " . $_POST['m_count'];
echo json_encode([ "message" => $message ]);
}
Also you you have an extra }); before the success function in your javascript.
var build = {
m_count : document.getElementById('count').value,
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",
success: function(data) {
console.log(data);
},
});

Getting Alert from ajax request

I have editable html table of user Information. There are some columns such as user_ID, branch_ID etc. when I am going to change the branch_ID of the user I want to check the particular user has tasked assigned to him or not. If he has tasks then update is not allowed. for that I am using the following java script part.
if(field=='branch_ID'){
$.ajax({
type: 'post',
url: 'check_user.php',
data: {udata: user_id},
success: function (data) {
// message_status.text(data);
}
})
}
In check_user.php
$user_id= $_POST['udata'];
$sql1="SELECT * FROM assign_task WHERE user_ID=$user_id";
$query1=mysqli_query($con,$sql1);
if(mysqli_num_rows($query1)>0){
echo"you can't update";
return false;
}
else{
echo"ok with it".$sql1;
}
The thing is I want the respond from check_user.php as an alert and return false to stop updating the content. As I am new to jQuery please help me.
You can use JSON to pass more complex data:
PHP :
if(mysqli_num_rows($query1)>0){
echo json_encode(array("success" => false));
}
else{
echo json_encode(array("success" => true,
"message" => "ok with it".$sql1));
}
Javascript:
success: function (data) {
var jsonData = JSON.parse(data);
if(jsonData.success){
alert(jsonData.message);
}
}
Remember to do more advanced checking on your variables and types first!

Serialzing form and posting ajax to function

I am trying to pass the form field values to a php function located into a file. The problem is that I can't understand how to pass that serialized form data to the function from this ajax to a function in php.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
$('#insert_news').serialize(); // how do I add this data here?
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
This ajax passed the values to the file ajax.php right beyond. And from ajax.php is called the function located in functions.php.
ajax.php
if (isset($_POST['action']) && $_POST['action'] == 'insert_news') {
$cp->insert_into_table('newss', array(
'NewsTitle' => $_POST['title'],
'NewsDescrption' => $_POST['description'],
'Date' => date('Y-m-d H:i:s'),
'status' => '1'
)
);
}
function.php
public function insert_into_table($table_name, array $data){
foreach($data as $col=>$value) {
$cols[] = $col;
$values[] = '\''.$value.'\'';
}
$cols = implode(', ', $cols);
$values = implode(', ', $values);
$this->db->query("INSERT INTO $table_name ($cols) VALUES ($values)");
echo "INSERT INTO $table_name ($cols) VALUES ($values)";
}
The issue is serialize() produces a URL encoded key value paired string, so you can't mix that with your data object.
You can use serializeArray() to get an array of objects, representing the form elements, then iterate over them and add them to a data object:
var data = { action: 'insert_news' };
$.each($('#insert_news').serializeArray(), function(){
data[this.name] = this.value;
});
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: data,
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
Side note: your PHP code is vulnerable to SQL Injection. Consider using a Prepared Statement instead of concatenating user input into the SQL.
You can pass serialized data via ajax to a function the way you are doing but your code needs slight modification.
$('#insert_news').submit(function(event) {
event.preventDefault();
var form = $('#insert_news').serialize();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: {
action: 'insert_news',
serializedData: form // use variable to assign data here
},
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
I think you can use alternate like this
First : add hidden input for action on your form
<input type="hidden" name="action" value="insert_news"/>
Then your ajax post like this
$('#insert_news').submit(function(event) {
event.preventDefault();
$.ajax({
type: 'POST',
url: 'includes/ajax.php',
data: $(this).serialize(), // $(this) is from <form id="insert_news">
success: function(datas) {
$('#message').html(datas).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
And then use print_r on your ajax.php
print_r($_POST);
$('#insert_news').submit(function(event) {
var name = $("#t1").val();
var pass = $("#t2").val(); //add more var as u need
var key = 0;
var formName = new FormData();
formName.append(key++,name)
formName.append(key++,pass) //append the the var to formdata
$.ajax({
url : 'includes/ajax.php',
dataType : 'text',
cache : false,
contentType : false,
processData : false,
data : formName,
type : 'post',
success : function(data){
$('#message').html(data).show() /*fadeIn(1000).fadeOut(1000)*/ ;
}
});
});
this works fine for me :-)

How to get values out of object in php

I have a javascript that is collecting data like this:
var chk = [];
$("input[name=row_sel]:checked").each(function() {
chk.push ({
"value": $(this).attr('id'),
"type" : $(this).data('typo')
});
});// JavaScript Document
The chk array is beeing sent via ajax into a php script
How can I interpret that array?
I have tried to do like this:
$chk = $_REQUEST['chk'];
foreach ($chk as $info) {
}
The ajax that is sending the array is:
$.ajax({
url: 'view/debts/debts_validation.php',
type: 'post',
dataType: 'json',
data: { 'chk[]' : chk },
beforeSend: function() {
$("#dt_debts_processing").css("visibility","visible");
},
complete: function() {
$("#dt_debts_processing").css("visibility","hidden");
$("#dt_debts_processing").html('Checking compatibility...');
},
success: function(json) {
if (json['status']) {
location = '?route=home/debts/insert';
cForm.hide().append('body').submit();
return false;
} else {
$.sticky("Current selection is not available for multiple edit.", {autoclose : 5000, position: "top-right", type: "st-error" });
}
}
});
I think you are trying to send an JavaScript object via ajax.
You cant do that. You need to serialize your object with the JSON.stringify() function.
Then you can reserialize this string with the json_decode() function.
I hope that helps.
PS:
Dont access the Request-Data with the $_REQUEST variable. Use $_GET or $_POST
this?
data: { 'chk[]' : chk },
you can perfectly send it like:
data: { chk : chk },
and access the array via:
$chk = $_POST['chk'];
foreach ($chk as $info) {
echo "value: ".$info["value"];
echo "type: ".$info["type"];
}
Just do it like this:
$chk = $_REQUEST['chk'];
foreach ($chk as $info) {
echo $info;
}

Categories

Resources