I have a JavaScript value given by Google maps and I need to save it in a MySQL database.
Actually I have the variable
<script>
...
var lugar = results[0].geometry.location;// this gives me a latitud, longitud value, like: -34.397, 150.644
...
</script>
And I need to pass that variable to the PHP variable lugar
<?
$lugar= ?????
?>
You can use jQuery ajax for this, but you need to create another script that save on your database:
<script>
$.ajax({
url: "save.in.my.database.php",
type: "post",
dataType:"json",
data: {
lugar: results[0].geometry.location
},
success: function(data){
alert('saved');
},
error: function(){
alert('error');
}
});
</script>
"save.in.my.database.php" receives a $_POST['lugar'] and you can save on your database.
You will need to pass it via a form submission, cookie, or through a querystring.
You can POST through a form or pass it in the URL if you're doing it on page transition, then just use $_POST or $_GET to receive the variable.
If you need it done seamlessly then you might want to look at using AJAX.
TIZAG AJAX Tutorial
This will convert js variable to php variable
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>
Demo: http://ibence.com/new.php
Related
I have several links in a HTML/PHP page and I want to pass the value stored in the link when they are clicked to the next PHP page via $_POST (I know how to do it with $_GET but that is not what I want).
I know I need to use javascript/jquery and I have tried a lot of different things but I haven't been able to get it working. I can add an onclick attribute to href, if it helps to solve the problem.
INSIDE "page1.php" or "page1.html"
// Send the values of variables var1, var2, etc. to the new PHP page...
<div class="super">
good
</div>
<div class="super">
better
</div>
<div class="super">
best
</div>
<script>
(function() {
$("#id").on("click",function(e) {
e.preventDefault();
$.post(this.href,function(value) {
$(".top").html(value);
});
});
});
</script>
INSIDE "page2.php"
<?php
// Retrieve the URL variables (using PHP and jquery).
$val_1= $_POST['var1'];
$val_2= $_POST['var2'];
$val_3= $_POST['var3'];
//to test we retrieved the values from page1
echo "value of var1 is: ".$var_1;
?>
The issue is because you're not sending any data in the $.post call. Presumably you want to send the id/value of the a elements.
Firstly, note that value is not a valid attribute of an a element. I'd suggest changing this to a data attribute to avoid validation issues.
Secondly, to send the data in the request you can build an object, like this:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="super">
good
</div>
<div class="super">
better
</div>
<div class="super">
best
</div>
<button id="id">Click me!</button>
<script>
$(function() {
$("#id").on("click", function(e) {
e.preventDefault();
var data = {};
$('a').each(function() {
data[this.id] = $(this).data('value');
});
console.log(data);
$.post(this.href, data, function(value) {
$(".top").html(value);
});
});
});
</script>
** Update **
When any of the href link is clicked, page2.php is opened and based on which linked is clicked e.g. 'link3 above' which has a value 300, the page2.php does something based on that value. I don't want to pass all values of the links at once
In this case you can just read the data-value from the element and send it in the request and read it back in the PHP:
$(function() {
$(".super a").on("click", function(e) {
e.preventDefault();
$.post(this.href, {
value: $(this).data('value')
}, function(value) {
$(".top").html(value);
});
});
});
<?php
$val = $_POST['value'];
echo "value of var1 is: ".$val;
?>
var value= $(this).attr('value');
After that pass thus value to ajax function.
Example:
var record_id=jQuery(this).attr('data-key');
jQuery.ajax({
url: url,
dataType:'json',
type: "POST",
data:{
record_id:record_id,
}
I am building a simple sign up form using ajax when I creating a data object and pass to PHP file.It shows variables and doesn't show values of that PHP variable.
The code of HTML of form is
<form id="myForm" name="myForm" action="" method="POST" class="register">
<p>
<label>Name *</label>
<input name="name" type="text" class="long"/>
</p>
<p>
<label>Institute Name *</label>
<input name="iname" type="text" maxlength="10"/>
</p>
<div>
<button id="button" class="button" name="register">Register »</button>
</div>
</form>
The code of js is
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
The code of PHP is
(mainlogic.php)
if(isset($_POST)) {
print_r($_POST);//////varaibles having null values if it is set
$name=trim($_POST['name']);
echo $name;
}
You are serializing your form on document load. At this stage, the form isn't filled yet. You should serialize your form inside your button click event handler instead.
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
In this code you serialize blank form, just after document is ready:
<script>
$(document).ready(function(){
var form=$("#myForm").serialize();
$("#button").click(function(){
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Valid click function should begins like:
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({...
It means - serialize form right after button clicked.
var form = $("#myForm").serialize();
That is the line that collects the data from the form.
You have it immediately after $(document).ready(function() { so you will collect the data as soon as the DOM is ready. This won't work because it is before the user has had a chance to fill in the form.
You need to collect the data from the form when the button is clicked. Move that line inside the click event handler function.
The problem is that you calculate the form values at the beginning when loading the page when they have no value yet. You have to move the variable form calculation inside the button binding.
<script>
$(document).ready(function(){
$("#button").click(function(){
var form=$("#myForm").serialize();
$.ajax({
type:"POST",
url: "mainlogic.php",
data:form,
success: function(result){
alert(result);
}
});
});
})
</script>
Alpadev got the right answer, but here are a few leads that can help you in the future:
ajax
You should add the below error coding in your Ajax call, to display information if the request got a problem:
$.ajax({
[…]
error: function(jqXHR, textStatus, errorThrown){
// Error handling
console.log(form); // where “form” is your variable
console.log(jqXHR);
console.log(textStatus);
console.log(errorThrown);
}
});
$_POST
$_POST refers to all the variables that are passed by the page to the server.
You need to use a variable name to access it in your php.
See there for details about $_POST:
http://php.net/manual/en/reserved.variables.post.php
print_r($_POST); should output the array of all the posted variables on your page.
Make sure that:
⋅ The Ajax request ended correctly,
⋅ The print_r instruction is not conditioned by something else that evaluates to false,
⋅ The array is displayed in the page, not hidden by other elements. (You could take a look at the html source code instead of the output page to be sure about it.)
I am using ajax to post data on the same page and trying to echo posted data with php with following script.
$('button').click(function(){
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function(){},
success: function(data){alert(data)},
error: function(err) {alert(err.responseText);}
})
})
and php script is :
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
my html is:
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
My problem is php does not echo posted data on page, but when i post form data on another php file which is same php script; php is able to echo posted data and ajax is alert that. please help me to resolve this issue. thanks
It's difficult to tell without seeing your entire PHP page as one listing, but from your description it sounds like your issue is either because of the way you are declaring your .click() event or the way you are posting to the page. The former is more likely.
The $.ajax() request will use an XMLHttpRequest object to POST to your PHP script. The PHP script should then take those values and generate the return string from the combination of the plain text in the script and the inserted echo'd values. This should then be received by the success method's callback function and alerted to your page as a blob of HTML text in the alert box.
Indeed, this is exactly what happens if I use the following code:
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script>
$(document).ready(function() {
$('button').click(function() {
$.ajax({
type: "post",
data: $("form").serialize(),
beforeSend: function() {},
success: function(data) {
alert(data);
},
error: function(err) {
alert(err.responseText);
}
});
});
});
</script>
</head>
<body>
<?php echo isset($_POST['data']) ? $_POST['data'] :''; ?>
<form>
<input type="hidden" name="data" value="to_success"/>
<button type="button">Click Me</button>
</form>
</body>
</html>
However, if I comment out the lines for $(document).ready(function(){ and its corresponding end });, then nothing happens when I click.
So, try wrapping your .click() event definition in a $(document).ready().
I am writing a plugin for a wordpress, where I use jquery for AJAX.
Following code doesn't work. I expect to show the content in results div when I type in input box.
Here is the code I use for ajax request. It is located on my theme header file.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" >
$(document).ready(function(){
//alert("sjsjs");
$("#se").keypress(function(e){
// e.preventDefault();
var search_val=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_string:search_val
},
success:function(data){
$('#results').append(response);
}
});
});
});
</script>
html content in template file
<form name="nn" action="" method="post"></br></br>
<input id ="se" type="text" name="test" width="20" />
<input type="submit" id="clicksubmit" value="Submit" />
</form>
<div id="results">val is:
</div>
Here is the code in plugin file
function wpay_search() {
//global $wpdb; // this is how you get access to the database
$whatever = $_POST['search_val'];
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
add_action('wp_ajax_wpay_search', 'wpay_search');
add_action('wp_ajax_nopriv_wpay_search', 'wpay_search');
I am new to wordpress plugin writing. Can anybody tell that where I have done the mistake?
Well one thing that obviously jumps out to me is this...
success:function(data){
$('#results').append(response);
}
Should be...
success:function(data){
$('#results').append(data);
}
Because you have no variable called response, you passed the function data as a variable, so you have to use that.
Also, you're passing search_string as a paremeter, when infact in your php file, the $_POST is looking for search_val.
So you need to send search_val as parameter and give your JavaScript search_val variable another variable name in the JavaScript, just for less confusion. In this case I made it search.
action:'wpay_search',
search_val:search
So overall it should look something like this...
$("#se").keypress(function(e){
e.preventDefault();
var search=$("#se").val();
$.ajax({
type:"POST",
url: "./wp-admin/admin-ajax.php",
data: {
action:'wpay_search',
search_val:search
},
success:function(data){
$('#results').append(data);
}
});
});
I'm trying to pass some values through onclick which to me is so much faster. But I need to use some kind of "live" clicking and I was looking into .on() or .delegate(). However, if I do any of those, passing those values within followme() seems a little harder to get. Is there some kind of method that I'm not seeing?
<div class='btn btn-mini follow-btn'
data-status='follow'
onclick="followme(<?php echo $_SESSION['user_auth'].','.$randId;?>)">
Follow
</div>
function followme(iduser_follower,iduser_following)
{
$.ajax({
url: '../follow.php',
type: 'post',
data: 'iduser_follower='+iduser_follower+'&iduser_following='+iduser_following+'&unfollow=1',
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text('Follow');
}
});
}
As you can see, its easier to just pass values from PHP to jQuery... Is there another way?
You can assign more data values, and you know what use is logged in, all you need is to pass who to follow:
<div class='btn btn-mini follow-btn'
data-status='follow'
data-who='<?php echo $randId; ?>'
id='followBTN'>
Follow
</div>
<script>
$('#followBTN').on('click', function(){
$.ajax({
url: '../follow.php',
type: 'post',
data: {
iduser_following: $(this).attr('data-who')
},
success: function(data){
$('.follow-btn').attr("data-status",'follow');
$('.follow-btn').text(data.text);
}
});
});
</script>
You can process $_SESSION['user_auth'] and the status directly from PHP, there is no need for you to pass them in jQuery. Make sure document is ready when you insert on click event.
just use the jquery 'on' event. Attach a new attribute called data-session to the div and then retrieve it using .attr method. You have the example bellow to show you an alert with the data, you just have to substitute it with your code
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(document).on('click', '#follow-me-button', function(){
alert($(this).attr('data-session'));
})
})
</script>
</head>
<body>
<div id="follow-me-button" class='btn btn-mini follow-btn' data-status='follow' data-session ="MY-SESSION-DATA-FROM-PHP">
Follow
</div>
</body>
</html>