Posting Javascript variable to PHP document - javascript

I want to get the value of data-id in my tag and transfer it to a PHP variable.
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
I already got the value of data-id using the javascript below and placed it into a variable, however its not posting on the page.
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid});
});
I tried doing this...
print_r($_POST);
but the array being displayed is empty What am I doing wrong here? Kinda new at this.

If you're trying to post on the same page (which is a bad idea anyway), you should have always have an exit/die; on that PHP catch block, and a success function callback on the $.post.
Example:
Simulated JS:
<?php $adminid = 1; ?>
<a data-toggle="modal" data-id="<?=$adminid;?>" href="#view_contact" class="btn btn-info btn-xs view-admin">View</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("click", ".view-admin", function () {
var adminid = $(this).data('id');
$.post("index.php", {admin_to_pass: adminid}, function(response){
console.log(response);
});
});
</script>
Here on the PHP (same page):
if($_SERVER['REQUEST_METHOD'] == 'POST') {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
}
Or
if(isset($_POST['admin_to_pass'])) {
echo json_encode($_POST['admin_to_pass']);
exit; // this is important
// you must have this or you'll catch the whole document
}
And since in your current code you don't have one, you need the success callback function to process the response which came from the server:
$.post("index.php", {admin_to_pass: adminid}, function(response){
^^^^
console.log(response); // your response from the server is inside (you can name it any name you want)
});

Related

Ajax not calling PHP

I have a problem with ajax calling a PHP code without change current page. In the php_error.log there is no reference to the PHP file. I have no errors on screen or anything to guide me to resolve the problem.
This is my javascript function
<script type="text/javascript">
function getMail(){
var name = $('#username').val();
var dominio = $('#dominio').val();
if(name.trim() == '' ){
alert('Ingrese su nombre de usuario.');
$('#username').focus();
return false;
}else{
$.ajax({
type:'POST',
url:'paginas/recover.php',
//data:'username='+name+'&dominio='+dominio,
beforeSend: function () {
$('.nextBtn').attr("disabled","disabled");
$('.modal-body').css('opacity', '.5');
},
success:function(msg){
$('#username').val('');
$('.nextBtn').removeAttr("disabled");
$('.modal-body').css('opacity', '');
},
});
}
};
</script>
This is the function calling button from the HTML
<button id="nextBtn" type="button" class="btn btn-primary nextBtn btn-lg pull-right" onclick="getMail()" disabled>Continuar</button>
And this is the PHP code
<?php
//include ('../paginas/header.php');
include ('../paginas/funciones.php');
//$dominio = $_GET['dominio'];
//$usr = $_GET['username'];
//getToken($usr,$dominio);
$to_mail = 'mail#gmail.com';//getMail($usr, $dominio);
$to_name = 'Usuario Prueba';
$message = 'Prueba';
$subject = 'Prueba';
sendMail($to_mail,$to_name,$subject,$message);
?>
If I access the PHP file alone, the mail was sent, but when I use the javascript function, nothing happened. The function was invoked because if I don't complete the username in the form the alert was executed.
Thanks
//data:'username='+name+'&dominio='+dominio,
change above line to this make it uncomment and pass data as blank
data:'',

Onclick event with PHP, ajax and jQuery not working

I want to use an onclick event with PHP in order to accomplish the following. I would like to use ajax to avoid the page being refreshed. I want to create buttons on event click.
I don't know how to join the div buttons with the ajax result.
Here is my PHP file: Button.php
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Dymanic Buttons</title>
<script type= "text/javascript" src ="jquery-2.1.4.min.js"></script>
<script type= "text/javascript" src ="test.js"></script>
</head>
<body>
<div>
<input type="submit" class="button" name="Add_Button" value="Add Button"</>
<input type="submit" class="button" name="Modify_Button" value="Modify Button"</>
<input type="submit" class="button" name="Delete_Button" value="Delete Button"</>
</div>
test.js contains this:
$(document).ready(function () {
$('.button').click(function () {
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php',
data = {
'action': clickBtnValue
};
$.post(ajaxurl, data, function (response) {
alert("action performed successfully");
});
});
});
And the other php that is ajax.php
<?php
if (isset($_POST['action'])){
switch($_POST['action']){
case 'Add_Button':
Add_Button();
break;
}
}
function Add_Button(){
echo '<input type="submit" class="button" name="Test_Button" value ="Test Button"</>';
exit;
}
?>
You're calling the <input>'s value, instead of it's name which you set it as.
Change your clickBtnValue to this:
var clickBtnValue = $(this).attr('name');
Since it has Add_Button/Modify_Button/etc.
To append the new button to your div, start by giving it an id, so that we can continue to call it:
<div id="my-buttons">
Now in your ajax request, simply jQuery.append() the html to the div:
$.post(ajaxurl, data, function (response) {
$('div#my-buttons').append(response);
});
You can add the result of request to your div with this:
$.post(ajaxurl, data, function (response) {
$("div").append(response);
alert("action performed successfully");
});
Note the value of your button is "Add Button", not "Add_Button"
You probably want to make sure that each component of your code is working first. The problem may be in your AJAX call, it should be similar to the following:
/** AJAX Call Start **/
// AJAX call to dict.php
$.ajax({
/** Call parameters **/
url: "ajax.php", // URL for processing
type: "POST", // POST method
data: {'action': clickBtnValue}, // Data payload
// Upon retrieving data successfully...
success: function(data) {}
});
Also, make sure you are using the correct routing to your PHP file and that your PHP file is returning a valid response.
EDIT: As per the jQuery Docs, I am fairly certain that the problem is within your AJAX call, specifically your $.post() setup. Please refer here for the proper setup is you want to keep your AJAX call structured as is instead of the way I suggested.
As per the jQuery Docs:
$.post( "ajax/test.html", function( data ) {
$( ".result" ).html( data );
});

Yii2: call javascript function with a button

I want to call a javascript function from a button in php
this is the php code:
//the view
<?php
$form = yii\widgets\ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]);
?>
<?=
$form->field($msubs, 'id_subespecifica', ['options' => ['class' => 'col-md-12']])
->widget(Select2::classname(),[
'data' => ArrayHelper::map($vectorConsul,'sesp', 'sesp'),
'options' => ['id' => 'prueba'],
])
->label(false);
?>
<button class="btn btn-primary" onclick="myFunction()">Add New</button>
<?php
yii\widgets\ActiveForm::end();
?>
And this is the Javascript code:
//Javascript
function myFunction() {
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:{pruebaId:$('#prueba').val()}
// alert(pruebaId);
});
In the javascript function, i need to send the $('#prueba').val() to a php function in the controller:
//Controller
public function actionGetLinea($pruebaId)
{
$model = new PartidaAsociada();
log($pruebaId);
}
But i am getting some errors, i think the button is reloading the whole form and don't recognize the previous data y sent to the form.
Note: The 'alert()' in the javascript function is on commentary because it wont let me use, the form stay loading when i put the alert. thanks beforehand.
I think part of the problem is you aren't preventing the default action of a button click.
We can clean things up a bit too. Hit control+shift+i and choose the console tab to see console.log output.
HTML:
<button class="btn btn-primary _addNew">Add New</button>
Javascript:
$('._addNew').on('click', function(event){
event.preventDefault();
var data = {};
data.pruebaId = $('#prueba').val();
var success = function(data){
console.log("Success!", data);
}
var error = function(data){
console.log("Error!", data);
}
$.ajax({
url:'partidaasociada/get-linea',
type:'POST',
dataType:'json',
data:data
}, success, error);
});

Ajax POST is not posting onclick to current page

Alright so this has been bugging me for a long time now... I have tried everything but I cant get it to work!
So what I want to have is a link that acts as a button, and once you click it, it POSTs an ID number of the button in the form "{ 'id' : id }"
edit-homepage.php:
<script>
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
// after you get response from server
editSlide(id);
});
});
});
</script>
The a href button is created using PHP and I want it to call the ajax function postID( id ) which will post the id so that later I can populate a form via PHP using the posted id.
edit-homepage.php:
echo '<li><a class="inactive" id="slide-'.$info["id"].
'" onClick="postID('.$info["id"].'); editSlide('.$info["id"].'); return false;">'
.'<img src="../images/'.$info["img"].'" width="175"/><p>Edit Slide '
. $info["id"] .'</p></a></li>';
Currently, when I click the link, it opens the alert but it is EMPTY or Undefined. It is supposed to display "ID: 1" for example if the link clicked has a ID of 1.
edit-homepage.php:
<script>
function editSlide($id) {
<?PHP
if (isset ($_POST['id'])) {
echo "alert('success!2');";
}$id = !empty($_POST['id']) ? $_POST['id'] : '';
$data = mysql_query("SELECT * FROM slider WHERE id='$id'") or die(mysql_error());
$info = mysql_fetch_array( $data );?>
document.getElementById("edit-slide-id").innerHTML="Edit Slide #"+$id;
document.getElementById("edit-form").style.display = "block";
document.getElementById("short-title").value="<?PHP echo $info['s_title']; ?>";
}
</script>
Thanks!
With jquery, you don't need to use attributes to attach events, like that:
$(function() { // document ready
$('a.inactive').on('click', function(event) {
event.preventDefault(); // instad of return false
var id = $(this).data('id');
// use $.post shorthand instead of $.ajax
$.post('edit-homepage.php', {id: id}, function(response) {
alert('ID:' + response);
// after you get response from server
editSlide(id);
});
});
});
As of server side, try replacing raw
<?PHP echo $_POST['id']; ?>
With
<?php echo !empty($_POST['id']) ? $_POST['id'] : '' ?>
You likely get notice about Undefined index id, which breaks javascript if there is no post data.
UPDATE
edit-homepage.php shold be separated something like that:
if(!empty($_POST)) {
// here you process your post data and return
// only wenever you want to pass to script
// not all the html
} else {
// here you output html and scripts, but don't do request processing
}
You should always remember, that your HTML rendering must always be separated from your logic. It is better to put views in separate files from logic, though it is not required, it is much easier to debug and maintain.
You can not include PHP code that is supposedly to run after the ajax call. The PHP code will be run only to generate the page. Anything you want to include in alert should be provided in the ajax response, in your case the data variable.
You need to use alert('ID: ' + id).
The $_POST['id'] part of the script does not react to the AJAX request. It is whatever the $_POST['id'] value is when the script is output to the browser (i.e. when the page is first loaded).
You will see this if you view the source.
alert ("ID:"+data);
then only you will get response
or
alert("ID"+id);
this will alert the id passes to function
http://jsfiddle.net/U54ME/
$(".checkthisclass").click(function() {
$.ajax({
type: "POST",
url: "edit-homepage.php",
data: { 'id' : $(this).attr("slideid"); },
success: function(data) {
alert(data);
}
});
}
});
--
<ul>
<li><a class="inactive checkthisclass" id="slide-5" slideid = "5" ><img src="http://blog.entelo.com/wp-content/uploads/2013/04/stackoverflow-logo.png" width="175"/><p>Edit Slide 5</p></a></li>
</ul>

confirm choice in php page using javascript

I'm trying to confirm deleting something, but I can't seem to get it to work.
When the button for 'deleteReply' I'm getting an alert message, but as far as I can tell nothing else is happening. I'm trying to simply echo the posted variable but it doesn't seem to work.
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
On my delete processing page I just have
$echo $_POST['replyID'];
Why do you have
if(isset($_POST['deleteReply'])){
?>
Before the javascript function? Did you expect to trigger the javascript code based on the $_POST['deleteReply'] var?
You have to keep in mind that php is processed server-side and outputs an HTML page. Your javascript code will only run in the client after all the php has run.
A much more elegant solution would be asking for a confirmation BEFORE sending the AJAX request.
And also, your ajax call doesn't seem to do what you're expecting. You're manually setting 2 parameters to send to your PHP which will have no use for it if you do the confirmation server-side.
A parameter should be something like the Reply ID of the reply you want to delete, and send the request to a different php file for handling.
I'd suggest you rewrite your code as Marian Zburlea is doing for you.
EDIT
Ok, if you want a simple confirm window, try this:
<input type="button" id="deleteSomething" value="Delete" />
<script type="text/javascript">
$(document).ready(function(){
$('#deleteSomething').click(function() {
if (!confirm("Are you sure?"))
return false;
$.post('delete.php', "replyID=" + replyID, function(response) {
alert(response);
});
});
});
</script>
EDIT
If you have multiple delete buttons, the best way to do this would be storing the replyID as the parameter to pass to your function. Echo your delete buttons in your php like this:
echo '<input type="button" value="Delete" onclick="deleteSomething(\'' . $replyID . '\')" />';
This way, the $replyID will be stored in the page's HTML, which will be passed to the deleteSomething(replyID) function which you now have to define (preferably in the document's head after the JQuery lib):
<script type="text/javascript">
function deleteSomething(replyID)
{
if (!confirm("Are you sure?"))
return false;
$.post('deleteProcessing.php', "replyID=" + replyID, function(response) {
alert(response);
});
}
</script>
Note that I removed the ID from the buttons to don't generate dupplicate IDs and they are no longer needed, as I've added a function call in the onclick event instead of binding an anonymous function to their IDs as you were doing previously.
<input type="button" id="deleteSomething" value="Delete" />
<div id="yesno" style="display:none;">
<input type="button" id="buttonYes" value="Yes" />
<input type="button" id="buttonNo" value="No" />
</div>
<script type="text/javascript">
// Here you attach a click event to the button Yes with id buttonYes
$('#deleteSomething').click(function() {
$('#yesno').css('display', 'block');
});
$('#buttonNo').click(function() {
$('#yesno').css('display', 'none');
});
$('#buttonYes').click(function() {
$.ajax({
beforeSend: function(e) {
// Code to process before calling AJAX
},
url: "pathToPHPFile.php",
dataType: "json",
type: "POST",
data: {
parameter: 'Yes',
},
success: function (m) {
console.log(m);
alert(m.text);
},
error: function (e) {
console.log("Something went wrong ...: "+e.message);
},
}); /* end ajax*/
e.preventDefault();
});
</script>
<?php
// This is a separate php file named pathToPHPFile.php
if(isset($_POST['parameter']) && $_POST['parameter'] == 'Yes'){
/* here you put the code that deletes the message */
$response['text'] = 'messageDeleted'
echo json_encode($response);
}

Categories

Resources