Send js value to php controller by ajax - javascript

I have this button
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
And this button related to this
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
I'm using this script to send value of button to my php controller
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable,
success: function (data){
}
});
}
When I use alert, the result of javascriptVariable is correct and I want it in my controller so I'm trying in my controller to do this:
if(isset($_POST['activation']))
{
$name = $this->input->post('myname');
var_dump($name);
}
But I get null value, what is the wrong?

When you pass data from the browser via AJAX only the data you pass in the data: parameter is sent to the PHP script.
So if you want to test for activation in the PHP script you must actually send that parameter
Also see the amendment to the data: parameter creation below. Its easier to read and a lot easier to code correctly when passing more than one parameter as you dont have to remember &'s and + concatenation.
function handleButton(obj) {
obj.preventDefault();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {activation: 1, myname: obj.id}, // add parameter
success: function (data){
alert(data);
}
});
}
Now the PHP will see 2 parameters in the $_POST array activation and myname
if(isset($_POST['activation']))
{
$name = $_POST['myname'];
var_dumb($name);
}
Or if you are using a framework which I assume you are
if(isset($this->input->post('activation')) {
$name = $this->input->post('myname');
var_dumb($name);
}
EDIT:
Spotted another issue your button has an attribute type="submit" this will cause the javascript to run AS WELL AS the form being submitted in the normal way.
Remove the type="submit" attribute and to be doubly sure that the form will not be submitted as well as the AJAX add a call to preventDefault(); as well before the AJAX call

Since the php script is conditioned by a second POST variable [if(isset($_POST['activation']))], you should post that as well.
function handleButton(obj) {
var javascriptVariable = obj.id;
// alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: 'myname='+javascriptVariable+'&activation=1',// <-- RIGHT HERE
success: function (data){
alert(data);
}
});
}
SIDE NOTE: you could also echo instead of dump the variable:
if(isset($_POST['activation']))
{
echo $this->input->post('myname');
}

Try this in your ajax function :
function handleButton(obj) {
var javascriptVariable = obj.id;
//alert (javascriptVariable);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/admin/active_users",
dataType: 'text',
data: {myname: javascriptVariable},
success: function (data) {}
});
}
And in your PHP script, you can do $_POST['myname'] to get it (maybe $this->input->post('myname') can work, you can test it)

Look two id
<button id="<?php echo $u['id']?>" name="activation" onclick="handleButton(this);" type="submit" class="btn btn-success"></button>
AND
<td id="<?php echo $u['id']?>"><?php echo $u['id']?></td>
For both html elements id is same.It can not be used with in the same page.This may cause a problem for you...

Related

Jquery autocomplete using typeahead suggestion does not display after a successful ajax

I use typeahead.js to put tags for my multiple input. The tags input function correctly except the fact that its autocomplete suggestion does not come out. Is there any way to correct this problem?
I've tried most solution related to my problem that are already on this site but currently still not be able to display the autocomplete suggestion. I am always stuck at the successful ajax response and that's it.
my jquery:
<script>
$("#s_to").tagsinput({
tagClass: 'uk-badge',
typeaheadjs: {
source: function(query) {
console.log(query);
url = "<?php echo base_url(); ?>index.php/<?php echo $loc_pts; ?>/ajax_email";
var s_to = extractLast(query);
ajax_status = "fail";
$.ajax({
url: url,
method: "POST",
data: {
s_to: s_to
},
async: false,
dataType: "json",
success: function(json){
return json.s_to;
}
});
}
}
});
</script>
my input :
<input required type="text" name="s_to" id="s_to" class="controls uk-autocomplete-results" value="<?php echo $s_client_email; ?>" autocomplete="on" data-provide="typeaheadjs" />
my related script:
<script src="<?php echo base_url(); ?>assets/bower_components/typeahead.js/typeahead.jquery.min.js"></script>
console log output screen shot
Supposedly the input able to receive multiple input and each input seleccted will be displayed inside a tag. What make it harder is that no error message displayed. Thus, I know that my ajax is done correctly.
The main issue is that you do not return the array in correct scope. Your return json.s_to; is inside the ajax success function, but you need to return the value in parent scope. So, the code should be like this:
$("#s_to").tagsinput({
tagClass: 'uk-badge',
typeaheadjs: {
source: function(query) {
console.log(query);
url = "<?php echo base_url(); ?>index.php/<?php echo $loc_pts; ?>/ajax_email";
var s_to = extractLast(query);
ajax_status = "fail";
var toReturn = [];
$.ajax({
url: url,
method: "POST",
data: {
s_to: s_to
},
async: false,
dataType: "json",
success: function(json) {
toReturn = json.s_to;
}
});
/* This is the correct scope to return the array */
return toReturn;
}
}
});

AJAX redirect to another php file and pass javascript variable to that same php file

I am new to Ajax. I have here a function that when a button is clicked, you should be redirected to id.php and at the same time pass the value of clicked_id.
Javascript code:
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
$.post('id.php',{ID:clicked_id},
function(data){
window.alert("here");
window.location='id.php';
});
}
Inside my id.php,
<?php
$clickedID = $_GET['ID'];
echo 'here at id.php';
echo $clickedID;
?>
Now the problem is that ID in id.php cannot be identified.
Please help me. I already tried both $_POST and $_GET.
I believe that the problem here is in the passing of the variable.
there is no need for ajax if you wanna pass the id to the id.php after redirection
function clicked(clicked_id){
window.alert("clicked");
window.alert(clicked_id);
window.location='id.php?id=' + clicked_id;
}
in id.php you can get the id like this:
<?php $id = $_GET['id'];
function buttonClicked() {
$.ajax({
url: "id.php", //url for php function
type: "POST",
data: {'clicked_id':clicked_id}, // data to sent
dataType: 'json',
success: function (data)
{
}
});
}
And in your id.php file:
$_REQUEST['clicked_id']

How to get another page on ajax?

I've a problem with my page, first code (let said is hompe.php)
<html>
<div id="trackingkp"></div>
</html>
then on my ajax I've code like these
$( document ).ready(function() {
var dataString = '';
$.ajax
({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'html',
success: function(html)
{
$('#trackingkp').html($(html).find('#trackingkp').html());
//$("#trackingkp").html($(data).find('#trackingkp').html());
}
});
});
and on my ajax controller, I do like these (I'm using framework laravel)
public function tracking($url)
{
//var_dump("AAA");
$this->view('ajax/tracking/'.$url,[]);
}
on my ajax/tracking view like this
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
When I try that is showing
Syntax error, unrecognized expression: "<input type='text'>
I have solved the problem, I'm using another option without using jQuery, so on same time, on controller when load view home.php, I try put load view too like these
public function index(){
is_header();
$this->view('home',[]);
$this->view('ajax/tracking/kp',[]); ---> I add these
is_footer();
}
and on ajax/tracking/kp (view) I put these code
<input type='text'></input>
and is working.
The problem would be in this one:
success: function(html) {
// Problem : $(html).find('#trackingkp').html();
$('#trackingkp').html($(html).find('#trackingkp').html());
}
From which this html response is expected to return a json value
in your given [controller]
<?php
//$json = array();
$json = "<input type='text'></input>";
echo json_encode($json);
?>
Thus this is equivalent to:
$("<input type='text'></input>").find('#trackingkp').html();
In this case, I don't think you might need to call another *.html(). You can simplify / solve this by calling it once:
$.ajax({
type: "POST",
url: host+"ajax/tracking/kp",
dataType: 'json', // Kindly replace [html] to [json] since you are returning a [json] value
success: function(html) {
$('#trackingkp').html(html);
}
});
Hope this helps for your case

ajax - save javascript value to php

After hours of trying to get this to work, i want to ask you :)
So i have a php Page that can display files from a server. Now I can edit
the files with a editor plugin.
Textarea is the tag where the editor gets rendered.
To save the changed text from the editor, I have a button that gets the innerHTML from the surrounding pre tag of the text with javascript.
I now want to pass that variable via ajax to a php variable on the site get.php,
so I can save it locally and send it to the server.
The problem is, that there is no reaction at all, if i click the "Save" button. I tested a lot of answers from similar ajax functions here, but none of them gave me a single reaction :/
php main
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
...
echo "<textarea><pre id='textbox'> ";
echo $ssh->exec($display);
echo "</textarea></pre>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
var show = document.getElementById('textbox').innerHTML;
$(document).ready(function() {
$('#butt').click(function() {
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
}
});
});
});
</script>";
...
get.php
if (isset($_POST["variable"])){
$show =$_POST["variable"];
echo $show;
}
Edit:
This is the actual working state:
echo "<textarea id='textbox'><pre> ";
echo $ssh->exec($display);
echo "</pre></textarea>";
echo '<input type="button" value="Save File" id="butt">';
echo "<script>
$(document).ready(function() {
$('#butt').click(function() {
var show = document.getElementById('textbox').value;
$.ajax({
type: 'POST',
url: 'get.php',
data: {'variable': show},
success: function(data){
alert(data);
},
});
});
});
</script>";
You have an error in the data: {'variable': show)} part. It should be: data: {variable: show}. Also you should use Firebug or Firefox developer tools for these kind of problems. A lot easier to see whats wrong.
I would suggest small changes to see if everything is running as it should.
I can see that pre tag is behind textarea closing tag - try to change it
Try putting var show = document.getElementById('textbox').innerHTML; inside of the ,,butt" function
Then I can see your problem here data: {'variable': 'show')}, - you are sending 'show' as a string - remove quotes to send it as a variable which will appear as a POST value in PHP site.
with this should work:
$.ajax({
type: 'POST',
url: 'get.php',
data: {variable: show)},
success: function (data){
alert(data);

Submit form for php without refreshing page

I've search for many solution but without success.
I have a html form;
<form id="objectsForm" method="POST">
<input type="submit" name="objectsButton" id="objectsButton">
</form>
This is used for a menu button.
I'm using jquery to prevent the site from refreshing;
$('#objectsForm').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function () {
alert('success');
}
});
});
In my php file I try to echo text to the body of my site;
<?php
if (isset($_POST["objectsButton"])){
echo '<div id="success"><p>objects</p></div>';
} else {
echo '<div id="fail"><p>nope</p></div>';
}
?>
I know the path to my php file is correct, but it doesn't show anything? Not even the "fail div".
Does anyone has a solution for me?
Thanks in advance!
The success function takes two parameters. The first parameter is what is returned from the php file. Try changing it to:
success: function (xhr){ alert(xhr);}
Based in your php source..
$.ajax({
type: 'post',
dataType: "html", // Receive html content
url: '/php/objects.php',
data: $('#objectsForm').serialize(),
success: function (result) {
$('#divResult').html(result);
}
});
PHP scripts run on the server, that means any echo you do won't appear at the user's end.
Instead of echoing the html just echo a json encoded success/ failure flag e.g. 0 or 1.
You'll be able to get that value in your success function and use jQuery to place divs on the web page.
PHP:
<?php
if (isset($_POST["objectsButton"])){
echo json_encode(1); // for success
} else {
echo json_encode(0); // for failure
}
?>
jQuery:
var formData = $('#objectsForm').serializeArray();
formData.push({name:this.name, value:this.value });
$.ajax({
type: 'post',
url: '/php/objects.php',
dataType: 'json',
data: formData,
success: function (response) {
if (response == 1) {
alert('success');
} else {
alert('fail');
}
}
});
EDIT:
To include the button, try using the following (just before the $.ajax block, see above):
formData.push({name:this.name, value:this.value });
Also, have the value attribute for your button:
<input type="submit" name="objectsButton" value="objectsButton" id="objectsButton">

Categories