jQuery PHP passing values within functions vs live clicking? - php

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>

Related

AJAX - form submit, same page, PHP

EDIT: I have changed the AJAX code to what I am now using and I have also included JQuery in my code
I've read up on as much AJAX as I can and I am flat out failing!
My HTML form looks like this:
<form action="match_details.php" method="post" id="match_details">
....
<button type="submit" form="match_details" name="match_details" class="w3-button w3-block w3-mam w3-section" title="Update Match Postcode">Update</button>
</form>
From Stack I've managed to get this AJAX:
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>
I've tried changing it from button to input and back again but nothing seems to change. The form still submits but it ignores the AJAX and the page refreshes.
You need to prevent the JS from submitting the form, and you're using the wrong form ID. Also, judging by the comments, you need to include jquery.
In the head of your HTML file, between <head> and </head> or just before the closing </body> tag, you can use the following:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
The following code may help you (though it's advised to not query the same page as your ajax request emits from):
<script type="text/javascript">
$(function(){
$('button[type=submit]').click(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "match_details.php",
data: $("#match_details").serialize(),
beforeSend: function(){
$('#result');
},
success: function(data){
$('#result').html(data);
}
});
});
});
</script>

SQL query without refresh

I've read all the related posted, watched videos, and read tutorials... But I still can't figure this out. I just want to run a mysqli_query insert without a refresh.
No inputs, no variables, just a pre-defined sql insert without a refresh.
Here is the main doc:
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
$("#click").click( function()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
});
</script>
</head>
<body>
<input type="button" id="click" value="Click">
</body>
</html>
Click.php (Has been tested standalone):
<?php
$db = mysqli_connect("localhost","root","","mytable")
or die("Error " . mysqli_error($db));
mysqli_query($db,"INSERT INTO items VALUES
('','test','test','total test','test','test','test','test')");
?>
This has been driving me crazy... I've read tutorials and watched many videos about ajax... but I can't figure this out.
Thank you for any advice.
To refresh a part of a page you got to bind the success function to a div in the html so add a div with an Id
<div id="myDiv"></div>
And then
$('#like$id').click(function()
{
$.ajax({
url: 'inc/scripts/liker_ajax.php?like=$id',
type: 'GET',
success:function(result){
$('#like$id').addClass('green');
$('#dislike$id').removeClass('red');
$('#myDiv').html(result);
}
});
});
You're binding the event $('#click').click() before there is an element to bind to (since $('#click') isn't loaded yet).
Just move your <script> tag with the click binding event into the <body> underneath the input button and it will work as expected.
You might also want to wrap in a jQuery document ready enclosure like:
$(function() {
});
to make sure it runs when DOM ready.
Try this.
<html>
<head>
<script src="inc/scripts/jquery-1.11.3.min.js"></script>
<script>
function runAjax()
{
$.ajax({
url: "click.php",
type: 'POST',
success: function(result) {
//finished
}
});
</script>
</head>
<body>
<input type="button" id="click" onclick="runAjax()" value="Click">
</body>
</html>
You are binding the event to the element when the element is not exixting yet.
You have 2 options here.
Either move your script block to just below the end of body tag after the element.
Encase your code inside the script block under $(document).ready(function() {
// your code here
});
Also use the console tab under your developer tools to find the root cause if any errors are present.

PHP not capture $_POST data send by ajax jquery on same page

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().

Pass a JS variable to a PHP variable

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

simple jquery fetch from mysql

I am trying to use jQuery with MYSQL and I wrote something like this :
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script>
function example_ajax_request() {
$('#example-placeholder').html('<p>Loading results ... <img src="ajax-loader.gif" /></p>');
$('#example-placeholder').load("loadres.php");
}
</script>
</head>
<body>
<div id="query">
<select name="show" id="box" >
<option value="0">Select A Test</option>
<option value="All">--All--</option>
<option value="M1">Model1</option>
</select>
<input type="button" onclick="example_ajax_request()" value="Click Me!" />
</div>
<div id="example-placeholder">
<p>Placeholding text</p>
</div></body>
</html>
Basically I want to pass parameters to the loadres.php file. But unable to figure out the exact way to do.
Any help is appreciated.
Thanks.
You should use the $.ajax() method from jQuery. you can pass data to the url and have a callback at the end.
$.ajax({
url: 'loader.php',
data: 'somedata',
type: 'GET',
success: function(data){
$('#example-placeholder').text(data);
}
});
This will do the trick. This method also provides far more flexibility. You can have different functions such as error functions and complete functions.
$('#example-placeholder').load("loadres.php?show=" + $('#box option:selected').val());
This will use jquery to get the selected value from the drop down list and append it to the URL as a querystring parameter, which you can access in the loadres.php page.
similar to saif-bechan's post you can use ajax with post and data can hold an object to pass multiple parameters
$.ajax({
type:"POST",
url: loadres.php,
data: {
foo:'bar',
selected:$('#selector').val()
},
dataType: 'json',
error: function(data) {
//error code here
},
success: function(data) {
//success code here
}
});
I will also note that is is better to put your click event in jquery context not in the html
so in script somewhere use
$('#button_id').click(function(){
//call to ajax
};

Categories