Send js variable to a php .ajax - javascript

I am trying to define id# of a choice and declaring it as variable send to "action.php", the file that connects to DB and inserts values.
Div-block with 5 id's in HTML:
<div class="rate">
<div id="1" class="b-1 rate-btn"></div>
<div id="2" class="b-2 rate-btn"></div>
<div id="3" class="b-3 rate-btn"></div>
<div id="4" class="b-4 rate-btn"></div>
<div id="5" class="b-5 rate-btn"></div>
</div>
anim.js intercepts the click event and declares the variable "therate" as clicked "id":
$('.rate-btn').click(function(){
var therate = $(this).attr('id');
$('.rate-btn').removeClass('rate-btn-active');
for (var i = therate; i >= 0; i--) {
$('.b-'+i).addClass('rate-btn-active');
$.ajax({
type : "POST",
url : "action.php",
data : therate,
success:function(){alert(therate)}
});
};
});
Second part of above code sends "therate" var to an "action.php". But unfortunately id doesn't=( success:function(){alert(therate)} shows me the id# on every choice no problem. "action.php" is in the same folder as "anim.js". I have also tried "/action.php" - no luck. The problem is anim.js does not send "therate" to "action.php". I'm sure this is really stupid and newbie problem but I don't recognize it=( Please, show me the problem! Thanks.

Knowing the php part of the script will help a lot. It is where you decide what data is returned to the client. Typically it goes something like this:
php
$therate = $_POST['therate'];
$response = array();
if(isset($therate)){
$response['status'] = 'success';
$response['therate'] = $therate;
} else {
$response['status'] = 'failure';
$response['message'] = 'Variable therate is not set.'
}
echo json_encode($response);
jQuery
$.ajax({
type : "POST",
url : "action.php",
data : {'therate': therate},
success:function(data){
var o = $.parseJSON(data);
if(o.status == 'success'){
alert(o.therate);
} else {
alert(o.message);
}
}
});
Notice the addition of adding a key identifier to the data we are sending to the server. This allows us to pull the post data serverside easily. Also notice the 'data' in the success function argument. This is the actual data returned from the server. Which you will notice below we can easily parse as json due to using json_encode to the array we passed back to the client.
I hope this helps! Let me know if you have any questions.

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 get javascript value into php variable without reloading the page using ajax

Here I want to get a value from JavaScript to PHP variable without using any POST or GET method.
Here I'm giving HTML code:
<input type="number" name="days" id="days" class="col-sm-2 form-control" placeholder="DAYS">
<input type="number" name="night" id="night" class="col-sm-2 form-control" placeholder="NIGHT">
<button id="generate" onclick="GetValue()" class="btn btn-danger">Generate</button>
Javascript Code
<script>
$(function(){
$("#generate").on('click', function(){
var days = $("#days").val();
var night=$("#night").val();
var base_url = $('#base').val();
$.ajax({
type: 'post',
url: base_url,
data: {'days' : days, 'night': night},
success: function( data ) {
console.log(data);
}
});
});
});
</script>
php code
<?php
$days = $_POST['days'];
$night = $_POST['night'];
echo $days . " " . $night;
?>
Variable value not working.
You can not directly assign javascript variable to PHP variable, that's why ajax is used.
If you want to perform operations on client side variables to server-side without page refresh and using the same page then you have to write the PHP code on the top of the page before anything start of client-side and the use exit to break after the PHP response is completed. and in jquery ajax forget the URL part as you are using the same page for request and response.
Note: Make sure to include jQuery
Cover all the element in form tag so we can simply send data using serialize method.
index.php
<?php
if(isset($_POST) && !empty($_POST['days'])){
$days = $_POST['days']; // you can write the variable name same as input in form element.
$night = $_POST['night'];
//Perform any operations on this variable and send in response whatever you want it will send the response to success function of jquery ajax and you can check response in `data`
echo $days . " " . $night;
exit();
}
?>
<!--<form id='frmsbmt' method='post' action='#'>-->
<input type="number" name="days" id="days" class="col-sm-2 form-control" placeholder="DAYS">
<input type="number" name="night" id="night" class="col-sm-2 form-control" placeholder="NIGHT">
<button id="generate" class="btn btn-danger">Generate</button>
<!--</form>-->
<script>
$(function(){
$("#generate").on('click', function(){
var days = $("#days").val();
var night=$("#night").val();
var base_url = $("#base").val();
$.ajax({
type: 'post',
//url: base_url,
data: {'days' : days, 'night': night}, //$("#frmsbmt").serialize(), //form serialize will send all the data to the server side in json formate, so there is no need to send data seperately.
success: function( data ) {
console.log(data);
//alert(data);
// It will write the response in developer tools console tab or you can alert it.
}
});
});
});
</script>
You can use an AJAX call for this.
function GetValue() {
var str = document.getElementById('days').value;
$.ajax({
type: 'post',
url: 'text.php',
data: {
someValue: str
},
success: function( data ) {
console.log( data );
}
});
}
To answer your question without using any post or get method to retrieve the variable is impossible. One language is a server side language, one language is a client side language, if the two languages never communicate through an established standard and protocol passing a variable between the two are impossible. PHP is translated server side which means the client side interface doesn't really know it exists unless there is an action that is tied to a method namely get or post. An Ajax request uses either POST or GET or one of the other established methods to communicate.

PHP says Undefined even when it is clearly defined in AJAX call?

I'm working on some function which needs to call php using ajax and get some values. How ever I'll post my JS function part below.
JavaScript
$.ajax({
type: "POST",
url: 'php/getAccountJobs.php',
ContentType:"application/json",
dataType:'json',
data:{email:$.cookie("email")},
success : function(arr)
{
for(var i=0 ; i<parseInt(response); i++) // number of jobs are the response we use there
{
var jobmsg = arr[2*i] ;
var imgurl = arr[2*i+1];
$.ajax({
type: "POST",
url: "php/addDivAccountJobs.php",
dataType:'json',
data: {imgURL:imgurl,message:jobmsg},
}).done(function( html ){ alert(html);});
}
}
});
So I checked the console log and saw this following error.
Notice: Undefined index:imgURL
So what I thought was to use isset function to test whether imgURL value is being set or not.
PHP
<?php
session_start();
if(isset($_POST["imgURL"]) && isset($_POST["message"]))
{
$username = $_SESSION["firstname"]." ".$_SESSION["lastname"];
$imgurl = $_POST["imgURL"];
$msg = $_POST["message"];
$fullecho = '<div class="col-md-4">
<div class="profile-card text-center">
<img class="img-responsive"src="'.$imgurl.'">
<div class="profile-info">
<h2 class="hvr-underline-from-center" id="jobOwnerName">'.$username.'</h2>
<div id="jobMessage">'.$msg.'.</div>
</div>
</div>
</div>';
echo json_encode($fullecho);
die();
}
else
echo json_encode("error");
?>
As I expected what I received was error message in alert box.
My Problem
I went through every stackexchange question and tried to find the reason behind it and fix it. but none of those solutions gave me a proper answer. Please can someone help me to find the problem?
when your json property has undefined value its completely disapear from json. so it because arr[2*i] or arr[2*i+1] somewhere get undefined value in the loop

securely passing sensitive data from PHP to javascript

My scenario looks like this, I'm showing database paginated grid on the screen.
I want add a button to download CSV spreadsheet .
so I coded something like this:
$(function(){
var file_complete = false;
var final_sql = $('.initiate_download').val();
var orderby = $('#search_submit').data('orderby');
var $posturl = $url + "index.php/Spawner/launch_spawner";
$('#downloadModal').modal('hide');
$('.initiate_download').on("click", function(e) {
e.preventDefault();
$('#pleaseWait').html($html);
setTimeout(function() {
$.ajax({ // initiate download
url: $posturl,
type: "POST",
data: {
final_sql: final_sql,
orderby: orderby,
report: $report
},
success: function(data) {
var download_id = data;
// console.log(download_id);
check_download_status(download_id);
}
})
}, 2000);
})
});
<div class="row top-buffer">
<button id="search_submit" class="btn btn-primary initiate_download" type="submit" value="<?php echo $sql; ?>" data-orderby="<?php echo $orderby;?>" name="final_sql_lic" >Download List</button>
<span id="pleaseWait"> </span>
</div>
it works fine, but the problem is that you can view SQL with view page option, is there a way around it ?
What most people do is they don't embed the SQL on page, but instead expose URLs that handle the SQL stuff behind the scenes.
In your example, you might create a page like this:
http://website.com/api/csv?select=col1,col2,col3&orderBy=someColumn&where=someCondition
Then your php will take those parameters and generate the sql based off of those and run the query. Make sure you securely handle the input to avoid SQL injection (See http://bobby-tables.com/php.html).
The problem with your current scenario is that someone viewing your source will plainly see that you're passing SQL directly to your server, meaning they can generate their own SQL like: DROP TABLE table1, table2; or worse.

Create a loop to call php function and echo from that function on same html page in javascript

I am trying to create a simple webapp sort of thing that will send push notifications to my clients on button click. Here is a sample page that i have created
I have a file named as sendPush.php
On button click i want to send a push notification which will be echoed as
Notifications sent:
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
"Notification sent to userId : xxxX"
I want to send notifis to all 147 users. Now here is my php code for button click
<script type="text/javascript">
function sendNotif()
{
alert('ok');
}
</script>
<div class="content">
<input type="button" value="Click to Send" onClick="sendNotif();">
<br />
<br />
<label for="push">Notifications sent: </label>
</div>
The problem here i am facing is, i have php function in same app named as sendNotification() that will send notification and echo the result. But I am not sure how can i make a loop of this php function in javascript inside javascript function
function sendNotif()
{
// LOOP HERE
}
If $clients is the list of my clients, how can i send notif to all in a loop using php function in same page as sendNotification($client)
MOdified
<script type="text/javascript">
var lastIdCount = 0;
function sendNotif()
{
var clients = "<?php echo $clients; ?>";
var getPath = "push.php?clientId=".concat(clients['lastIdCount']);
$.ajax({
type: "POST",
url: getPath,
task: "save",
data: {
ajax: "true",
},
dataType : 'json'
}).done(function( msg )
{
alert('ok');
if( msg.status=="1")
{
alert('okasdf');
lastIdCount++;
sendNotif();
}
else
{
alert("Error : "+msg.error);
}
});
}
</script>
In push.php
sample
$resp = array();
$resp['error'] = 'Invalid Request';
$resp['status'] = '0';
$resp['data'] = '0';
You can try first to get all clients you want to send notification and use them ID's for setInterval or setTimeout functions which would repeat your queries. Probably you should
get_clients.php
<?php
$clients_array = array(1,2,6,15,29); /// let's say ID's you got from SQL or w/e you need.
echo json_encode($clients_array); // [1,2,6,15,29]
?>
send_for_client.php
<?php
$id = isset($_POST['id'])?$_POST['id']:false;
if($id){
// do some code you need
echo "Notification sent for id: ".$id;
}
?>
index.html
...
<head>
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(window).load(function(){
$("#send").click(function(){
$.post('get_clients.php',{},function(cid){
obj = JSON.parse(cid);
var cids = obj;
/// cids is array of clients. so, you can do like:
var i = 0;
var interval = setInterval(function(){
if(cids.length > i){
$.post('send_for_client.php',{id:cids[i]},function(resp){
$("#result").append(resp+"<br />");
i++;
});
} else {
clearInterval(interval);
}
},100);
});
});
});
</script>
</head>
<body>
<input id="send" type="submit" name="button" value="Send notifications" />
<div id="result">
</div>
</body>
...
I'm not tested this think, however it should work or simply show idea how you could try to find a solution for your problem. Have in mind this code can have mistakes so.. don't be lazy to check them out, not even do copy/paste :)
I hope it helped even a bit.
javascript and php are run in 2 different places. Your javascript runs in a browser while your php runs on the server. You cant really mix those two.
The way you probably want to do this is, on button click capture the click with javascript and send ajax request to your php script sitting on the server. Than have the php perform push notifications. Once php script is done, return result back to javascript to show it to the user.
You should also use javascript library like jquery which makes things much easier (especially the ajax call).

Categories