use a global javascript variable in ajax php mysql - javascript

I have a variable 'user_cache' stored in local storage: Now I am doing a $.getJSON call
<script>
user_data = JSON.parse(localStorage.getItem("user_cache"));
$.getJSON("query.php", { productId: productId}, function(data) { /*do something*/});
</script>
Query.php does a php_mysql database query:
<? php
if( $_REQUEST["productId"] )
{
$productid = $_REQUEST['productId'];
/*Database connection*/
include_once("php_includes/db_conx.php");
$sql = "DELETE FROM USERPRODUCTCOLLECTION WHERE Product_ID = $productid";
if ($db_conx->query($sql) === TRUE) {
echo "Success";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$db_conx->close();
}
?>
My question is that I also want to use the object 'user_data' in the query.php file to do that database query but I dont want to pass 'user_data' in $.getJSON. Is it possible to use 'user_data' object inside 'query.php' file without having to pass it in the $.getJSON?

Unfortunately that will not be possible. You must pass the data to the php file in order to utilize it. Are you leaning away from passing the user data because it is passing it as a GET variable (in the URL)? If so, consider using a jQuery.post() call instead. This way the data will be posted instead of in the URL.
See : http://api.jquery.com/jquery.post/

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

ajax get empty array from json_encode()

So I have this php class where i have a function that get users from a PSQL database but the AJAX keep loging empty array in the console:
public function getUsers(){
$query = pg_query(self::$DBH, "select id, name, email, admin from users order by name;");
$result = array();
$i = 0;
while ($row = pg_fetch_row($query)) {
$result[$i] = $row;
$i++;
}
return $result;
}
I use a phphandler file to call the function from ajax
:
<?php
include_once $_SERVER['DOCUMENT_ROOT'].'/bdd.php';
require_once 'modele_backend.php';
$module = new Modele_Backend();
echo json_encode($module -> getUsers());
?>
and finaly there is the AJAX call
$(document).ready(function(){
$("#user_email").on("input", function(){
// Print entered value in a div box
$.ajax({
url: 'modules/mod_backend/backendHandler.php',
type: 'post',
dataType: 'json',
success: function(response) { console.log(response); }
});
});
});
The problem is that js keep showing empty array in the console.
The json_encode works fine as json_last_error = 0.
I Tried replacing the return of my getUsers() function by
echo json_encode($result);
to test if the function manage to encode my array and it did show up like a JSON on the page so this is not a encoding of my array problem. Still when AJAX get the result of the json_encode function it display an empty array.
Thanks for any help !
Necro.
Solution 1
You have to set content type of header in your php file before echo
header('Content-type: application/json');
Solution 2
change dataType in your ajax code to html
or remove it to return default dataType (default: Intelligent Guess (xml, json, script, or html))
and then convert returned string to json using javascript JSON.parse() method .
It turned ou the problem was not json_encode at all, it was a problem with my static DB class wich I was includong twice with the AJAX call.
Thanks anyway for the support

POST-GET session variable (javascript-php) -javascript takes the previous variable but not last created

From the selected value (from the form) I create a variable (var parcela).
var parcela;
$(document).ready(function(){
parcela = localStorage.getItem("parcela");
if (parcela !== '') {
$('#parcela').val(parcela);
}
$("#parcela").on('change',function() {
selectBoxVal_1 = $('#parcela').val();
if (typeof(Storage) !== "undefined") {
localStorage.setItem("parcela", selectBoxVal_1);
} else {
alert('Sorry! No Web Storage support..');
}
location.reload();
});
});
From the created variable (parcela), I create a session variable in PHP.
$.post("phpscripts/session.php", {"parc_id": parcela});
PHP (session.php)
<?php
session_start();
$parcela = $_POST["parc_id"];
$parcela_int = (int)$parcela;
if($_POST){
$_SESSION['parcela_id'] = $parcela_int;
}
?>
After that, the created session variable urge to another php script
query.php
<?php
session_start();
require("common.php");
$user_id = htmlentities($_SESSION['user']['id_korisnika']);
$parc = $_SESSION['parcela_id'];
try
{
$stmt = $db->prepare("SELECT y_cent, x_cent FROM parcele WHERE id_korisnika='$user_id' AND id_parcele='$parc' ");
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
....
This all works perfectly!
However, when I call a php script with query (query.php) in javascript, there is a problem. JS takes the previous session variable instead of the last selected.
$.ajax({
url: 'phpscripts/query.php',
type: 'GET',
success : function(data) {
chartData = data;
//console.log(chartData);
...
Does anyone know what the problem is? I'm trying for two days to solve this ...
Note: The javascript code is contained in a single script.
I solved the problem. I had to extract part of javascript code that calls the php script into a separate script. I called the new JS script with jQuery getScript() Method.
Thank you #knets.

PHP : get response fro $.ajax call

I want to fetch data based on ajax call
this is my code to get the id
<h3> <a class='click' data-id='<?=$rows["id"];?>'><?=$rows['title'];?></a</h3>
This is my jquery code
$(document).ready(function() {
$(".click").on('click',function() {
var id= $(this).attr("data-id");
alert(id);
$.ajax({
type: "POST",
url: "getevents.php",
data: {id:id},
dataType: "html",
success: function(response){
console.log(response);
}
});
})})
</script>
getevents.php
<?
if(isset($_POST['id'])){
echo $_POST['id'] ;
}
$singleevent = mysqli_query($link, 'SELECT * FROM `events` WHERE `id`=."'$id'" ') or die('error');
while($row= mysqli_fetch_array($link , $singleevent)){
print_r($row);
}
?>
$_POST['id']; gets printed in console but not the response . i tried echo and print_r() both in while loop but nothing is in response .
Please help me with this
There are a couple of problems in your PHP. First, you forget to reassign the variable, then you improperly concatenate the variable in your query. You also probably do not want the query to run if the id is not set, so you need to re-arrange your brackets:
<?
if(isset($_POST['id'])){
$id = $_POST['id'] ; // set the variable for the query
$singleevent = mysqli_query($link, "SELECT * FROM `events` WHERE `id` = $id") or die('error');
$row= mysqli_fetch_array($singleevent, MYSQLI_ASSOC);
print_r($row);
}
?>
I am assuming that your $link is a good and correct connection to your database. You also do not need a while loop, assuming that the id selects a single row of data. You also need to fetch the array properly, using the result of the query and MYSQLI_ASSOC like this:
$row= mysqli_fetch_array($singleevent, MYSQLI_ASSOC);
Which I have included in the code block.
NOTE
If PHP short tags are not enabled you will need to change <? to <?php
WARNING
Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe!

To pass argument from a php file to javascript file

I am facing some trouble in passing a simple variable from a php to javascript file.
I have a form which submits through a php file which basically updates the record at the server end. And if the updation is succesful, I just want to pass the message back to the javascript where I can update it on a certain section of the page.
My codes are:
Javascript code - abc.js
function expand_cards(project, SlNo)
{
name = project['project_name'];
j = "ShowForm-"+SlNo+"";
s = "<div class='edit_project_card'>";
s += "<form method='post' action='Edit_Project.php'><div class='project_form'>
// Form Contents
s += "<div class='Form_button'> <input type='submit'> </div>";
s += "</form></div>";
$("#"+j+"").html(s);
response = $.parseJSON(data);
$("#"+j+"").html(response);
}
PHP file - Edit_Project.php
<?php
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
echo json_encode($response);
mysqli_close($connection);
?>
But the problem is the screen is printing $response variable as it is and not exactly passing it back to the javascript function as wished. I know I can use a $.post function which can can receive argument but it's a long form and passing parameters would be difficult in that.
Can anybody help me out here ?
Thanks
Dirty, but it will work:
<script type="text/javascript">
var my_var = <?php echo $some_variable; ?>
// Do something with the new my_var
some_func(my_var);
</script>
I wouldn't do too much detailed stuff with this though, if you can use AJAX that is better.
Note, this can only work on a .php file or one being read as such.
you'll want to do some variable handling in your php side because if the string is empty you'll end up with a
var my_var = ;
which will break the script. so something like:
var my_var = <?php echo "'" . $some_variable . "'";?>
if it's a string or if it's a number:
var my_var = <?php echo (empty($some_variable) ? null : $some_variable);
This is int specific, I'm sure you can come up with a function that will handle it better.
References:
empty function http://php.net/manual/en/function.empty.php
shorthand if http://davidwalsh.name/php-ternary-examples
Since you're submitting the form to the PHP file directly the browser loads the Edit_Project.php file as it would a normal page. If you want a json response to the already loaded page you'll have to use $.post or $.ajax
You can post the whole form simply by using serialize() like this:
$('#form_id').on('submit', function(e) {
// Stop the browser from posting the form
e.preventDefault();
// Post the form via Ajax
$.ajax({
url : 'Edit_Project.php',
type : 'POST',
data : $(this).serialize(),
success : function(response) {
// Here you do the HTML update
$("#"+j+"").html(response.reply);
}
});
});
The Edit_Project.php needs to be changed as well:
//The updation stuff at the server end
if (!mysqli_query($connection,$sqlquery)) {
$response = "'Error in your code: ' . mysqli_error($connection)";
}
else {
$response = "1 record updated";
}
mysqli_close($connection);
/*
* As SuperDJ suggested, you need to tell the browser that it's
* receiving a JSON ojbect although he did use the wrong content type:
*/
header('Content-Type: application/json');
/*
* According to php.net most decoders should handle a simple string as
* json object but to be safe always encode an array or an object since
* you can't know how the decoder will respond.
*/
echo json_encode(array('reply' => $response));

Categories