Ajax after success, how to pass data to a variable to php - javascript

I have script like this
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
I don't know how I can pass data response to php code ?
For Example: if I alert response, it's show 123 .so I want pass value 123 to a variable in php
$id = 123

response is the result passed BY php, not TO php. What's passed to php is the id and the task.
In your tab.php, you can access these two values :
<?php
$id = $_POST['id'];
$task = $_POST['task'];
//do anything you want with it...
?>

This is not the right workflow. PHP executes on runtime, so every time the page has finished loading you can't really put variables back into PHP (unless you reload the page). This is where AJAX comes in, so you can call PHP scripts from JavaScript / jQuery and don't have to reload the page every time.
The right thing to do is to either store the variable you have generated in the tab.php script in a database, $_SESSION, $_COOKIE or something similar like so:
//put this at the top of all your php scripts you want to use the variable in
session_start();
//now store the variable you wanted to pass (in tab.php)
$_SESSION['returnValue'] = $myValue;
Now if you want to use the variable in other pages just echo it like so (remember to add session_start() at the top of the PHP script.
echo $_SESSION['returnValue'];

First of all, start by reading this
To answer your question,
function getval(sel) {
var id= sel.value;
$.ajax({
type:"POST",
url:"./tab.php",
data:{id:id,task:'search'},
success: function(response){
//(I don't know what i should write for pass to php code)
}
});
}
The result from id and task are sent via $_POST (type:"POST") to the page tab.php (url:"./tab.php"). If you want to do that on a different page, just change the url in your ajax call: url:"./any_other_page.php" and the posted values will be sent there
Finally, read THIS post as well. It is greatly written and very well explained.
Hope it helps!
Keep on coding!
Ares.

Related

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

PHP file called by javascript and another php file

I have a php file (I will call ORIGINAL) which do some calculations (through db mysql). I want to read this php from javascript. For that operation I have used ajax function and my php uses echo $result to print the data I need.
Everything is perfect here.
What happends now, I am creating another php file which need to call the ORIGINAL php file. If I want to call it, I must change the echo to return which is normal. This causes that my javascript call doesnt work.
Do you have a solution which work for both situations?
Thanks in advance.
Do you mean something like this?
original_php_file.php:
<?php
require_once "other_php_file.php"; // include all of the other files contents
// all code contained within original_php_file
?>
You were being pretty broad with your request (not including file names or code), so this is all I can assume you need.
Tell me if it helps :-)
Just send one more parameter into your ajax request to tell that ORIGINAL php file what type of output it should return.
Into your ORIGINAL file check for that output so you can understand from where that request come and what output you should return.
$.ajax({
url: 'ORIGINAL.php',
data: 'data=test&output=1',
success: function(r){
// here you have your output
}
});

How to pass a value from JavaScript in php?

Translate translator from Google. So that did not swear if something is not clear. Itself from Russia.
The question arose. How to pass the value of the alert in the javascript in the variable $ value in php, and write it in the case file. And another question: how to hide the alert? or use instead to visually it was not visible, but the value was passed?
//a lot of code
{
console.log(data);
alert(data['value']);
}
});
So. Also there is a PHP script that writes logs (current page and the previous one) to a file. According to this principle here:
//a lot of code
$home = $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$referer = $_SERVER['HTTP_REFERER'];
$value = how the value of the java script to convey here?;
$lines = file($file);
while(count($lines) > $sum) array_shift($lines);
$lines[] = $home."|".$referer."|".$value."|\r\n";
file_put_contents($file, $lines);
It is necessary that the value of js is transferred to the php-script and write to the file. How to do it? Prompt please. I am a novice in all of this.
PHP scripts run before your javascript, which means that you can pass your php variables into javascript, but not the other way around. However, you can make an AJAX POST request from JavaScript to your PHP script, and grab the POST data in PHP through the global $_POST variable.
Assuming you use jQuery, your JavaScript would look something like:
// assign data object:
var data = { value: "test" };
// send it to your PHP script via AJAX POST request:
$.ajax({
type: "POST",
url: "http://your-site-url/script.php",
data: data
});
and your PHP script would look like:
// if the value was received, assign it:
if(isset($_POST['value']))
$value = $_POST['value'];
else
// do something else;

Using Ajax to require different php page

I want to use jquery ajax to change the content of my div elemnt by requiring different php files.
here is the ajax code :
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num
},
success:function(result){
$("#right_bot").html(result);
}
});
the project_functions.php would be something like :
$result = '<?php require "Panels/Project/Main/main.php" ?>';
echo $result;
I can see the value being outputted , but the html comment out the php part
<!--?php require "Panels/Project/Main/main.php" ?-->
It just comments out the php. Is there a way i load different php files into my div ?
In the main.php file , It has php code , html code , and some style tags. Can I use ajax to load all this into the div element ? or I have to echo all my html code ?
You can't do this like that. What you want is that all PHP is excecuted on the server and only the result has to be returned.
You can't send php-code back to javascript and try to run it there, PHP is a serverside language, it will only work on the server. Javascript is clientside, it will only run in the browser.
If you where to send <?php echo 123; ?> back to Javascript, you'll get exactly that as result, not 123.
The solution in your case is to make project_functions.php really require it. This will include the main.php, all it's functions and output.
require "Panels/Project/Main/main.php";
Some suggested reading:
http://www.codeconquest.com/website/client-side-vs-server-side/
A trick which might help you: Paste the link to your urlbar, and add the variables to it. The result you get in your screen is what Javascript will output. Note: This only works for method=get, not post.
In this case browse to /project/Functions/project_functions.php and do the simple require per my code above. That output will be send to Javascript.
Send a parameter in the ajax request 8for example type):
$.ajax({
url:"/project/Functions/project_functions.php",
type:"POST",
data:{
functions:num, type: "main"
},
success:function(result){
$("#right_bot").html(result);
}
});
And then in php-file get the type variable:
if($type == "main") {
require "Panels/Project/Main/main.php"
}
else {
require "Panels/Project/Main/sthelse.php"
}
You should also have some sort of same function name or something to output the results of the file;
<?php
function printResult() { }
echo printResult();
Try:
$result = file_get_contents('Panels/Project/Main/main.php');

JS/jQuery passing array/variable/data to PHP in same page?

Im hoping you can point me in the right direction.
I have a php page, that includes some HTML markup and some JS/jQuery routines to build an array of 'user choices' based on the 'user input' (checkboxes..etc).
my question is, how can I pass off this (multidimensional) array to PHP, that is in the same page? (ultimately I want to save this data/array to my PHP session)
While looking around, I read about using another (external) .php script to do,, which is NOT what Im after, I'm hoping to do this to the SAME PAGE I'm in... WITHOUT A REFRESH.
will $.post() do this for me? without a page refresh (if we suppress the event or whatever)...
and -not- using an external .php script?
I understand PHP runs/executes FIRST... then everything else..
I'm not really trying to get PHP to do anything with the data being sent from JS/AJAX.. outside of save it to the SESSION array..
Ajax seems like it will be needed?
To summarize:
1.) PHP and JS are in/on same page (file)
2.) No page refresh
3.) No external PHP script to do 'anything'.
4.) Trying to get (multidimensional) array to PHP session in same page.
5.) I am trying to 'update' the PHP SESSION array each time a user 'clicks' on a checkbox.
I have read a little on using AJAX to post to the same page with the URL var left empty/blank?
edit:
to show the data, I want to pass...heres a snippet of the code.
its an array of objects.. where 1 of the poperties of each object is another array
example:
var somePicks = [];
somePicks.push({casename:caseName, fullname:fullName, trialdate:trialDate, citystate:cityState, plaintiff:plaintiff, itemsordered:itemsOrdered=[{name:itemOrdered, price:itemPrice}]});
when from all the checkboxes.. I update the 'sub-array' (push or splice..etc)
somePicks[i].itemsordered.push({name:itemOrdered, price:itemPrice});
'this' is the array/data I want to get into my PHP session from JS using whatever I can AJAX most likely.
You can sort of do that, but in essence it won't be any different than using an external PHP file. The PHP code gets executed on the server before ever being sent to the browser. You won't be able to update the PHP SESSION array without reconnecting with the server.
If you really want to use post to call the current page (I don't think you can just leave the url blank, but you can provide the current file name), you can just have the PHP handler code at the top of the page. However, this would be the exact same as just putting that handler code in an external file and calling it.
Either way, the page will not refresh and will look exactly the same to the user.
You can use $.ajax function with $(#formid).serializearray (). And use url as ur form action in $.ajax function.
I hope it will work for you
<form id="formId" action="post.php" methor="post">
<input type="checkbox" name="test1" value="testvalue1">TestValue1
<input type="checkbox" name="test2" value="testvalue2">TestValue2
<input type="button" id="buttonSubmit" value="click here" />
</form>
<script>
$("document").ready(function ()
{
$("#buttonSubmit").click(function () }
{
var serializedata=$("#formId").serializeArray();
$.ajax(
{
type:"post",
url:$("#formId").attr("action"),
data:{"data":serializedata},
success:function()
{
alert("yes");
}
});
});
});
</script>
<?php
if(isset($_POST))
{
session_start();
$_SESSION["data"]=$_POST["data"];
}
?>
I suggest to use the .post method of Jquery, to call a PHP file, sending the array and processing in the PHP called.
Can find the jquery documentation about .post() here: http://api.jquery.com/jquery.post/
Edited:
I used this case some time ago:
document.getElementById("promotion_heart_big").onclick = function(e){
$.post("' . URL_SITE . 'admin/querys/front.make_love.php",
{
id_element: ' . $business["promotion"]["id"] . ',
type: \'promotion\',
value: $("#field_heart").val()
},
function(data) {
if (data.result) {
//some long code....
}
}
},
"json"
);
from some preliminary testing..
this does NOT seem to be working, (will do more test tomorrow)
$.ajax({
type : 'POST',
//url : 'sessionSetter.php',
data: {
userPicks : userPicks,
},
success : function(data){
//console.log(data);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
});
It was mentioned that posting to external .php script -or- posting the same page would produce the same results..
no page refresh
$_SESSION would update for future pages
Does anyone have an y example for that?

Categories

Resources