I feel like I must be missing something, or I'm just too clueless to search for the right question, so please pardon me (and redirect) if this is a duplicate. My issue is probably much harder than I think it should be.
I have a page with a rather lengthy block of php code (mainly MySQL queries) which generate variables that are eventually passed into JavaScript as strings. The data is then used to create some interactive form elements. The end result is a textarea field which contains a JS string which I'd like to carry into to a new page. I will also be POSTing php variables to that new page.
Sample code:
<?php //Get data from MySQL, define variables, etc.?>
<script> //Move php strings into JavaScript Strings;
//put JS vars into textareas; etc
var foo = document.getElementById('bar').value </script>
<form action="newpage.php" method="post">
<input type="hidden" id="id" name = "name" value="**JAVASCRIPT foo INFO HERE**"/>
<input type = "hidden" id="id2" name = "name2" value = "<?php echo $foo; ?>" />
<input type="submit" name="Submit" value="Submit!" />
Calling JS functions in the right order is a little sticky because they depend on php variables which aren't defined until queries are complete, so I can't do much with an onload function. I'm literate in php. I'm a novice in JavaScript. I'm fairly inept with JQuery and I've never used AJAX. I'd also really rather not use cookies.
It would be great to see an example of what the original and new page code might look like. I know I can receive the php on the new page info via
$foo = $_POST['name2'];
beyond that, I'm lost. Security isn't really a concern, as the form captures information which is in no way sensitive. Help?
If you don't need to use the failure function, you can skip the AJAX method (which is a bit heavier), so I would recommend you make use of the $.post or $.get syntax of jQuery.
Pre-defined syntax: jQuery.post( url [, data ] [, success ] [, dataType ] )
Here is the example for jQuery:
$.post('../controllerMethod', { field1: $("#id").val(), field2 : $("#id2").val()},
function(returnedData){
console.log(returnedData);
});
Otherwise, you could use the AJAX method:
function yourJavaScriptFunction() {
$.ajax({
url: "../controllerMethod", //URL to controller method you are calling.
type: "POST", //Specify if this is a POST or GET method.
dataType: "html",
data: { //Data goes here, make sure the names on the left match the names of the parameters of your method you are calling.
'field1': $("#id").val(), //Use jQuery to get value of 'name', like this.
'field2': $("#id2").val() //Use jQuery to get value of 'name2', like this.
},
success: function (result) {
//Do something here when it succeeds, and there was no redirect.
}
});
}
function init()
{
var str1 = <?php echo varname; ?> //to access the php variable use this code//
document.getElementById('id').value= str1;
}
<body onload="init()">//make sure you call the function init()`
did you try something like this
Related
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
I have a PHP file that requests six rows from a database. I'm using an ajax call.
I want these six rows (multiple columns) to be passed through to my main file. I was unable to find a way to get these values to my main page except for posting them in html in the request file and posting this as a table on my main page.
I don't want them on the page in a plain table for everyone to be seen.
So not like this:
success: function(html) {
$("#display").html(html).show();
}
I always need six rows at the moment but could be more later on.
One of the ideas that I had was posting it as one long string and loading this into a variable, and then reading using explode or something a-like. Not sure if this is a good way to do this...
I am basically asking for ideas to expand my horizon.
I am still learning JavaScript and jQuery so I'd rather have a good explanation than a block of working code.
Thanks in advance!
PHP Side
This is a very simple process, which you may kick yourself after grasping ;) But once you do, it opens a world of possibilities and your mind will go crazy with ideas.
The first stage is you want to adjust your data that you will be returning to the ajax call. If you have a few rows of a few fields, you would do have something along these lines (could come from db, or assignments, whatever):
$rows = [];
$rows[] = array('thing'=>'value 1','something'=>'blah','tertiary'=>'yup');
$rows[] = array('thing'=>'value 2','something'=>'yadda','tertiary'=>'no');
$rows[] = array('thing'=>'value 3','something'=>'woop','tertiary'=>'maybe');
Now, to get this rows of data out to ajax, you do this one simple operation:
echo json_encode($rows);
exit; // important to not spew ANY other html
Thats all you really need to do on the PHP side of things. So what did we do? Well, we took a multidimensional array of data (usually representing what comes from a database), and encoded it in JSON format and returned it. The above will look like this to your browser:
[{"thing":"value 1","something":"blah","tertiary":"yup"},
{"thing":"value 2","something":"yadda","tertiary":"no"},
{"thing":"value 3","something":"woop","tertiary":"maybe"}]
It will have handled all escaping, and encoding of utf8 and other special characters. The joys of json_encode()!
JAVASCRIPT Side
This side is not as difficult, but theres some things to understand. FIrst off, lets get your jquery ajax call into shape:
<div id="rows"></div>
<script>
$("#your-trigger").on('click',function(e){
e.preventDefault(); // just stops the click from doing anything else
$.ajax({
type: "POST",
url: 'your_ajax.php',
data: { varname: 'value', numrows: '6' },// your sent $_POST vars
success: function(obj) {
// loop on the obj return rows
for(var i = 0; i < obj.length; i++) {
// build a div row and append to #rows container
var row = $('<div></div>');
row.append('<span class="thing">'+ obj[i].thing +'</span>');
row.append('<span class="details">'+
obj[i].something +' '+ obj[i].tertiary
+'</span>');
$("#rows").append(row);
}
},
dataType: 'json' // important!
});
});
</script>
So lets explain a few key points.
The most important is the dataType: 'json'. This tells your ajax call to EXPECT a json string to turn into an object. This object becomes what you define in the success function arg (which I named obj above).
Now, to access each specific data variable of each row, you treat it as an object. Array of rows, each row has vars named as you named them in PHP. This is where I have the for example to loop through the array of rows.
For example obj[0].thing refers to the first row of variable thing. The use of i lets you just go through all rows automatically based on length of the object. A few handy things in there.
You can build any html you wish from the returned object and values. I just showed how to setup a <div><span class="thing"></span><span class="details"></span></div> example row. You may want to use tables, or more complex setups and code.
To keep the return data from your ajax call, you can store it in a local or global variable like so:
<script>
var globalvar;
$....('click',function(e){
var localvar;
$.ajax(.... success: function(obj){
....
localvar = obj;
globalvar = obj;
....
});
});
</script>
Do what Frederico says above. Return json from your php and get in in jQuery using ajax call.
Something like this: http://makitweb.com/return-json-response-ajax-using-jquery-php/. Just skip step #3 and do what you need with received data in step #5 if you don't need it to be printed to html.
I have a simple form on my homepage (index.php), that takes one user input.
<form action="/run.php" method="POST" target="_blank"
<input type="text" name="userinput">
<button type="submit">Run!</button>
</form>
That input is then passed to run.php where the content is displayed and inserted into a MySQL database.
However, I need to run JavaScript functions on that user input, and then input the results (from the JavaScript function) into the database (so passing the value from JavaScript to PHP).
I originally had the JavaScript in the run.php, which worked for calculating and displaying the value, but I was unable to pass the value to PHP to insert into the database.
From what I've read, you can't pass JavaScript values to PHP on the same page, as it requires some sort of POST or GET, so I'm attempting to run the JavaScript functions on the homepage index.php and then use a hidden input field to POST the value to the run.php file.
<input id='hidden_input' type='hidden' name='final-calc' value='random(userinput)' />
Where the function is a JavaScript Promise:
function random(userinput) {
....
.then(function(userinput) { // Function needs to use the userinput from the form
// calculations
return X //(X being any random value)
}
}
The two problems I'm running into is that:
I can only get the userinput value after the user enters a value and submits the form, so I don't believe I can pass that userinput value into the JavaScript function and still POST the returned value?
The JavaScript function is an asynchronous Promise, but apparently, this might not have an effect - so it may not be a problem.
The key here is AJAX. You have to retrieve the userinput using plain JS, make any calculations needed and then send the results to your PHP script. I left a fiddle: https://jsfiddle.net/k5xd54eu/1/
<input type="text" id="userinput" name="userinput"/>
<button onclick="inputhandler();">TEST</button>
<script>
function inputhandler() {
var text = document.getElementById('userinput').value;
alert(text);
/*DRAGONS BE HERE*/
/*THEN*/
/*USE AJAX HERE TO PASS THE RESULTS TO PHP SCRIPT*/
}
</script>
I'm not explaining how to implement the AJAX call to send the results, mainly because it's a matter of taste too. For example you can use plain JS or a library such as jQuery (which is my personal preference, since it's very clean and easy). Take a look here:
http://api.jquery.com/jquery.ajax/
and here:
https://www.w3schools.com/jquery/jquery_ajax_intro.asp
for more information.
EDIT: Since I've mentioned AJAX, it would be more correct to include some code. So this is what I generally use for simple POSTs (it's based on the jQuery library so be careful to include it):
var url = 'ajaxhandler.php';
var stuff = '1234abcd';
$.ajax({
type: "POST",
url: url,
data: {stuff: stuff},
success: function (data) {
/*Do things on successful POST*/
}
});
I have a CHTML:ajax function that does some AJAX stuff on a select dropdown - I simply want to do something which says..
"on change, grab the selected value & pass that as param childID in the URL"
This should then display the following in the url section of the
CHTML::ajax function:-
'url' => 'isAjax=1&childID=5134156'
I've tried to append the variable selected onto the url but it doesn't work - can anyone see what I'm doing wrong
jQuery(function($) {
$('#child-form select[name="Child[user_id]"]').bind('change', function(e){
var selected = this.value;
console.log('selected : '+selected ); // outputs an ID to the console.
<?php echo CHtml::ajax(array(
'url' => '?isAjax=1&childID='+selected,
'type' => 'post',
'update' => '#parents-sidebar',
// rest of the ajax function (quite long...)
You can't take a value extracted from the dom using javascript and inject it directly into PHP code.
From the PHP.net documentation:
Since Javascript is (usually) a client-side technology, and PHP is
(usually) a server-side technology, and since HTTP is a "stateless"
protocol, the two languages cannot directly share variables.
CHtml::ajax() is primarily a shortcut for generating javascript code. So the easy solution would just be to write your javascript manually. That will allow you to use your selected variable.
Note:
You might try Taron Saribekyan's solution, posted in the comments. The idea is that the javascript expression ('...+selected') will be printed by PHP as a string, and thus be evaluated by javascript. In theory, this should work.
That is obvious. You have defined a javascript variable and you are using it in your php code! Everything inside <?php ?> block, will interpret on the server and before javascript. So, I think you should use normal jquery ajax method in your case. Something like this:
$.ajax({
"url": <?php echo Yii::app()->baseUrl.'/controller/action' ?>'?isAjax=1&childID='+selected,
'type' => 'post',
...
})
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.