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

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?

Related

Load php file within javascript (AJAX or others)

I am trying to finish one page of my website the last couple of hours while achieving the following.
While clicking on a button, the following should happen
Download link appears (done - works)
The mySQL table should be opened and a counter should be incremented
As far as I got the points. Javascript cannot handle that and thus we can use AJAX or jQuery. I was already checking out different posts and websites such as:
how to execute php code within javascript
https://www.w3schools.com/js/js_ajax_database.asp
and much more. However, I guess I do have problems with the AJAX syntax and I actually don't know if the requested php files is loaded/opened or not. Especially the second link given above is almost similar to what I am searching for. However, it does not work. To check if the php file is called, I set an alert which works if I do call the file explicitly in the browser. Maybe this does not work with AJAX as I expect it. Here the code to get more familiar with the inconstency I am doing.
The page code:
<?php
echo '<div><button onclick="incrementAndDownload('testPath', 'fileName'); ">Click me</button></div>';
?>
<script>
function incrementAndDownload (link, fileName)
{
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
// Print something if necessary
}
});
//- Open the link
// window.open(arguments[0], "_blank");
//- Increment download inside mysql
//var xhttp;
//xhttp = new XMLHttpRequest();
//xhttp.open("GET", "openfoam/increment.php?foo=nana", true);
//xhttp.send();
}
</script>
The increment.php looks as follows:
<?php
echo '<script type="text/javascript" language="Javascript">
alert("Test message if the script is called...");
</script>';
// Code for accessing the mysql database and manipulate the data
//$page_id = mysql_real_escape_string(html_entities($_POST['file']));
?>
Now when I click the button, the javascript is executed (e.g., if I uncomment the window.open) this works as expected. However, as already said, the second part is to open the database via php and increment a number (counter). For any reason, I am not able to figure out where the problem is located. I am even not sure if AJAX opens the increment.php file (the alert messages never appears so I guess it is never called). Any suggestion is appreciated and I hope that this question does not just contain a fundamental small error. Thank in advance, Tobi
It's not the way the AJAX works. If you call alert() on a destination page it won't show in your browser. Your case is very basic so I will keep my solution on a basic level.
In increment.php just echo something, it can be just OK string. So when you go to increment.php page you will see only OK, nothing more, nothing less.
Then go back to your javascript and check what is your response.
$.ajax({
url: 'openfoam/increment.php',
success: function(data) {
if (data == 'OK') {
console.log('It works, sir!');
}
}
});
If you don't see a message in a console after these modifications something doesn't work. However, I think your page is executed properly, but you just don't get feedback, because you don't handle the response (data param in your case).
Check it out and don't forget to give me a feedback!🤓

Button On click call jquery function and acess php

I am very new to Wordpress and Woocommerce. I have few doubts wrt jquery in Wordpress. Say i have a function
function test(){
alert("test");
<?php
error_log("Test ---------------------------- ", 0);
?>
}
and a button:
<input type="button" id="btnclick" onclick="test();" value="Test" />`
error log is printing on page load but not on click. But i want to execute code inside php block only when user clicks on button.Is there a way to achieve this ? Thanks in advance`
jPO has already explained how to solve this in a good way, but I thought I should explain why this happens.
PHP is executed on the server. Once the page has been sent to the client, the PHP is no more. JavaScript happends on the client, and can be executed as long as the user is viewing the webpage. Since they do not live during the same timeperiod they are not aware of each other and can not be mixed in that way.
When you visit the page in your browser, the browser sends a request to the server. On the server the PHP interpreter goes through the code of the requested page, executing everything between <? and ?>. It does not understand what the other stuff around it is - it could be HTML, JS, plain text, anything, the PHP interpreter does not know and does not care. That is why it writes to the error log on page load.
When the PHP interpreter is done it has produced a document looking like this:
function test(){
alert("test");
}
That is sent to the client, and the JS (without any instruction to write to the error log) is run on the client when the button is pushed.
Not possible like that. If you'd like to do so. You need something like ajax method in php which you can call. Let's say you have a file in the root of your project called ajax.php, there you can define a function named test(), then you have to have a $_REQUEST translator, which calls your function test(), so the ajax.php would look like this
<?php
// checks if you sent a parameter named method and calls the method
// if you provide parameter named params it will send them too
if(isset($_REQUEST)){
if(isset($_REQUEST["params"]))
ajax($_REQUEST["method"],$_REQUEST["params"]);
else
ajax($_REQUEST["method"]);
}
function ajax($function,$data = null){
$function($data);
}
function test(){
error_log("Test ---------------------------- ",0);
}
and your ajax would look like this
function test(){
$.ajax({
url:"ajax.php",
data:{
method:"test"
}
});
}
hope it helps

Mysql query result is not giving me the right result

I'm updating my php page each 5 seconds
window.setInterval(function(){
console.log(<?=mysql_num_rows(mysql_query("select * from records"))?>)
}, 5000);
If I have 5 records in my table, the output will be 5,
but when I insert a new record, the output remains 5 unless I refreshed the whole page, then it will be 6..
What's wrong?
You have a fundamental misunderstanding of how PHP and Javascript work. Don't worry, it's very common when first learning web development!
When you use PHP to print things onto the page (for example the code inside <?= ?>), the code is executed on the server. Try viewing the source of your page, and you'll see that when the browser receives the page, the PHP code has already been replaced by its result.
This means that when your Javascript loop runs, it's simply writing out the same precomputed value repeatedly.
To accomplish what you're going for, you'll either need to accept simply refreshing the page every 5 seconds, or read up on AJAX. AJAX is how you can load new content from the server (so, anything from the database) without reloading the page. It's what StackOverflow uses to show "1 new answer to this question", for instance.
This is because you are mixing PHP with JS, PHP value is written on page load and it remains that for all the time you stay in the page.
You should use a Ajax request that request again the value.
Do a PHP page that only returns this value:
<?=mysql_num_rows(mysql_query("select * from records"))?>
Then extend you JS with something like this:
setInterval($.ajax({
url: 'your-url-with-php-result',
type: 'GET',
cache: false,
success: function(result){
console.log(result);
}
}), 5000);
You need also to include Jquery to do this
you can not use php in javascript codes
you soulde save php in example.php and you call example.php in javascript code
your example.php like this
<?php
echo mysql_num_rows(mysql_query("select * from records"));
?>
and you can now get data from example around 5 second time by this code (load is jquery function)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
setTimeout(function(){
$("#showRes").load("example.php");
}, 5000);
</script>
</head>
<body>
<div id="showRes"></div>
</body>
</html>
you are normally mix the concept of jaavscript and php .you can solve this very easily . by passing php value into ajax and that value u should catch in that javascript .Try viewing the source of your page, and you'll see that when the browser receives the page, the PHP code has already been replaced by its result.
write php code in php page like:-
<?=mysql_num_rows(mysql_query("select * from records"))?>
and use js as different page . call that value as your requirement.
like:--
setInterval($.ajax({
url: 'your-url-with-php-result',
type: 'GET',
cache: false,
success: function(result){
console.log(result);
}
}), 5000)
if u need some jquery then you also include that in your code .

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

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.

Yii redirect from controller action after ajax call not working

I use the following buttons in my view file (don't pay attention to second one, but I just wanted to show you why I'm not using a normal form submit):
<?php echo CHtml::Button('Search Symptom(s)', array('id'=>'search')); ?>
<?php echo CHtml::Button('Add Another Symptom to Search', array('id'=>'addSymptom')); ?>
When the user clicks the buttons this javascript runs (it's inside a document.ready function)
$('#search').click(function()
{
//create new symptom in javascript
var newSymptom =
{
symptomCode: $('#symptomToBeSearchedCode').val(),
dateSymptomFirstSeen: $('#dateSymptomSeen').val(),
symptomTitle: $('#symptomToBeSearchedTitle').val()
};
//pass new symptom into symptomsList array
symptomsList.push(newSymptom);
//make ajax call to server
$.ajax({
type:'POST',
url: '/mysymptomsbook/index.php?r=symptomhistory/search',
data:{symptomsList: symptomsList} ,
dataType:'html'
});
});
symptomsList is an array with JS objects
This is the code in my controller action:
if(isset($_POST['symptomsList']))
{
foreach($_POST['symptomsList'] as $symptom)
{
//populate symptom search model attributes with user id, current date, and form input
$newSymptom = new Symptomhistory;
$newSymptom->setAttributes(array(
'user_id'=>Yii::app()->user->id,
'dateSearched'=>date('Y-m-d'),
'symptomCode'=>$symptom['symptomCode'],
'dateSymptomFirstSeen'=>$symptom['dateSymptomFirstSeen'],
'symptomTitle'=>$symptom['symptomTitle'],
));
//save search history
$newSymptom->save();
//add into the searched for symptoms code the latest code
array_push($symptomCodes, strval($symptom['symptomCode']));
}
$this->redirect(array('disease/index'));
}
I was planning on using redirect to send the $symptomCodes array to the other controlleraction (DiseasesController and actionIndex), but even without passing anything the redirect doesn't work. The models get saved to my database normally.
Anyone have any idea what is wrong? I'm thinking it has to do with Ajax since it's waiting for a response, but I want my controller to redirect instead. Any help as always, is greatly appreciated :)
I had similar problem, recommend you to look at this topic at official forum:
redirect not working when called via Ajax-Request
See the last answer in topic.

Categories

Resources