passing arguments to php function using jquery [duplicate] - php

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I'm having problem with my code below:
jquery
var data = $('thisForm').serialize();
var msg = <?php echo computeAverage(data)?>;
alert(msg);
php
function computeAverage($data){
return $data;
}
I'm getting " data"(string) as the output and not the actual value of data. By the way, I only use one php file that contains the jquery and php function above.
Your help will be appreciated. I really need to figure this out. I'm new to jquery.
thank you for your replies.
given that i need to place my php function to a separate file
jquery
var url = "myPhpFunction.php";
var data = $('thisForm').serialize();
$post(url,data, function(response)); // how can i get the reponse from my url?
php
function computeAverage($data){ // how to convert $data to an array?
return average; // how can i return the average back to my jquery?
}
can anyone help me? thanks

PHP code is executed on the server before the client starts executing Javascript. All the code within <?php ?> are executed first.
After the PHP code has been executed, it will send output to the client which will look like:-
var data = $('thisForm').serialize();
var msg = data; // echo executed
alert(msg);
Now javascript will start executing.
The PHP will not consider javascript variable data as it is a part of client-side scripting.

You cann't pass the value from the javascript to PHP function as PHP execute on SERVER side and Javascript execute Clint side.
You should use the Ajax for doing such thing.

use $.post for sending data to your php script!
<script type="text/javascript">
$(document).ready(function () {
$("#autocomplete").keyup(function(e){
var form = $("#autocomplete");
var data = form.serialize();
$.post("ajax_form.php", data, function(response) {
$( "#autocomplete" ).autocomplete({
source: response
})
})
})
})
</script>
html part:
<input class="formfeld" id="autocomplete" name="suchfeld" title="type "a"">

Related

How to pass a variable from jQuery to PHP? [duplicate]

This question already has answers here:
How do I pass JavaScript variables to PHP?
(16 answers)
Closed 8 years ago.
I have a jQuery function, which, on click, itercepts a clicked link:
$("a").click(function(e) {
e.preventDefault();
var link = $(this).prop('href');
alert(link);
});
and it works properly, but how to pass that link to a PHP variable to 'echo' it later?
I unsuccessfully tried:
$("a").click(function(event) {
event.preventDefault();
var link = $(this).prop('href');
<?php $link = .'link'. ?>
});
I know it may be a silly question, I looked all over the web but I didn't find any proper answer.
The only way to do this is to have a script wich stores values passed to it in a session or to a DB and either output the session data later or read from the db
$("a").click(function(event) {
event.preventDefault();
var link = $(this).prop('href');
$.post('saveLink.php', {href : link});
});
the saveLink.php would be something like this
<?php
// Clean your POST variable, always clean any POST variables
// see here for a good discussion on that
// http://stackoverflow.com/questions/4223980/the-ultimate-clean-secure-function
$link = htmlspecialchars($_POST['href']);
$_SESSION['links'] = $link;
?>
then later on you can retrieve all you session data
Note
Session data is not permanent and not shareable between users so if you need to do that you would be better off with a db query also if you need to access a particular link then you will need to send some sort of id with it.
PHP is preprocessor running on a server side. jQuery is running on client side (in user's browser) and it can't comunicate with PHP like this.
Although you can send the data to PHP with Ajax request and process them in another php script, for example store them in a database.
$.ajax({
url: '/ajax_catch.php',
type:'POST',
data: {
link: link
},
success: function(m){
//what to do after its done
}
});

How to send variables from javascript to PHP

I want to know how to send variables from javascript to php so i can create a variable that contains dynamic sum of rows.
More specific:
When I search in my search box, i want to get the number of rows (1 match is 1 row, 2 matches is 2 rows and so on
I tried to implement this: document.getElementById("i1").value = allCells.length; so i later could call in the php, but i did not work.
This is my javascript, by the way the javascript works perfectly.
<script language="javascript" type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function()
{
$('#search').keyup(function() {
searchTable($(this).val());
});
});
function searchTable(inputVal)
{
var table = $('.table');
table.find('tr').each(function(index, row)
{
var allCells = $(row).find('td');
if (allCells.length > 0) {
var found = false;
allCells.each(function(index, td)
{
var regExp = new RegExp(inputVal, 'i');
if (regExp.test($(td).text()))
{
found = true;
return false;
document.getElementById("i1").value = allCells.length;
}
});
if (found == true)
$(row).show();
else
$(row).hide();
}
});
}
$(function()
{
$('#table a').click(function(e)
{
e.preventDefault();
$('#result').val($(this).closest('tr').find('td:first').text());
});
});
</script>
I wanted to spit the dynamicelly sum of rows her in my table header.
<h3>Total: (<?php print_r($_GET["i1"])?>) </h3>
I hope you can help me.
You probably have never learned the difference between javascript and php
Javascript is clientsided, which means everything is processed by your local system. PHP is server sided which means everything is processed by the server and parsed into html.
You can't send a value from javascript into plain php like you did.
You can however send a post or get to the same script and let that reload a part of your script
http://api.jquery.com/jQuery.get/
http://api.jquery.com/jQuery.post/
You're not the first to want this, and not the first to be told it is impossible the way you imagine. When you browse to a PHP page things go basically like this:
Browser sends HTTP request to server
Server determines what page to send to the browser
Server discovers you want a PHP page
Server executes PHP
Server sends what is returned by PHP to the browser
Browser doesn't know about the PHP and displays HTML
Browser executes Javascript.
Now the important part is that the browser doesn't know what PHP is, but can execute JavaScript, while the server doesn't know what JavaScript is (for simplicity's sake) but can execute PHP. Bottomline: it is hard to communicate between the two because they are executed in different places. You'll most probably want to use AJAX, so here is a supersimple sample:
The PHP page we're going to fetch:
<?
// We're on the server
// We're going to output something:
echo "Yay! You can see me!"; // So the browser sees only "Yay! You can see me!" (without quotes).
?>
JavaScript (with jQuery) to fetch the PHP page:
$("#anElementID").load("thePHPPageWeWantToFetch.php"); // It's that simple! The element with the ID #anElementID now contains "Yay! You can see me!" (without quotes).
I suggest too, use AJAX or something to pass your javascript values to PHP.
You can create a AJAX call, add the data from your javascript, and catch the data in your PHP file.
var value = "Jan";
$.ajax({
url: "/form.php",
type: "post",
data: "name=" + value
});
in your PHP file you can do:
<?php
$catchedName = $_POST["name"];
?>

call php function in javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to call a PHP function in JavaScript?
i have a form to print to a POS printer. Problem 1 is that i cant print directly, Mybe in google chrome in kioskmode.. so. i would like to call a function after the windows be closed from printing. code is like this:
<script type="text/javascript">
$(function(){
$('#printOut').click(function(e){
e.preventDefault();
var w = window.open();
var printOne = $('.contentToPrint').html();
var printTwo = $('.termsToPrint').html();
w.document.write('<html>' + printOne + '<hr />' + printTwo ) + '</body></html>';
w.window.print();
w.document.close();
I INSERTED HERE>>> insert(); <<<<<<<<<<< AND WORKS BUT NOT BY CLOSING THE priter WINDOWS. I dont want to close the BROWSER!
return false;
});
});
</script>
where can i call the php function insert();
You can't call a PHP function since it's on the sever and your JavaScript code is on the client. You can navigate to a PHP containing that function or make an AJAX call to that page.
Navigating via Javascript would be:
document.location = "yourpage.php"
You cannot call PHP functions in the classic sense with Javascript. PHP code is run on the server, while Javascript code is executed in the user's browser window. What you can do however is use a technology called AJAX to send a request back to your server. Using HTTP methods you could initiate a PHP script that returns information back to your Javascript code also over HTTP.

append PHP in jquery [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Creating jQuery AJAX requests to a PHP function
How can i write PHP in Jquery
is there is a way to do this
$('button').click(function(){
<?php session_destroy();?>
}) ;
You can't execute PHP client-side.
But
You can call a php script on click to do what you want:
$('button').click(function(){
$.get("destroySession.php");
});
You can also get or post some values:
var values = {
destroy: true
};
//get request:
$.get("destroySession.php", values);
//post request:
$.post("destroySession.php", values);
You can't execute PHP client-side.
You cannot. PHP is interpreted on the server side and jQuery is interpreted on the client side.
You should either use an anchor <a href="session_destroy.php"> to go to another PHP page and destroy the session or use AJAX to call the destroy function without leaving the page.
jQuery('button').click( function () { jQuery.get("session_destroy.php"); } );

HTML form stop redirect and allow PHP to call JavaScript from within the HTML file

I'd like to have a form on a HTML page not refresh when it's sent, which I've done, but I'd also like to allow the echo command in the PHP file to be able to call JavaScript from within the HTML file.
So far, all the echo commands aren't being carried out, which isn't what I expected.
Here's some code from the HTML and PHP files:
HTML:
<script type="text/javascript">
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
var content = $(this).serialize();
$.post('signup.php?', content);
return false;
});
});
</script>
and the PHP:
echo '<script type=\'text/javascript\'>functionInFile()</script>';
So basically, I'd like the PHP file to be able to invoke a function in the HTML file, while not being redirected when I click submit.
Any help appreciated.
You can use the success callback of the $.post() to execute a function which your PHP passes back. Try this:
PHP
// do some stuff with the posted data
echo 'functionInFile'; // name of js function to execute in calling page
jQuery
function functionInFile() {
alert("recieved");
}
$(function() {
$(".postform").submit(function() {
$.post(
'signup.php?',
$(this).serialize(),
function(func) {
window[func]();
},
'text'
);
return false;
});
});
It could be better to use the callback function of post
jQuery.post( url [, data] [, success(data, textStatus, jqXHR)] [,
dataType] )
So you would execute what ever code is within the reply or pre determined login onsusccess
$.post( 'signup.php?', content,
function( data ) {
//data contains the reply of the post so you can
//exec the code like this using JavaScript
//altogether eval is frowned upon because it is high overhead and opens
//opens up to code injection or whatever
//eval(data);
//so you just execute whatever method you need
functionInFile();
//or you reply from server in json and converto tobject
//reply: {'executeFunction': true}
var obj = jQuery.parseJSON(data);
if (data.executeFunction == true) { functionInFile(); }
}
);
ParseJSON
In order for PHP echo to work. the page MUST reload baecause it is server side.
A webpage cycle is SERVER SIDE, then Client side.
[SERVER] -> [CLIENT -> AJAX to SERVER -> SERVER REPLY ATTACH]
It looks like you're sending the right <script> tag. XHR return values are treated as data though, not executable code. Luckily for you, jQuery has code to check if you insert a <script> tag into the dom and execute it. You should be able to just do:
$.post('signup.php?', content, function(html) {$(document).append(html);});
and your script will execute.
(I would recommend making this happen in a different way though. I've worked on Apps that send large portions of javascript back in AJAX calls, and it's a pain to debug. It would be much better to send back a JSON object with a string for the next action, then keep an object of "approved" actions as a string -> function lookup table.)

Categories