Passing session variable through AJAX to PHP file - javascript

My goal is to pass $userId variable (which contains the session variable), through an ajax statement, into a php file that contains an echoed form. The purpose is so that when the form is submitted the session variable can be inserted into the database and then used as a way to identify which entries where done by which users.
Im having a bit of trouble getting the variable data to go to the ajax statement. What am i doing wrong?
<?php
session_start();
if(isset($_SESSION['userid'])) {
$userId = mysql_real_escape_string($_SESSION['userid']);
echo $userId;
echo ' (irrelevant code)...
//button that loads form via ajax...
Add URL
(irrelevant code)... ';
}
AJAX code:
function showAdd(str) {
$('#response').html('Processing Request. Please wait a moment...');
var userId = str;
alert (userId);
$.ajax({
type: "POST",
url: "addUrlForm.php",
data: "userId=" + str,
success: function(msg) {
$('#response').empty();
$('#content01').html(msg).show();
},
error: function () {
alert('error');
}
});
};
EDIT: I took your suggestion (thank-you) and it some-what helped. Now the alert is returning "$userId" variable as a string. How do I make it be recognised as a variable containing the session data, not as a string? I tried "showAdd($userId)" but console is telling me $userId is not defined?.

Since you're sending the userId as a parameter to the showAdd() function you should change your code to:
function showAdd(str) {
var userId = str;
// ...
}
or simply rename the parameter to userId:
function showAdd(userId) {
// use userId here
]
To make you above code send the correct userId and not the string $userId to the function you should wrap your output string in double quotes or output it directly:
echo 'Add URL';
or:
echo "<a href='#' class='small button radius expand' onClick='showAdd($userId);return false;'>Add URL</a>";

I do not understand why would you use $(this) when the userid is already present and is passed as function parameter.
Change this:
var userId = $(this).attr('userId');
To:
var userId = str;

Related

How to bring a json result into PHP

I have some results from a fetch.php using json and I successfully brought all results to my bootstrap modal HTML screen.
When the Modal is being shown, I would like to run a MYSQL query using a value coming from the same json I used for the modal, however I can't put this value into a PHP variable to run the SQL query.
How can I get this?
I am trying to bring the same value I input into the HTML textbox (modal), but it is not working. I also tried to use the value from json '$('#PCR').val(data.PCRNo);)', but nothing happen.
This is the script to collect information from database using fetch.php file:
<script>
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
var pcr_number = $(this).attr('id');
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
</script>
This is the PHP code
<?php
//trying to get the value I have included on #PCR (textbox) which has ID='PCR' and name ='PCR' **
$PCR= $_POST['PCR'];
//running now the code to check if the database has the value and return the desired response to be shown **
$sql1 = mysqli_query($dbConnected,"SELECT * FROM change_management.tPCN");
while ($row1 = mysqli_fetch_array($sql1)) {
if ($row1['PCRNo']==$PCR){
echo $row1['PCNNo'];
echo "<br/>";
}else{
}
}
?>
I would like include value from this val(data.PCRNo) json return into the $PCR variable, so the MYSQL query is going to work
There are a number of quite basic logical issues with your code which are preventing it from working.
1) data: { pcr_number: pcr_number}- the name pcr_number doesn't match the value PCR which the server is searching for using $_POST['PCR'];. The names must match up. When making an AJAX request, the name you gave to the form field in the HTML does not matter (unless you use .serialize()) because you are specifying new names in the data parameter.
2) Your SQL query doesn't make sense. You seem to be wanting to read a single row relating to a PCR number, yet your query makes no usage of the input PCR value to try and restrict the results to that row. You need to use a SQL WHERE clause to get it to select only the row with that ID, otherwise you'll fetch all the rows and won't know which one is correct. (Fetching them all and then using an if in a PHP loop to check the correct one is very inefficient.) I wrote you a version which uses the WHERE clause properly, and passes the PCR value to the query securely using prepared statements and parameters (to project against SQL injection attacks).
3) Your output from the PHP also makes no sense. You've told jQuery (via dataType: "json" to expect a JSON response, and then your code inside the "success" function is based on the assumption you'll receive a single object containing all the fields from the table. But echo $row1['PCNNo']; echo "<br/>"; only outputs one field, and it outputs it with HTML next to it. This is not JSON, it's not even close to being JSON. You need to output the whole row, and then use json_encode() function to turn the object into a JSON string which jQuery can parse when it receives it.
Here's a version of the code containing all the above changes:
JavaScript:
$(document).ready(function(){
$('#table').on('click', '.fetch_data', function(){
$.ajax({
url: 'fetch.php',
method: 'post',
data: { pcr: $(this).attr('id'); },
dataType: "json",
success: function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
});
});
PHP:
<?php
$PCR = $_POST['pcr'];
$stmt = $dbConnected->prepare("SELECT * FROM change_management.tPCN WHERE PCRNo = ?");
$stmt->bind_param('s', $PCR);
$stmt->execute();
$result = $stmt->get_result();
//an "if" here will cause a single row to be read
if ($row = $result->fetch_assoc()) {
$output = $row;
}
else
{
$output = new StdClass();
}
$stmt->free_result();
$stmt->close();
//output the result
echo json_encode($output);
?>
N.B. I would potentially suggest studying some tutorials on this kind of subject, since this is a fairly standard use case for AJAX/JSON, and you should be able to find samples which would improve your understanding of all the different parts.
P.S. Currently the PHP code above will return an empty object if there is no matching row in the database. However, this is probably an error condition (and will cause your JavaScript code to crash due to trying to read nonexistent properties), so you should consider how you want to handle such an error and what response to return (e.g. 400, or 404, and a suitable message).
You need to first return json from php by using json_encode.
Inside this loop
while ($row1 = mysqli_fetch_array($sql1)) {
$data = array('PCRNo' => 'itsvalue', 'PCC' => 'itsvalue', 'Creation_Date' => 'itsvalue')
}
print json_encode($data)
store all the data in an associative array and then convert it into json using json_encode and return the json.
Use json data in you ajax file
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
var data = JSON.parse(data);
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
}
});
Below is the changed script to store different values in $PCR variable
<script>
$(document).ready(function(){
var i = 1;
$('#table').on('click', '.fetch_data', function(){
if(i == 1) {
var pcr_number = $(this).attr('id');
} else {
var pcr_number = $('#PCR').val();
}
$.ajax({
url:'fetch.php',
method:'post',
data:{pcr_number:pcr_number},
dataType:"json",
success:function(data){
$('#PCR').val(data.PCRNo);
$('#PCC').val(data.PCC);
$('#PCR_Creation').val(data.Creation_Date);
$('#PCR_Status').val(data.Stage);
$('#Required_Completion').val(data.Required_Completion);
i++;
}
});
});
});
</script>

How to access a javascript variable inside a php query?

I want to access a javascript variable inside a php query
function myFunction2(){
Total=parseInt(point2)
<?php
$con->query("UPDATE eventlist SET P2 = $this.Total WHERE Eid=$PID");
?>
}
I want the query to set p2=value of total
I understand that php is a serverside script and I cant do this like this. What is an alternative to this.?
EDIT
ok i got this on the JS side
function myFunction2(){
var Total = parseInt(point1)+parseInt(point2);
$.ajax({ url: 'ajax.php',
data: {'total' : Total},
type: 'post',
dataType:'json',
success: function(output) {
alert(output);
},
error: function(request, status, error){
alert("Error");
}
and if i put
echo $_POST['total']
in ajax.php i get an alert with the value passed. So i think the value is being passed properly.
But what i need to do is a Mysql Query.
$con->query("UPDATE eventlist SET P2 = $_POST['total']; WHERE Eid=1");
Something like this. How do i do this
Try send javascript value to another php page which contain your query
function myFunction () {
var param = "value";
$.post('query.php', { postvalue: param}, function(data) {
//do what you want with returned data
//postvalue should be the name of post parameter in your query page
})
}
Change your PHP in this way:
$total = $_POST['total'];
$con->query("UPDATE eventlist SET P2 = $total WHERE Eid=1");

Is this piece of jquery ajax code correct?

I am making a simple web chat application using ajax,php,javascript and mysql.
What I am trying to do here is to avoid fetching the whole database after an interval of 1 sec(which is normally done in basic chat application ) but rather I want to fetch and display(by appending) also those chats which have been newly entered into the database by any user.
To implement this ,First when the user first opens the chat screen the whole database is loaded in the chat window(not shown in this code snippet),and then I am using the variable msgid to fetch the latest value of MSg_ID (which is the auto-increment primary key in my chat table) through an ajax request to the page 'Msg.php' which returns the required value of msg_id.
Now using this value of msgid and comparing it with the max value of Msg_ID every second in the database through the ajax request to the page 'Chat3.php'.
If the Max value of Msg_ID has changed the required rows are returned . After this I m updating the value of 'msgid' using the same earlier ajax request to the page 'Msg.php'
The pages Msg.php and Chat3.php are working perfectly ,as I have tested them thoroughly.
My question here is what is the problem in my code , why is not working?
Can we use an ajax request inside a ajax call back function or not?
What else can be a probable source of error?
Any input will be valuable :)
If you have any problem in understanding the code,leave a comment.
'#yyy' and '#zzz' are random div elements which i am using to test the data value of ajax callback function.
I can even post the rest of the code if it helps.
<script type"text/javascript">
$(document).ready(function() {
var dept = '<?php echo $deptId; ?>';
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
$('#yyy').html(data);//this displays the correct value
var msgid=data;
}
});
var interval = setInterval(function() {
$.ajax({
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid},
success: function(data) {
if(data!='bad'){
//$('#messages').prepend(data);
$('#zzz').html(data);//does not display any value although Chat3.php is returning the correct value.
//below ajax request to update the value of msgid
$.ajax({
url: 'scripts/php/Msg.php',
data: {dept:dept},
success: function(data) {
var msgid=data;
$('#zzz').html(data); //not displaying anything although above one is was displaying
}
});
}
}
});
}, 1000);
});
</script>
Here is my Msg.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept){
$query= "SELECT Msg_ID,Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
$messages =array();
while($message=mysql_fetch_assoc($run)){
$messages[] =array('msgid'=>$message['Msg_ID'],
'sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
$dept=$_GET['dept'];
$messages = get_msg($dept);
$x=count($messages);
if($x){
foreach($messages as $message) {
if($x==count($messages)){
echo $message['msgid'];
}
$x--;
}
}
?>
Here is my Chat3.php
<?php
require '../../includes/database/connect.db.php';
function get_msg($dept,$msgid){
$query1= "SELECT MAX(Msg_ID) as msg_id FROM chat" ;
$run1=mysql_query($query1);
$row = mysql_fetch_assoc($run1);
$result =$row['msg_id'];
$messages =array();
if($result>$msgid)
{
$query= "SELECT Sender, Message ,Time_stamp FROM chat WHERE Dept_ID='$dept' AND Msg_ID>'$msgid' ORDER BY Msg_ID DESC" ;
$run=mysql_query($query);
while($message=mysql_fetch_assoc($run)){
$messages[] =array('sender'=>$message['Sender'],
'message'=>$message['Message'],
'time_stamp'=>$message['Time_stamp']);
}
return $messages;
}
else
{
return $messages;
}
}
$dept=$_GET['dept'];
$msgid=$_GET['msgid'];
$messages = get_msg($dept,$msgid);
if(count($messages)){
foreach($messages as $message) {
echo '<strong>'.$message['sender'].' Sent</strong><br>';
echo $message['message'].' <i><small><div align="right">'.$message['time_stamp'].'</i></small></div>';
}
}
else {
echo 'bad';
}
?>
The problem is the msgid
In your first AJAX Request you are setting the variable var msgid=data; which is in local scope.
I think you are trying to access that variable in the second AJAX request while sending the datas
url: 'scripts/php/Chat3.php',
data: {dept:dept,msgid:msgid}, // Trying to access the local variable of previous ajax request
EDIT:
Try removing the var from var msgid=data; in your first AJAX request. Removing var will make the variable GLOBAL, Although its not good to pollute the global scope, but you can definitely try out this for the time being

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

Send json from javascript to php

I have a page where users do some stuff and on selecting next, I want to redirect them to a php file, called "Step2.php" along with some JSON information.
I built my json string and it looks like this:
[{"name":"IMG_20130726_182336.jpg","size":2280709,"type":"image/jpeg","width":null,"height":null,"lastModified":1374852216000,"fileExtension":"jpg","orientation":1,"displayed":true,"attributes":[{"title":"Name: ","value":"IMG_20130726_182336.jpg"},{"title":"Date: ","value":"no date"}]}]
Now, I sent it trough jquery POST like this:
jsonData = JSON.stringify(serializableAttributes);
console.log(jsonData);
$.ajax({
type: 'POST',
url: 'Step2.php',
data: {"jsonData" : jsonData},
success: function(msg) {
console.log("Json Sent! " +msg);
window.location("")
},
error: function(request,msg){
console.log("Error : " + msg);
}
});
Question: Why I can`t receive anything in my Step2.php file? Am I wrongly redirect user to that page?
Code in the Step2.php files looks like this:
if(isset($_POST["jsonData"])) {
$json = $_POST["jsonData"];
var_dump(json_decode($json, true));
} else {
echo "NO";
}
It always shows NO.
Ok so I think you misunderstand how AJAX works. You ajax request sends the json to you php and should then respond to it with the appropriate return, in your case a var_dump.
This won't hold the json in the php at all and if you go and request the php file without the POST request you won't get anything else but the output "NO" as there is no POST data you are sending.
If you do want to send a json to you php you do what you are doing now and listen to the request responds which you can see in your inspector. I am not clear on what you ultimately want to do with the data so I don't know if this is the right way.
You can't do it like this. That's not how AJAX and POST work.
If you're simply going to Step2.php, try sending it to the page as part of the URL.
Instead of your AJAX function, simply do:
var jsonData = [YOUR DATA];
window.location.href="Step2.php?json="+jsonData
Or if PHP created the JSON string, you could store it as a SESSION variable.
EDIT: To venture a bit further on the SESSION variable route...
Have your AJAX script as it is now, but make a new PHP file. In this example we'll call it foo.php. Have your foo.php file setup like so:
session_start();
if($_POST){
if(isset($_POST['jsonData'])){
$json = $_POST['jsonData'];
$_SESSION['jsonData'] = $json;
//CREATE A JSON RESPONSE INIDCATING SUCCESS
echo '{ "success" : 1 }';
}
}
Your SUCCESS function of the AJAX call could analyze the response for the success code. If it's "1" redirect to the Step2.php page.
Just make sure that you're calling session_start() at the top of each page.
You can post JSON to PHP
jsonData = JSON.stringify(serializableAttributes);
console.log(jsonData);
$.post("Step2.php", { json: jsonData }, function(msg) {
console.log("image name = " + msg);
});
PHP, you simply parse:
if(isset($_POST['json'])){
$json = $_POST['json'];
$data = json_decode($json);
$image = $data[0];
echo $image->name;
$atributes = $image->attributes;
foreach($atributes as $atrribute){
//echo 'title '.$atribute->title;
}
}
Try this code in my work:
<?php
if(isset($_POST["jsonData"])) {
$json = $_POST["jsonData"];
$json = str_replace('\\', '', $json);
var_dump(json_decode($json, true));
print_r($json);
} else {
echo "NO";
}
?>

Categories