I am running a mysql select query in php like this
<?php
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
var1 and var2 are javascript variables on the same page. I know client side variable cannot be passed to server side. But is there any workaround as the variables are in the same page.
In order for you to make this happen - I believe - you have to use AJAX.
The code will look like this:
$.ajax({
url: 'your_script.php',
type: 'POST',
data: {var1: javascript_var_1, var2: javascript_var_2},
success: function(data) {
console.log("success");
}
});
Your PHP will look similar to this (without keeping in mind the JSON encode:
<?php
$var1 = $_POST['var1'];
$var2 = $_POST['var2'];
$getvalue="SELECT id,name from table1 WHERE column1='$var1' and column2='$var2'";
$result=mysql_query($getvalue) or die(mysql_error());
while($row=mysql_fetch_array($result)){
extract($row);
echo $name;
}
?>
Then you can JSON encode the results and pretty much output them on the success. Your php script - however - must live on another php file.
Also, escape your data. Use prepared statements.
In theory, you could pass the vars to php via some sort of ajax call. I think it would go something like...
JavaScript:
var data = {
'var1': $('selector').val(),
'var2': $('selector').val()
};
$.ajax({
type: 'post',
url: 'path-to-your-file.php',
data: data,
timeout: 50000
}).done(function(response) {
console.log(response);
}).fail(function(error) {
// uh-oh.
});
php:
<?php
print_r($_POST['data']);
Otherwise, you could use:
cookie
hidden input
php:
<?php
... column1='$_COOKIE["mycookie1"]' and column2='$_COOKIE["mycookie1"]'";
... column1='$_POST["hidden1"]' and column2='$_POST["hidden2"]'";
NOTE: you will want to sanitize the data. Using raw cookie and/or input values could lead to some less than desirable results.
Use Method Post in AJAX or Form!! To send js variable in Php and receive it in php using $_post[ name_of_obj ];
Related
I have a index.php with a javascript function Loaddata()
function loaddata(){
<?php
$data = //connects to database and gives new data
?>
var data = <?php echo json_encode($data); ?>;
}
setInterval(loaddata,3000);
I understand the fact that php scripts can only be run once when the page is loaded and it cannot be run again using set interval method. Can someone please guide me how to run the php script at regular intervals inside my index.php using ajax or some other method. My javascript variable "data" depends upon the php script to gets its value. Thanks a lot
Generally, using ajax to get data from a PHP page on the front page is a good way. The way you write this code is fine, too. I suggest writing like this,
var data = <?php echo json_encode($data);?>;
function loaddata(){
// use data
}
setInterval(loaddata,3000);
I think it is more clear
You could use an ajax call to retrive data from php and call that function in setInterval function something like this.
function demofunc()
{
$.ajax({
url: '<?php echo base_url();?>',
type: 'POST',
data: formdata,
dataType: 'json',
success: function(data) {
// do your thing
}
});
}
setInterval(demofunc,3000);
If anyone wondering how to do it.
Echo the PHP value that you want ajax to get for you.
Do an ajax request to the php page to get the data.
$.ajax({
method: 'get',
url: 'time.php',
data: {
'ajax': true
},
success: function(data) {
console.log(data)
}
});
// Second Method
$.get('time.php',function(data){
console.log(data);
});
PHP file
if ($_GET['ajax']) {
echo "HELOOO";
}
//if using the 2nd method just echo
echo "hi second method";
Basically I have a combination of PHP codes and javascript codes. My mySQL data are encrypted using CodeIgniter, thus to load the data (view and edit) in json, i need to decrypt it again. My question is how to make my "$x" variable dynamic?
Thanks.
function edit_person(id)
{
save_method = 'update';
$('#form')[0].reset();
$('#modal_form').modal({backdrop: 'static', keyboard: true, show: true });
<?php
$x = 13; //<== **i need to make this $x dynamic based on "edit_person(id)"** //
$url = "http://myurlhere.com/main/ajax_edit/".$x;
$datax = file_get_contents($url);
$string = json_decode($datax, TRUE);
?>
$.ajax({
url : "<?php echo site_url('main/ajax_edit')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
// ** below code "firstName" is my decryption requirement ** //
$('[name="firstName"]').val("<?php echo $this->encryption->decrypt($string['firstName']); ?>");
$('#modal_form').modal('show');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
You are probably confusing the server-side and the client-side code.
In simple terms: First, the client sends a request to the server. The target PHP code gets executed on the server-side only. It then generates an HTML file, which contains your JS code. This file is sent to the client and is executed on the client-side only. At that time, on the client-side, there is JS code only and no PHP code anymore. All the PHP code gets replaced by some value or is simply removed or ignored.
If you want to access some PHP functionality from your JS code, you have to send a request from the client to the server. As you are doing with the AJAX call.
So in order to make your $x dynamic, you have to call some PHP code and pass the ID as a parameter.
In a strongly simplifyed way you could achieve this by:
$.ajax({
url : "your url to some file.php/?id=" + id,
type: "GET",
})
some file.php
<?php
$x = $_GET["id"]; //<== $_GET["id"] will return the value of the parameter "id" in the url
?>
Starting from here, you should read more about AJAX calls, input sanitation and validation in order to secure your requests.
I've got the following ajax request that I want to run every 5 seconds. To test it, I just set up a couple alerts. I set up an alert('hello'); inside the success and it fired every 5 seconds. So that works.
What isnt working is the if(response.update==true){ section.
I am setting
<?php $data['update'] = "true"; return $data; ?> inside the ajax url file.
Am I doing something wrong? Is this an incorrect approach? Am I missing something?
I even tried setting datatype: json, inside ajax and returning return json_encode($data); inside ajax url as well with no success.
CODE
<script type="text/javascript">
$(document).ready(function(){
/* AJAX request to checker */
setInterval(
function (){
$.ajax({
type: 'POST',
url: '<?php echo http() . $websitedomain .'/Manage/order_management/search_orders_checker.php'; ?>',
datatype: html,
data: { counter:10 },
success: function(response){
if(response.update==true){
alert('yes');
}
}
})
},5000);
});
</script>
EDIT
console log is now reporting the json response. But the if (response.update == "true") { alert('yes'); } still isnt working.
The console.log response: {"update":"true"} and its updating every 5 seconds like its supposed to.
Here are all the things you need to get it working:
1) PHP:
you need to
encode your data as JSON
echo your data to your script's output, rather then returning it somewhere within PHP
return a boolean true instead of a string "true" in the "update" field
Here's the new code for that:
<?php
$data['update'] = true;
echo json_encode($data);
?>
2) JavaScript:
You need to change datatype: html to dataType: "json"
This is because
JS variables are case-sensitive, so jQuery doesn't recognise an
option called 'datatype'
the value "json" must be string (before you used html which was actually a reference to a non-existent variable
specifying "json" tells jQuery to automatically parse the response as JSON, meaning you don't have to do you own call to JSON.parse()
in the callback.
Couple things look incorrect here. First off...
<?php $data['update'] = "true"; return $data; ?>
If this is how you are returning your data, then this is not returning json. You need to encode the associative array into json and echo that to the standard out.
<?php $data['update'] = "true"; echo json_encode($data); ?>
Once you have that, then you can make your ajax request expect the response to be json.
$.ajax({
type: 'POST',
url: '<?php echo http() . $websitedomain .'/Manage/order_management/search_orders_checker.php'; ?>',
//dataType tells ajax to auto-parse the json response into an object
dataType: 'json',
data: { counter:10 },
success: function(response){
if(response.update==true){
alert('yes');
}
}
})
I'm trying to send an array from a JS file to a PHP file in the server but when I try to use the array in php, I got nothing.
This is my function in JS:
var sortOrder = [];
var request = function() {
var jsonString = JSON.stringify(sortOrder);
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function() {
alert('data sent');
}
})
};
and this is my php file MYPAGE.php:
<?php
$arrayJobs = json_decode(stripslashes($_POST['sort_order']));
echo($arrayJobs);?>
This is the first time that I use ajax and honestly I'm also confused about the url because I'm working on a template in wordpress.
Even if I don't use json it doesn't work!
These are the examples that I'm looking at:
Send array with Ajax to PHP script
Passing JavaScript array to PHP through jQuery $.ajax
First, where is that javascript code? It needs to be in a .php file for the php code (wordpress function) to execute.
Second, how do you know that there is no data received on the back-end. You are sending an AJAX request, and not receiving the result here. If you read the documentation on $.ajax you'll see that the response from the server is passed to the success callback.
$.ajax({
type: "POST",
url: '<?php echo get_template_directory_uri(); ?>/MYPAGE.php',
data: { sort_order : jsonString },
cache: false,
success: function(responseData) {
// consider using console.log for these kind of things.
alert("Data recived: " + responseData);
}
})
You'll see whatever you echo from the PHP code in this alert. Only then you can say if you received nothing.
Also, json_decode will return a JSON object (or an array if you tell it to). You can not echo it out like you have done here. You should instead use print_r for this.
$request = json_decode($_POST['sort_order']);
print_r($request);
And I believe sort_order in the javascript code is empty just for this example and you are actually sending something in your actual code, right?
the problem is in your url, javascript cannot interprate the php tags, what I suggest to you is to pass the "get_template_directory_uri()" as a variable from the main page like that :
<script>
var get_template_directory_uri = "<?php get_template_directory_uri() ?>";
</script>
and after, use this variable in the url property.
Good luck.
I hope it helps
Here's the javascript:
var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
alert(data);
},
'json'
);
And here's the ending of the do_register() method:
if( $_REQUEST['format']=='JSON' ){
$jsonHelper=Loader::helper('json');
echo $jsonHelper->encode($registerData);
die;
}
The $registerData variable holds all the data I need. I want the function to return it after the ajax call. However, when I specify dataType: 'json' nothing is returned. Any suggestions?
I think your problem is in url
$.post(
'<?php echo $this->url("/register", "do_register"); ?>?format=JSON',
function(data) {
alert(data);
},
'json'
);
Also you can use following line in php part to get json values
header('Content-Type: application/json');
I suppose problem is somewhere here:
'<?php echo $this->url('/register', 'do_register')?>', in using quotes.
Use double and single quotes:
"<?php echo $this->url('/register', 'do_register')?>",.
It's impossible to receive right suggestion with little description.
Y'd better to paste more php & javascript code, with much more context, thing to be simple.
And another suggestion, mixed coding is bad. separating the javascript and php with php template such as Smarty.
var data = $('form#registration-form').serialize();
$.post(
'<?php echo $this->url('/register', 'do_register')?>',
function(data) {
alert(data);
},
'json'
);
this source file of above code is a php file ?
Debug with firebug to capture weather the ajax request sent or not
Why use JSON helper??
json_decode(string $json);
json_encode(mixed $value); //normally array...
it is built-in in php.