Catch Ajax data variables in PHP? - php

I'm trying to get the data used below to be caught in my alives.php page.
Essentially, alives.php requires a variable $passcode.
How do I pass the content of data below as the variable $passcode through a POST request?
<script>
$(document).ready(function() {
$('#alive').click(function () {
var data = '<?php $row['code']; ?>';
$.ajax({
type:"GET",
cache:false,
url:"alives.php",
data:data, // multiple data sent using ajax
success: function (html) {
}
});
return false;
});
});
</script>
alives.php
<?php
require("database.php");
$checkvote = "SELECT code FROM votes WHERE code = '$passcode'";
$updatealive = "UPDATE votes SET alive = +1 WHERE code = '$passcode'";
$addvote = "INSERT INTO votes (code, alive) VALUES ('$passcode',+1 )";
$checkvoterlt = mysqli_query($con, $checkvote);
if(mysqli_num_rows($checkvoterlt) > 0) {
$result = mysqli_query($con, $updatealive) or die(mysqli_error());
} else {
$result = mysqli_query($con, $addvote) or die(mysqli_error());
}
mysqli_close($con);
?>

So much is wrong.
Problem 1: You are specifying a GET request: $.ajax({ type:"GET",. If you want it to be POST:
$.ajax({
type:"POST",
Problem 2: Your javascript data variable should be key: value pairs like:
var data = { 'passcode' : code };
Then in PHP get the data with $_POST['passcode']

This sort of passcode should NOT be passed to the client side, as it can be easily manipulated.
Instead, store such information in a $_SESSION variable (assumes you've started your PHP with session_start), as this will keep the value safe, pass it to all pageloads where it may be needed, and be impossible to manipulate (while it is possible to hijack someone else's session, a malicious user still won't be able to actively change the value)

Related

AJAX Call Return PHP Value Empty

i have a problem about ajax call, i dont get what exactly why i still getting this empty success call. i tried the past solution to solve this but i don't know what the cause of this.
as you can see this my table then when i click the action of update, delete, or, add, even print_r($_POST) it's still empty.
then when i go to console i got this error.
the value of selected attr still send to the php file
heres my code :
$(document).on('click', '.update', function(){
var user_ID = $(this).attr('id');
$.ajax({
url:"datatable/account/fetch_single.php",
method:"POST",
data:{user_ID:user_ID},
dataType:"json",
success:function(data)
{
console.log(data);
$('#account_modal').modal('show');
$('#username').prop("disabled", true);
$('#username').val(data.user_Name);
$('#email').val(data.user_Email);
$('#pass').val(data.user_Pass);
$('#con_pass').val(data.user_Pass);
$('#level').val(data.level_ID).change();
$('#status').val(data.user_status).change();
$('#action').val('Edit');
$('#operation').val('Edit');
$('.modal-title').text('Edit Account Info');
$('#user_ID').val(user_ID);
}
})
});
fetch_single.php
include('db.php');
include('function.php');
if(isset($_POST["user_ID"]))
{
$output = array();
$statement = $conn->prepare(
"SELECT * FROM `user_accounts`
WHERE user_ID = '".$_POST["user_ID"]."'
LIMIT 1"
);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
$output["level_ID"] = $row["level_ID"];
$output["user_Name"] = $row["user_Name"];
$output["user_Pass"] = decryptIt($row["user_Pass"]);
$output["user_Email"] = $row["user_Email"];
$output["user_status"] = $row["user_status"];
}
echo json_encode($output);
}
or it's might be the cause of problem is the design template?
i solve this issue, in my requested php file i change my $_POST to $_REQUEST if your data in ajax look like
data:{user_ID:user_ID}
or
data: "fname="+fname+"&lname="+lname
this might work for you, then if your data look like this data:new FormData(this) maybe you should use this type
data:{user_ID:user_ID}
to work the request and execute your sql.
but the best solution i got is change your
method:"POST"
to
type:"POST"
to solve this problem.
if your data.success_variable is undefined add
header('Content-type: application/json.');
to your requested php file.
Related topic:
ppumkin5 answer to
JQuery Ajax is sending GET instead of POST

Pass value from JQUERY to PHP ,and return a JSON

When call php from jquery via ajax ,have any response .I changed the dataTypeand put jsoninstead html.I´m thinking the issue is that,for the ajax call never trigger the php code,it seems $_POST['retriveForm'] never carries a value.
PHP:
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
and jQuery :
$(document.body).on('click', '.edit', function() {
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {
retriveForm: id
},
dataType: "json",
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
Code is all in the same page if that may be important.
Since the AJAX code is in the same script, make sure you don't output any of the normal HTML in this case. Your PHP code should be at the very beginning of the script, before any HTML is output. And you should exit the script after echoing the JSON. Otherwise your JSON will be mixed together with HTML, and jQuery won't be able to parse the response.
Also, you're not correctly adding to $data_json in your loop. You're overwriting the variable each time instead of pushing onto it.
<?php
// code here to set up database connection
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json[] = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
exit();
}
?>
<html>
<head>
...
Then in the success function, you'll need to index the elements of response, since it's an array, not a single object.

how to pass AJAX response value to PHP variables?

I want to use the result value and pass it to php variable,
here is my code...
billingCoffee.php
$("#linkAddSize").click(function(e){
e.preventDefault();
var txtCoffeeName = document.getElementById("txtCoffeeName").value;
var cmbSizes = document.getElementById("cmbSizes").value;
var txtPrice = document.getElementById("txtPrice").value;
$.ajax({
url: "addSizeandPrice.php",
type: "POST",
data: {coffeename: txtCoffeeName, sizes: cmbSizes, price: txtPrice},
datatype: "json",
success: function (result){
//set it php variable
}
});
});
addSizeandPrice.php
if($tableresult){
$query = "INSERT INTO tbl$CoffeeName (CoffeeSize, Price) VALUES ('$Size', '$Price');";
$insertresult = mysqli_query($con, $query);
if($insertresult){
SESSION_START();
$_SESSION['nameCoffee'] = $CoffeeName;
echo $_SESSION['nameCoffee'];
}
else{
echo "Something went wrong!";
}
}
I want to use the variable without refreshing the page... and I got this idea to use AJAX but don't know how to set it in php variable.
You are using POST as the method to send variables to your PHP script. So in PHP, they will be in the superglobal named $_POST
For example,
$coffeename = $_POST['coffeename'];
Further reading: http://php.net/manual/en/reserved.variables.post.php
Please also do some research about preventing SQL injection.

Retrieve data from dynamic php page to javascript using jquery

This is arrivalPlay.php. This page is loaded if user click data from arrivalRead.php and make the url become arrivalPlay.php?id=1 (2,3,4,5 and so on).
<?php
$con = mysqli_connect("localhost","admin","admin","flight_status");
$id = $_GET['id'];
$getrow = mysqli_query($con, "SELECT * FROM arrival WHERE id='$id'");
$row = mysqli_fetch_array($getrow);
mysqli_close($con);
$order = array(1,2,3,4);
foreach ($order as $o) {
$res[$o][f] = $row[$o];
}
json_encode($res);
?>
This is getData.js file. The file file receive res and will be passed to 'mp'.
<script>
function aha() {
$.ajax({
url:'arrivalPlay.php',
data:{id:3},
dataType:'json',
type:'GET',
success:function(data){
document.write(data[1].f);
document.write(data[2].f);
document.write(data[3].f);
document.write(data[4].f);
}
});
}
</script>
Page arrivalPlay.php only has data if the url become arrivalPlay.php?id=X. Is there any way to retrieve data from the 'dynamic' php to the javascript page? Feel free to change my approach if you think it is odd. Thank you...
Try this:
First in your server page apply echo before json_encode($res);
It should be echo json_encode($res);
And then if it not works then try this code
<script>
$(document).ready(function(){
$(document).on('click','#a',function(e){
e.preventDefault();
$.ajax({
url:'arrivalPlay.php',
data:{id:1},
dataType:'json',
success:function(data){
$('#res').html(data);
}
});
});
});
</script>
If you want json from server then only json data should be passed from server
like in your code
<?php
$con = mysqli_connect("localhost","admin","admin","flight_status");
$id = $_GET['id'];
$getrow = mysqli_query($con, "SELECT * FROM arrival WHERE id='$id'");
$row = mysqli_fetch_array($getrow);
mysqli_close($con);
$res=array();
$order = array('airline','flight','origin','status');
foreach ($order as $o) {
$res[$o] = $row[$o];
}
echo json_encode($res);// echo the json string
// remember that no other output should be generated other than this json
return; //so you can use this line
?>
is enough
but you don't want json then you use this code
echo implode(',',$res); instead of echo json_encode($res);
also in javascript remove this option dataType:'json', in this case.
Read jquery.ajax
Since you are receiving JSON data, I doubt that you would like to place them into an HTML element. I would either change my PHP file to produce HTML elements, or implement som javascript logic to create elements based on the JSON data the server provides.

jQuery ajax call won't update mysql after pressing back button

I have a form that uses ajax to submit data to a mysql database, then sends the form on to PayPal.
However, after submitting, if I click the back button on my browser, change some fields, and then submit the form again, the mysql data isn't updated, nor is a new entry created.
Here's my Jquery:
$j(".submit").click(function() {
var hasError = false;
var order_id = $j('input[name="custom"]').val();
var order_amount = $j('input[name="amount"]').val();
var service_type = $j('input[name="item_name"]').val();
var order_to = $j('input[name="to"]').val();
var order_from = $j('input[name="from"]').val();
var order_message = $j('textarea#message').val();
if(hasError == false) {
var dataString = 'order_id='+ order_id + '&order_amount=' + order_amount + '&service_type=' + service_type + '&order_to=' + order_to + '&order_from=' + order_from + '&order_message=' + order_message;
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php", data: dataString, success: function() { } });
} else {
return false;
}
});
Here's what my PHP script looks like:
<?php
// Make a MySQL Connection
include('dbconnect.php');
// Get data
$order_id = $_GET['order_id'];
$amount = $_GET['order_amount'];
$type = $_GET['service_type'];
$to = $_GET['order_to'];
$from = $_GET['order_from'];
$message = $_GET['order_message'];
// Insert a row of information into the table
mysql_query("REPLACE INTO gift_certificates (order_id, order_type, amount, order_to, order_from, order_message) VALUES('$order_id', '$type', '$amount', '$to', '$from', '$message')");
mysql_close();
?>
Any ideas?
You really should be using POST instead of GET, but regardless, I would check the following:
That jQuery is executing the ajax call after you click back and change the information, you should probably put either a console.log or an alert calls to see if javascript is failing
Add some echos in the PHP and some exits and go line by line and see how far it gets. Since you have it as a get, you can just load up another tab in your browser and change the information you need to.
if $j in your jQuery is the form you should be able to just do $j.serialize(), it's a handy function to get all the form data in one string
Mate,
Have you enclosed your jquery in
$j(function(){
});
To make sure it is only executed when the dom is ready?
Also, I'm assuming that you've manually gone and renamed jquery from "$" to "$j" to prevent namespace conflicts. If that isn't the case it should be $(function and not $j(function
Anyway apart from that, here are some tips for your code:
Step 1: rename all the "name" fields to be the name you want them to be in your "dataString" object. For example change input[name=from] to have the name "order_from"
Step 2:
Use this code.
$j(function(){
$j(".submit").click(function() {
var hasError = false;
if(hasError == false) {
var dataString = $j('form').serialize();
$j.ajax({ type: "GET", cache: false, url: "/gc_process.php?uu="+Math.random(), data: dataString, success: function() { } });
} else {
return false;
}
});
});
You'll notice i slapped a random variable "uu=random" on the url, this is generally a built in function to jquery, but to make sure it isn't caching the response you can force it using this method.
good luck. If that doesn't work, try the script without renaming jquery on a fresh page. See if that works, you might have some collisions between that and other scripts on the page
Turns out the problem is due to the fact that I am using iframes. I was able to fix the problem by making the page without iframes. Thanks for your help all!

Categories