send php variables via ajax call - javascript

According to jquery API this is the wat of sending value asigned to a name with ajax
.data( key, value )
Problem is my values are already in php variables. how can i send them using ajax?
this problem is relate to this question i asked yesterday. Still couldn't find a way to send php variables to another php page when a button is clocked. sad that jQuery API Documentation doesn't have examples.

You have two php....let say page.php and ajax.php. If you call ajax.php from ajax in page.php you must write variables from php to javascript with something like
var data1 = <?= $data1 ?>;
var data2 = <?= $data2 ?>;
and then add these variables to ajax call.
Best regards,
nele

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
var ajax_value1 = $("#ajax_value1").val();
var ajax_value2 = $("#ajax_value2").val();
$.ajax({
type: "POST",
url: 'sample.php?ajax_value1='+value1+'&value2='+ajax_value2,
//Specify the datatype of response if necessary
data: $("#your_form_id").serialize(),
success: function(data){
}
});
</script>
<!-- Set your ajax value in html input fields -->
<input type="text" name="ajax_value1" id="ajax_value1" value="<?php echo $ajax_value1;?>" >
<input type="text" name="ajax_value2" id="ajax_value2" value="<?php echo $ajax_value2;?>" >

Related

Is there a way to get create a php varialble from ajax data returned from another php script

I have a php script that creates a webpage with my select box options
Eg index.php has a html select box:
<select id="sel_option">
<option value="0">- Select Option -</option> ....
this is posted on sel_option change using ajax to a php processing script as below:
<script type="text/javascript">
$(document).ready(function(){
$("#sel_option").change(function(){
var optionid = $(this).val();
$.ajax({
url: 'procscript.php',
type: 'post',
data: {option:optionid},
dataType: 'json',
success:function(response){ ...
I would like to pull some of the returned array into Php variables again in order to change some of the tabulator group or format options
eg $("#table1").tabulator({
height:500 ,
VirtualDomHoz:true,
<? echo "groupBy:[\"group_option_from_response array\"]," ?>
So Php script1 sends option data by ajax -> php script2 which gathers data from a mysql db and returns to script1
I have tried creating session variables in php script 2 and it works on first selection , but after that it seems to cache the initial sessions in the browser , the response sessions from the second php script do not seem to copy over to the first script in subsequent calls. I think it might because the first page never reloads , all selections are done within the loaded first page using js??
If what I am trying to do is if not possible by php can I rewrite the php section in tabulator below using some js code?
$("#table1").tabulator({
height:500 ,
VirtualDomHoz:true,
<? echo "groupBy:[\"group_option_from_response array\"]," ?>
placeholder:"No Data Set",
columns:[
{title:"ID", field:"ID",width:30},
{title:"F_name", field:"f_name", sorter:"string"},
<? echo "{title:\"different var\", field:\"field2\", sorter:"string"},"; ?>
Thanks for looking !
Steve
Receive your data through ajax, then create the tabulator object. If there is data coming through ajax for that object, you can add it in, then instantiate it.
success:function(response){ ...
response = JSON.parse(response);
createTabulator(response,"table1")
});
function createTabulator(data, idToUse) {
var tabobject = {
height:500 ,
VirtualDomHoz:true,
placeholder:"No Data Set"
}
if (data.groupBy) {
tabobject.groupBy = [data.groupBy]
}
var cols = [
{title:"ID", field:"ID",width:30},
{title:"F_name", field:"f_name", sorter:"string"}
]
// if there is columns data coming in, bring it as an array...
data.columns.forEach(item => {
cols.push({title: item.title, field: item.field, sorter:"string"})
})
tabobject.columns = cols;
$("#"+idToUse).tabulator(tabobject);
}
There are so many ways to achieve what you want. I think the best way is just to push the variable to the ajax request.
$.ajax({
...
data: {
option:optionid,
groupoption: "groupoptionvalue"
}
...
});
The first time you just have to send it empty. PHP will always be able to handle the value since you will always capture it at the very beginning.
If your variable is an object or an array, just use JSON.parse/JSON.stringify in javascript and json_encode/json_decode in PHP for them to communicate.

Trying to use AJAX to grab parameter of function and pass to PHP code

I have an HTML input with a function and parmeter set to it like so
<input onclick='myFunc($count)' type='button' value='ClickMe'>;
I also have script references to JQuery and my script file
<script src="jquery.js"></script>
<script src="myscript.js"></script>
Inside my myscript.js file I have the contents as such
function myFunc(x) {
alert(x);
$(document).ready(function() {
$.ajax({
url: "myphp.php",
method: "post",
data: { param1: "x" },
dataType: "text",
success: function(strMessage) {
}
})
})
}
Here is my myphp.php file
<?php
$param1 = $_GET['param1'];
echo $param1;
?>
As you can see in the javascript file, I have alert(x); to test that the function is grabbing the $count variable and so far that is working (the correct value appears in the alert box). However, I want to pass that x parameter to the PHP script but my PHP script won't echo anything, I assume the line where I have param1 is wrong. Any tips?
In your AJAX call you are using a POST method, so in order to catch the variable in PHP you need to access it from $_POST:
<?php
$param1 = $_POST['param1'];
echo $param1;
?>
You're making the XHR with POST method
method: "post",
and youre looking for it in the GET array
$_GET['param1'];
Change either to post or get (keeping in mind your scenario) and you should be good imo.
read more here to know about the different methods of sending http requests: https://www.guru99.com/php-forms-handling.html
You are using post method in AJAX but trying to grab the value in $_GET which is wrong.
In your PHP code, just replace $_GET['param1'] with $_POST['param1'] and it works.
or If you like to use $_GET in your PHP code then change the method in AJAX or use $.get. Examples can be found on W3School.
https://www.w3schools.com/jquery/jquery_ajax_get_post.asp

How do I transfer the PHP variables to another javascript file?

So my goal is to use PHP to get data from a PostGreSQL database. I want to use this data in a separate javascript file so I can display it on the screen a certain way that I have my website configured. All the tutorials that I have seen online just puts a script tag inside the PHP file but I cannot do that because my website display javascript code is in the separate file. I just need the numbers to be in the javascript file that I got from the PHP file that got its data from the PostGreSQL database. How can I do this?
I just need help with the means to get to the ends because I have researched on my own but it is always not exactly what I want.
PHP:
<?php
$myPDO = new PDO('pgsql:host=myHost; dbname=myDBName', 'myUsername', 'myPassword');
?>
$result = $myPDO->query("SELECT * FROM table WHERE id = 'someID'");
Now I want to use this row's values in another javascript file. How can I do this?
You could use Ajax for this.
You could so something like this in your JS file:
$.ajax({
type: "GET",
url: 'FILENAME.php',
success: function(data){
alert(data);
}
});
and then in your FILENAME.PHP just return the values.
Your JS should then pull through whatever has been returned, in this case, your database query.
Your JS file needs to request the data from your PHP controller, via an AJAX request. You can then manipulate the returned data object whichever way you like.
We have mainly two methods to pass php value to javascript variable
Simple variable method at the time of first page load
<script>
var js_variable = <?php echo $data_php_variable; ?> ;
//this is working only at the first time of the page load
//you can also parse the data to any format
</script>
Use AJAX call to trigger a PHP request and manipulate return PHP value in JS
$.ajax({
type: "GET", //get or post method
url: 'FILENAME.php', //php request url
data :{}, //optional ,you can send data with request
success: function(res){
// this 'res' variable is the php return data in the form of js data
console.log(res);
}
});
ajax method is more dynamic ,it can use any time request handling
use the javascript ajax to call a php api
pass your data at php in your view file , use something like:
var phpData = JSON.parse("<?php echo json_encode($data)); ?>");

AJAX - my simple ajax request does not work

I'm currently learning how to use Ajax but i already have a problem :
1 HTML :
<body>
<form>
Nom d'utilisateur : <input type="text" id="username" name="username"/>
<input type="submit" id="submit" />
</form>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="script.js"></script>
JS :
$(document).ready(function(){
$("form").submit(function(e){
e.preventDefault();
var don=$('#username').val();
$.ajax({
url:'test.php',
type:'post',
data:don,
success: function(html){
alert(html);
}
});
});
});
PHP :
<?php
if(!empty($_POST['username'])){
$response="yep";
}
else{
$response="nope";
}
echo $response;
?>
As you can see, it is really simple. But it drives me crazy, i didn't understand why i always have the response "nope".
Can you help me ?
Thank you
PHP requires you to submit key=value constructs to properly build $_POST/$_GET with. No key, no value. You haven't provided a key, just a value.
Try
data: {"username":don}
instead. Or have your PHP script read the raw POST data via php://input.
You are just sending a string. You need to send a JSON object:
var don = {"username" : $('#username').val()};
jQuery will turn this into a string and send it (I'm assuming, otherwise you need to JSON.stringify it), and then you'll need to call json_decode on it server-side before you query it.
If you want to continue using your current serverside code, you need to use a GET request and submit to url: "test.php?username="+encodeURIComponent($('#username').val()) and then check the _GET variable on PHP side.

Can't get PHP variable to JavaScript file using AJAX

While looking at tons of examples of how to get a PHP variable sent to a JavaScript file, I still haven't had success getting it.
My PHP file is:
$title = $json["title"];
echo json_encode($title);
And my JavaScript file app.js is:
$.ajax({
url : 'index.php',
type : 'GET',
data : film,
dataType : 'json',
success : function (data) {
alert(data.title);
console.log(data.title);
},
})
I would like to know the right code to get the PHP $title variable to the ajax call in app.js.
Thanks
For this example there are two files. One has the JQuery ajax method. The other file is a PHP script that returns the requested information.
show_title.html
<!-- JQuery library already loaded -->
<script>
$.ajax({
url : 'get_title.php', // requesting a PHP script
dataType : 'json',
success : function (data) { // data contains the PHP script output
alert(data.title);
console.log(data.title);
},
})
</script>
get_title.php
<?php
$json["title"] = 'a title';
echo json_encode($json);
?>
If you'd want a .title property on the response, then you should create an array then encode that instead. You got the other way around. Something like this:
PHP
<?php
$title = 'Yahoo!';
$json['title'] = $title;
echo json_encode($json);

Categories

Resources