How can i add a variable in AJAX URL - javascript

I have a function in php that need an id and i need to add a variable in my ajax url the id
PHP Code:
function get_json_selected($purpose)
{
//echo $this->input->post("ids");
$ids = explode(",", $this->input->post("ids"));
$site_url = site_url($this->router->class);
if ($purpose == "EQUIPEMENT"){
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get("equipments a")->result_array();
echo json_encode(array("spares" => $result));
} else {
$this->db->select(
'a.id,
a.manufacturer,
a.description,
a.serial_no,
a.part_no,
a.status,
a.availability,
getReturnStatus(a.id) as return_status',
FALSE
);
$this->db->where_in('a.id', array_unique($ids));
$result = $this->db->get($this->active_table." a")->result_array();
echo json_encode(array("spares" => $result));
}
}
Ajax Code:
this is just example of the variable of id.
$purpose = "EQUIPMENT"; // how can i add this php variable to ajax url
url: "<?=site_url('equip_request/get_json_selected');?>", // this is the current code how can i add id in this url
or is this code right?
url: "<?=site_url('equip_request/get_json_selected/'.$purpose);?>"

var purpose = '<?php echo json_encode($purpose); ?>';
url: 'example.php?=' + purpose;
+ is the concatenator in javascript. hope this helps. spend plenty of time and add plenty of security to echoing that var into javascript. else you could find yourself viction of xss.

Related

Passing js variable to php using ajax does not work

I want to get variable rating_idex in my php file so if is user click button #add-review it should pass in ajax variable and it will get array in php file and send review to the database, but it is not working and I don't see solution
$('#add-review').click(function(){
var user_name = $('#reviewer-name').val();
var user_review = $('#review').val();
console.log(user_name);
console.log(rating_index);
console.log(user_review);
if(user_name == '' || user_review == '')
{
alert("Please Fill Both Field");
return false;
}
else
{
$.ajax({
url:"rating-data.php",
method:"GET",
data:{
rating_index: rating_index,
user_name: user_name,
user_review: user_review
},
success:function(data)
{
$('#review_modal').modal('hide');
load_rating_data();
console.log(data);
}
})
}
});
This is my php code when I can get the variable and send them to the database:
<?php
include 'connection.php';
echo ($rating_index);
if(isset($_GET["rating_index"]))
{
$data = array(
':user_name' => $_GET["user_name"],
':user_rating' => $_GET["rating_index"],
':user_review' => $_GET["user_review"],
':datetime' => time()
);
$query = "
INSERT INTO review_table
(user_name, user_rating, user_review, datetime)
VALUES (:user_name, :user_rating, :user_review, :datetime)
";
$query_run = mysqli_query($conn, $query);
if($query_run){
echo "Your Review & Rating Successfully Submitted";
} else{
echo '<script type="text/javascript"> alert("Something went wrong") </script>';
echo mysqli_error($conn);
}
}
?>
When I am trying to echo ($rating_index) it give me feedback that variable does not exist so it is something with ajax but can't find solution, thanks in advance for any solutions
Instead of echo ($rating_index); try echo ($_GET["rating_index"]); reason being you didn't actually declared $rating_index
if I'm not wrong you want to pass the PHP variable in javascript?
if yes you cant pass the PHP variable in js like this.
var x = " < ? php echo"$name" ? >";
you can pass your PHP variable like this but in only the .php file not in the .js

Get method in php then pass the value into json format

i'm trying to access the value that i've got from get method in my php file. My PHP file would looks like this
<?php
include 'Con.php';
header('content-Type: application/json');
$catid = $_GET["CatId"];
//array declaration
$array = array();
//declaration for the index name of the array
$text1 = "data1";
$text2 = "data2";
$text3 = "data3";
$text4 = "data4";
$text5 = "data5";
$sql = "select `Total Cliks`,`Categories_idCategories`,`Month` from Clicks where Categories_idCategories in ($catid)";
$_sql = mysqli_query($connection,$sql);
foreach ($_sql as $result) {
$Clicks = $result['Total Cliks'];
$Categories_idCategories = $result['Categories_idCategories'];
$Month = $result ['Month'];
if(array_key_exists($Month, $array[$text1]) == false){
$array[$text1][$Month] = $Clicks;
}
elseif(array_key_exists($Month, $array[$text2]) == false){
$array[$text2][$Month] = $Clicks;
}
elseif(array_key_exists($Month, $array[$text3]) == false){
$array[$text3][$Month] = $Clicks;
}
elseif(array_key_exists($Month, $array[$text4]) == false){
$array[$text4][$Month] = $Clicks;
}
elseif(array_key_exists($Month, $array[$text5]) == false){
$array[$text5][$Month] = $Clicks;
}
}
echo json_encode($array);
?>
and then in my Javascricpt file i wanted to make the reference url same as the url that i already get in "get method" in php
so the javascript code would look like this
$(document).ready(function(){
$.ajax({
url : "http://localhost:8888/ClicksChart/ckbox.php?CatId <?php $_GET["CatId"];?>",
type : "GET",
success : function(array){
console.log(array);
alert('Welcome');
In the URL, i wanted to have the url same as the value of my "Get method"
For example : in my get method i have got http://localhost:8888/ClicksChart/ckbox.php?CatId =1,2,3". so the url in the javascript file same as the value of the PHP file.
is there any way to solve this? thank you for the help
You are missing an '=' and an 'echo'
$.ajax({
url : "http://localhost:8888/ClicksChart/ckbox.php?CatId=<?php echo $_GET["CatId"];?>",
You forgot to write echo
url : "http://localhost:8888/ClicksChart/ckbox.php?CatId=<?php echo $_GET['CatId'];?>",
your parameter is missing in ajax
$.ajax({
url : "http://localhost:8888/ClicksChart/ckbox.php?CatId=<?php echo $_GET['CatId'];?>",
type : "GET",
dataType:'json',
success : function(array){
console.log(array);
alert('Welcome');

Undefined index in php when getting value passed from AJAX

I'm trying to get the value that I passed in AJAX to PHP. It shows an alert that says, "Success!" however it when I try to display the value in PHP, it says undefined index. Also I am passing it in the same page.
Whenever I click a button, it opens a modal and I also passing values from that button to the modal. This is evident in my JS code.
<script>
$(document).ready(function(){
$('#editModal').on('show.bs.modal', function (e) {
var id = $(e.relatedTarget).data('id'); //im trying to pass this value to php, e.g. 5
var time = $(e.relatedTarget).data('time');
var name = $(e.relatedTarget).data('name');
var stat = $(e.relatedTarget).data('stat');
var desc = $(e.relatedTarget).data('desc');
alert(id);
$("#task_id_edit").val(id);
$("#new-taskID").val(id);
$("#allotted_time_edit").val(time);
$("#task_name_edit").val(name);
$("#task_status_edit").val(stat);
$("#task_desc_edit").val(desc);
$("#task_id_ref2").val(id);
//AJAX CODE HERE
$(function() {
$.ajax({
type: "POST",
url: 'tasks.php?id='<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>,
data: { "userID" : id },
success: function(data)
{
alert("success!"); //this display
}
});
});
}); // line 1131
});
</script>
PHP CODE:
<?php
$uid = $_POST['userID'];
echo $uid." is the value";
?>
It keeps getting an error that says, undefined index: userID. I am confused. Please help me how to fix this. Your help will be much appreciated! Thank you!
Echo the number in the javascript string.
Currently you will get:
url:'tasks.php?id='1,
The 1 should be concatenated or inside the quote. Try:
url: 'tasks.php?id=<?php $id = isset($_GET['id']) ? $_GET['id'] : ""; echo $id; ?>',
or take that parameter out since it doesn't appear to be being used.
Just put the $_POST['userID'] in a if statement
Undefined index: UserID is not a error it is a warning
<?php
if(isset($_POST['userID'])
{
$uid = $_POST['userID'];
echo $uid." is the value";
}
else
{
echo "Sorry Value cant be printed";
}
?>

how to use javascript variable in php inside a javascript function

i am trying to fetch JavaScript variable "i" in my PHP Code within a JavaScript function in the below code, I find problem in retrieving records, either first record or the last record repeats instead of all records in database.. can you guys help me out ?
Thanks
<?php
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
?>
<script language="javascript" type="text/javascript">
var intervalID = 0;
var time = 10;
MsgPop.displaySmall = true;
MsgPop.position = "bottom-right";
$(document).ready(function(){
var test = MsgPop.open({
Type: "success",
AutoClose: true,
Content: "Welcome to MsgPop!"});
MsgPop.live();
});
function showMessages(){
var n = '<?php
echo $nr;
?>';
var i = 0;
while (i < n){
var name = '<?php
echo $results[i]['name'];
?>';
MsgPop.open({
Type: "success",
Content: name,
AutoClose: false});
i++;
}
</script>
First you have to create a php file which return same array. File contain
$query21 = $mysqli->query("SELECT * FROM register");
$nr = mysqli_num_rows($query21);
while ($row = mysqli_fetch_assoc($query21)) {
$results[] = $row;
}
echo json_encode($results);
exit;
Now you have to call this file using ajax from your javascript code.
$.ajax({
type: "POST",
url: "sql.php", //your file url
})
.done(function (data) {
//you get your array data(json format)
});
now you get that array in ajax response in json format and you can do anything with this data.
Impossible: PHP is a server side language that runs only at server. but javascript is a client side script it only run at your browser only. Php only gives response depends on your requests. The roll of php is end at server. But the javascript work with your response only, that is javascript can work at browser only.
You could try using AJAX, or else it isn't happening. Like said PHP is server-side only... Good luck!
PHP cannot fetch javascript variables. You should try another strategy.
At the server side (PHP), try to store $resuts in a javascript variable.
var results = '<?php echo json_encode($results); ?>';
Then at the browser side, try to access the data with javascript functions.
var name = results[i]['name'];

Getting a value from Javascript in PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 7 years ago.
I am not very experienced in web programming and am attempting to run a script which updates my database.
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts)
<?php
include_once 'accounts/config.php';
$text = ...;
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
}
</script>
I have no idea what to put in the $text section as shown with $text = ...; in order to get the variable texts from above.
EDIT
I have updated my code but the function does not seem to be accessing the PHP file. I am using a button to call the function and I have also tested it so i know the function is being called. My file is called update.php and is in the same directory as this file.
<button onclick="myFunction()">Click This</button>
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: "update.php",
type: "POST",
data: {texts:texts},
success: function(response){
}
});
}
</script>
you can post your $texts value to other php page using ajax and get the variable on php page using $_POST['texts'] and place update query there and enjoy....
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
url: 'update.php',
type: "POST",
data: {texts:texts},
success: function(response)
{
}
});
And your php file will be named as update.php
<?php
include_once 'accounts/config.php';
$text =$_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE `enemies` SET `text`='".$text."' WHERE `id`=1";
$result = mysql_query($query) or die(mysql_error());
?>
PHP runs on the server and then generates output which is then returned to the client side. You can't have a JavaScript function make a call to inlined PHP since the PHP runs before the JavaScript is ever delivered to the client side.
Instead, what you'd need to do is have your function make an AJAX request to a server-side PHP script that then extracts the data from the request body and then stores it in the database.
PHP: "/yourPhpScript.php"
<?php
include_once 'accounts/config.php';
$text = $_POST['data'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text='".$text.'" WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
JavaScript:
function myFunction() {
var texts = document.getElementById("content").textContent;
alert(texts);
// append data as a query string
var params = 'data='+texts;
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
// when server responds, output any response, if applicable
if(http.readyState == 4 && http.status == 200) {
alert(http.responseText);
}
}
// replace with the filename of your PHP script that will do the update.
var url = '/yourPhpScript.php';
xmlhttp.open("POST", url, true);
xmlhttp.send(params);
}
A word of caution: This is not a safe, production-friendly way of updating data in your database. This code is open to SQL injection attacks, which is outside the scope of your question. Please see Bobby Tables: A guide to preventing SQL injection if you are writing code that will go into production.
You are wrong in approach
You should use ajax to post 'texts' value to your php script
https://api.jquery.com/jquery.post/ and create separate php file where you will get data from ajax post and update DB
javascript:
<script>
function myFunction() {
var texts = document.getElementById("content").textContent;
$.ajax({
type: "POST",
url: "update.php",
data: "texsts=" + texts,
success: success
});
}
</script>
update.php
<?php
include_once 'accounts/config.php';
$text = $_POST['texts'];
$tbl_name='enemies'; // Table name
$query = "UPDATE enemies SET text=('$text') WHERE id=1";
$result = mysql_query($query) or die(mysql_error());
?>
i will use PDO if i was you, what you do mysql_query are outdated, if you use my framework https://github.com/parisnakitakejser/PinkCowFramework you can do the following code.
<?php
include('config.php');
$text = $_POST['text'];
$query = PinkCow\Database::prepare("UPDATE enemies SET text = :text WHERE id = 1");
$bindparam = array(
array('text', $text, 'str')
);
PinkCow\Database::exec($query,$bindparam);
$jsonArray = array(
'status' => 200
);
echo json_encode($jsonArray);
?>
place this code in jsonUpdateEnemies.php file and call it width jQuery
<script>
function myFunction(yourText) {
$.post( 'jsonUpdateEnemies.php', {
'text' : yourText
}, function(data)
{
alert('Data updated');
},'json');
}
</script>
its a little more complex then you ask about, but its how i will resolved your problem, :)

Categories