How to access a javascript variable inside a php query? - javascript

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");

Related

How to GET javascript data in PHP file without page reload

I am building my best attempt at a twitter clone and have run into a bit of a problem. I want to be able to click on a post and, without a page refresh, display that post in the overlay of the page (as you would on a twitter feed to look at replies, etc.).
In script.js, I check for a click and try to change the url.
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
window.history.pushState(obj, "Status", "profile.php?id="+uid+"&status="+pid);
});
The javascript works as intended...but as I will soon find out, the victory is short-lived.
In profile.php, I attempt to GET the status id from the URL parameter.
<?php
$status_id = $_GET['status'];
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'");
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
?>
This doesn't work because, as I've learned, using 'window.history.pushState' only changes the url- but doesn't load the page. Thus the $_GET statement fails. I need a way to get the id of the post I click on into profile.php without a page refresh. Even if it means taking a different approach (instead of using a URL parameter).
PS: I tried to do an XMLHttpRequest as well- to no avail. :(
Thanks in advance!
$('body').on("click", ".chirp", function(){
var uid = $_GET['id'];
var pid = $(this).attr("id");
var pidSplit = pid.split("chirp");
var messageID = pidSplit[1];
var obj = {foo: "status"};
$('.chirpOverlay').addClass("active");
$.ajax({
url: "profile.php?id="+uid+"&status="+pid,
type: "GET",
data: obj,
dataType: "html",
success: function(data){
console.log(data);
}
});
});
You need to just get something up and going that works and then you can add more to it as you figure things out. This should give you a good starting place.
Here are your two files. Make sure they are both in the same directory.
You will need to make sure you have a jquery version loaded. Put this on whatever page you are calling the script.js from.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
script.js
$(document).ready(function(){
$('body').click(function(){
var id; //define your id.
var pid; //define your pid.
var datastring = 'id=' + uid + '&status=' + pid;
console.log(datastring);
$.ajax({
url: 'profile.php',
type: 'POST',
cache: false,
data: datastring,
dataType: 'json',
success: function(data){
console.log('Made it to the success function: ' + data);
if (data) {
//It works, do something.
console.log(data);
} else{
//It does not work, do something.
console.log('Your ajax failed to get the info from your php page. Keep troubleshooting');
}
}
});
});
});
profile.php
<?php
/*
$status_id = $_POST['status']; //This needs to be sanitized and validated.
$sql = $db->query("SELECT * FROM chirps WHERE id='$status_id'"); //This is unsafe sql practice.
if (mysqli_num_rows($sql) > 0) {
$c = $sql->fetch_object();
}
echo json_encode($c); //This is what gets sent back to script.js
*/
echo 'You made it to your php page.';
?>
A few things:
You can not call any php variable from within your js. var uid = $_GET['id']; does not work.
Any value that you pass to the php page needs to be validated to make sure it is a legitimate value.
Your SQL query is prone to sql injections. Please read up on how to parameterize your queries. Good Mysqli Practices
I have finally found a AJAX-based solution to my problem.
I created a new php file called "chirp_open_ref.php" and added this ajax to script.js:
var datastring = 'status=' + messageID;
$.ajax({
url: "chirp_open_ref.php",
type: "POST",
data: datastring,
cache: false,
dataType: "text",
success: function(data){
$('.chirp-container').html(data);
}
});
Inside of 'chirp_open_ref.php':
<?php
require 'core.inc.php';
if (isset($_POST['status']) && isset($_SESSION['user_id'])){
$chirp_id = $_POST['status'];
$c = "";
$sql = $db->query("SELECT * FROM chirps WHERE id='$chirp_id'");
if (mysqli_num_rows($sql) > 0){
$c = $sql->fetch_object();
}
include'chirp.inc.php';
}
?>
'chirp.inc.php' is simply a template for the layout/structure of each post.
This works like a charm, but I am always open to any criticism of how I am performing this. Thanks for all the help guys!

redirect page using ajax & jquery (php)

i want to redirect from page a to page profile and in between there is a post session on them. in this case let's say the data is variable $name in string. so far my code is like this on page a
jQuery("#result").on("click",function(e){
var $clicked = $(e.target);
var $name = $clicked.find('.name').html();
var decoded = $("<div/>").html($name).text();
$('#searchid').val(decoded);
//the ajax script
$.ajax({
type: 'POST',
url: 'b.php',
data: 'result='+$name,
success: function() {
window.location.href = "profile.php"; // replace
}
});
});
and on page b the code is:
<?php echo $_POST['result']?>
the outcome should be the value from result in which determined on page a.
but so there is an error message saying unidentified index. so where am i doing wrong?
Could it be, that your data parameter is wrong?
I have my ajax calls as folowing:
jQuery.ajax({
type: "POST",
url: "b.php",
data: {
result: $name
},
success: function() {
window.location.href = "profile.php"; // replace
}
});
It is a new request after the redirect. In order to access the result you need to sotre it in som kind of session or pass it again.
You can pass it like this, then it will be in $_GET
success: function(data) {
window.location.href = "profile.php?result="+data; // replace
}

Javascript Not Calling PHP function in wordpress

I am trying to get the following code to work:
//In Javascript
function updateContentEditable(){
var span = $(this);
var data = new Object();
data.pid = '1';
data.content = 'this is a test';
data.action = 'update_content'; //This should run update_content php function
$.post(ajaxPath, data, onContentSaved); //ajaxPath returns: /wp-admin/admin-ajax.php
}
//In PHP
function update_content(){
echo "<script>alert (\"php was reached\")</script>";
}
NOTE:
//onContentSaved is this:
function onContentSaved(data){
console.log(data);
}
My problem is the the php function is not being run.
What I'm I doing wrong?
Assuming you are using jquery, try this:
function SendRequestCallBack(webMethod, parameters, callBack) {
$.ajax({
type: "POST",
url: webMethod,
data: parameters,
contentType: "application/json; charset=utf-8",
success: function(results) {
$(".ajaxImage").hide();
eval(callBack(results.d));
}
});
}
function formatData(obj){
alert(obj);
}
$(document).ready(function()
{
SendRequestCallBack("http://url-to-php","{'any':'parameters'}",formatData);
});
Then all the PHP needs to do is echo valid JSON. Or if you like you can change the contentType: parameter to text/xml or text/plain etc depending on what you want it to return. Keep in mind that your PHP needs to output the matching content type as well. for example
<?php
header("Content-type: text/json");
echo {"d":[{"firstname":"John","lastname":"Doe"},{"firstname":"Jane","lastname":"Doe"}]}
?>
If you want to pass data in to the PHP function, set it in the parameters, and make sure that your PHP will accommodate it using the $_POST array.

Transfer data to javascript array with mysql data request via php and $.ajax

I have the following code for requesting data from a mysql database:
jquery/javascript:
ajaxGet = function (url) {
var result = $.ajax({
url:url,
type:"POST",
data:{action:'call_this'},
dataType: 'json',
success:function(data) {
}
});
return result;
}
php:
<?php
if($_POST['action'] == 'call_this') {
// call waypoint search
include ('link.php');
$sql="SELECT * FROM Waypoints"; //data in table Waypoints
$result = mysqli_query($link,$sql);
$wptdata=array();
while($line = mysqli_fetch_assoc($result)){
$wptdata[] = $line;
};
mysqli_close($link);
echo json_encode($wptdata);
};
?>
To get the data as a javascript array, I would like to be able to say something like this:
wpdata=ajaxGet('datacall.php');
Suggestions on how to get this to work? If I put alert(data[0].name) within the success function, it comes up with the right result, so the call to the database table is definitely working. But I can't seem to figure out how to get the array out of the $.ajax call.
Thanks for any help- have been searching through other questions, and just came seem to find a solution. I would like to keep the ajaxGet function if at all possible- once I get it working, I will be able to update it so that it is flexible as to what kind of data are called from the table.
The answer is no. You cannot do this is any way that is sane. Use callbacks/promises - that's the way to go!
function ajaxGet(url) {
return $.ajax({
url: url,
type: "POST",
data: {
action: 'call_this'
},
dataType: 'json'
});
}
ajaxGet().done(function(wpdata) {
// use wpdata here
});

get json string at server side in php-wordpress

hy,i am working on a wordpress plugin in which i require to delete multiple items using checkbox.when i check all rows and delete them i get their row id in the form of json string.
js code:
$('.check_it:checked').each(function (i){
c[i]=$(this).val();
});
var chk = JSON.stringify({ list: c });
debugger
$.ajax({
type:"POST",
data: chk,
url:'/word/wp-content/plugins/craiglist/action.php?action=delete_leads',
dataType: "json",
success:function(response){
alert('fdsfsfdsfd');
},
failure:function (response) {
alert("Please Try Again");
},
error:function (xhr, status, error) {
alert(xhr.response);
}
});
In var chk i got string like
"{"list":["151","152","153","154","155","156","157","158","159","160","161","162","163","164","165","166","167","168","169","170","171","172","173","174","175"]}"
how can i get it at server side in php and send it to database so i can delete the so called rows.
Because you are sending JSON as the post data, you will have to access the raw post data on the PHP side. This can be done like so:
$obj = json_decode($HTTP_RAW_POST_DATA);
foreach($obj->list as $item)
{
// delete from mytable
$wpdb->query(
$wpdb->prepare("DELETE FROM mytable WHERE id = %d", $item)
);
}
If you want the data in a $_POST variable, then you will have to change your ajax request data to something like:
$.ajax({
....
data: { list : JSON.stringify(c) },
....
Now, on the PHP side it is present in $_POST['list']. So you can do:
$obj = json_decode($_POST['list']);
foreach($obj->list as $item)
{
// delete from mytable
$wpdb->query(
$wpdb->prepare("DELETE FROM mytable WHERE id = %d", $item)
);
}
In your server side php since you're not calling the get_header() function, you have to add this piece of code manually require_once('../../../wp-load.php'); and you can now call global $wpdb; safely and all wp functions. Please also take note that you're php file must be inside your theme together with your functions.php and other core files. Do not put it into another directory inside your theme

Categories