onClick not working on ajax generated content [duplicate] - javascript

This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
My code doesn't show errors, but also doesn't work as it should. The output from the ajax call is working fine but I just can't get anything out of the onClick, no errors message, nothing.
The HTML
<div id="serials"></div>
<div id="accounts_info_key" style="text-align:left"></div>
The Ajax call
$(document).ready(function() {
$('.tab2').click(function(){
var account_id = $('#account_id').val();
$.ajax({
url: 'ajax/account_info_serials_ajax.php',
type:'POST',
dataType: 'json',
data: 'account_id='+account_id,
success: function(response){
$('#serials').html(response.table),
$('#accounts_info_key').html(response.key),
$('.drop_down').hide();
},
error:function (xhr, ajaxOptions, thrownError){
alert(thrownError);
} // End of success function of ajax form
}); //end of ajax
});//close trigger
});//close whole function
The PHP
$response = '';
$response .='<div class="question">';
$response .='plop';
$response .='</div>';
$response .='<div class="drop_down">';
$response .='bob';
$response .='</div>';
$output_array = array(
'table' => $response,
'key' => $key,
'count' => $count
);
echo json_encode($output_array);
The jquery onclick
$(document).ready(function() {
$('#serials').on("click", ".question", function(e){
alert('smeg');
});
});
Please note, I am not asking how to do it, I am asking why my version is not working, it is NOT a duplicate question

I have created a fiddle that shows how it should be done in my opinion http://jsfiddle.net/6VtA8/.
$(document).ready(function () {
$('.tab2').click(function () {
var account_id = $('#account_id').val();
$.ajax({
url: '/echo/json/',
type: 'POST',
dataType: 'json',
data: {'something':'else'}
}).done( function (response) { $('#serials').html('<div class="question ">abcd</div>'); });
});
}); //close whole function
$(document).ready(function () {
$('#serials').on("click", ".question", function (e) {
alert('smeg');
});
});
There are multiple reasons that could cause your code to not work. It could even be the fact that your div (from some css rule) would end up having a height of 0 and therefore the event wouldn't trigger. So instead of debugging I chose to do a little rewriting.

You have to subscribe to the event click on #serials once it's in the dom. So when your ajax callback is over and that .question is in the dom, you subscribe to the click on #serials.

Related

Updating an input field with PHP vale in JavaScript

I want to update the value of an input field when I receive some information from an api. I tried using:
$('#txtFirstName').val($_SESSION['jUser']['first_name']);
But an error occurs due to the PHP not being able to run in a js file. How can I make this update otherwise? Is there a way in js to update the entire form and input fields without submitting?
I can't reload the entire window, because it will eliminate other information that the user of the website has put in.
1) put value into #txtFirstName from php script
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
echo $_SESSION['jUser']['first_name'];
}
// javascript code
function func(){
$.ajax({
type: "POST",
url: "script.php",
success: function (response) {
$('#txtFirstName').val(response);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
2) put value into $_SESSION['jUser']['first_name'] from javascript
// javascript code
function func(){
var your_value = "some_value";
$.ajax({
type: "POST",
url: "script.php",
data: { va: your_value },
success: function (response) {
console.log("value setted to session successfully");
},
error: function (e) {
console.log("ERROR : ", e);
}
});
}
// script.php code
if ($_SERVER['REQUEST_METHOD'] === 'POST' && $_POST['va'] !='') {
$_SESSION['jUser']['first_name'] = $_POST['va'];
echo "ok";
}
Why don't you just echo the value from php script and make an AJAX request from javascript to get the value ? This should be the recommended approach.
However, it can also be accomplished with the approach you've taken:
let first_name = <?php echo $_SESSION['jUser']['first_name']; ?>:
$('#txtFirstName').val(first_name);
For further reading, you can visit How do I embed PHP code in JavaScript?
.

Calling PHP function when clicking <button type="submit"> [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 5 years ago.
I inserted an onclick to my button but don't know where I'm going wrong here but it seems like the function is fired each time the page is loaded.
How can I call the function ONLY when clicking on the button itself
<button type="submit" class="btn btn-primary" onclick="<? $query = DB::update('ads')->set(array('sale_agreed' => '999'))->where('id_ad', '=', $msg_thread->ad->id_ad)->execute(); ?>"><?=_e('ACCEPT This Offer')?></button>
Any take on this? Thanks ;-)
You can make use of jQuery Ajax to perform this operation.
Add a button with some id.
<button id="click-button"></button>
Inside your script tag.
$(document).read(function(){
$("#click-button").click(function(){
$.ajax({
url: "remote-file.php",
method:"POST",
data:"token=buttonclick",
success: function(result){
if(result != "fail"){
//Perform actions with the results...
}
}});
});
});
In you PHP remote-file.php
<?php
if(isSet($_POST['token']) && $_POST['token'] == 'buttonclick'){
$result = myFunction();
echo $result;
}else{
echo "fail";
}
function myFunction(){
// Perform your DB actions...
return true; //Return your data
}
?>
You can't use php functions from client side. The attribute "onclick" fires a javascript funciont, not a php one.
In order to execute a php function with onclick, you have to make an Ajax request to the server.
$('.button').click(function() {
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
.success(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In the "url" variable you have to put the url to your php script, and the data object contains all the PHP $_REQUEST parameter to be send to the script. The success function executes once the script is complete.
Button click is client side whereas PHP is server side, but you can achieve this by using AJAX.
$('.button').click(function() {
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
In your PHP file:
<?php
function abc($name){
//your code here
}
?>
You cant add php functions to client side button clicks.
You should get your PHP to check if the page has been submitted and then run your function

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

Can't process simple form submitted by jQuery ajax

My form:
<form id="new-protocol-form" method="post" role="form">
<textarea name="text"></textarea>
</form>
My jquery ajax:
$('#submitProtocol').click(
function() {
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function() { alert{'ok'} },
error: function() { alert('error'); }
});
}
);
My newProtocol.php:
<script>
alert(<?php echo $_POST['text']; ?>);
</script>
Alert window with 'ok' text triggered by ajax 'success' method is shown, but I can't get alert window with $_POST['text'] value from newProtocol.php file. No error in javascript console.
You need to use $_POST['text']. You're using parentheses where you shouldn't be.
In addition, since you're using AJAX you probably don't want to navigate to the other page. Your alerts in your success function will never fire if you don't prevent the default behavior.
newProtocol.php
<?php
echo $_POST['text'];
?>
jQuery
$('#submitProtocol').click(function(event) {
event.preventDefault(); // stop the default click behavior
$.ajax({
type: "POST",
url: "newProtocol.php",
data: $('#new-protocol-form').serialize(),
success: function(data) {
console.log(data); // show the text being returned
},
error: function() { console.log('error'); }
});
}
);
Also, quit using alert() for getting return values and trouble-shooting.
First, $_POST is not a function, it's an array. So it should be $_POST['text']. Also,
<script>
alert(<?php $_POST('text'); ?>);
</script>
will not create an alert like you expect since an async request does not run any javascript in the target page.
Since you're trying to test if the AJAX is working, the best way is to check what was the date returned from that request. Example:
//...
success: function(data) { console.log(data) },
//...

Header wont redirect when passedthrough ajax

Not sure if this is possible but I have a page that submits a form with AJAX and if it meets certain conditions it should automatically take the user to another page. NOTHING is outputted before the header tag its just a bunch of conditions.
Problem: Header redirect not working...
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
header("Location: http://localhost/manage/card.php?id=$id");
Headers can only be modified before any body is sent to the browser (hence the names header/body). Since you have AJAX sent to the browser, you can't modify the headers any more. However, you can have the add.php script called via AJAX return the $id parameter. Then that parameter can be used in JavaScript to redirect the page: window.location = 'http://localhost/manage/card.php?id=' + id.
More info on PHP header(): http://www.php.net/manual/en/function.header.php
AJAX
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
window.location = 'http://localhost/manage/card.php?id=' + data;
}
});
});
add.php
$row = mysqli_fetch_array($result);
$id = $row['id'];
echo $id;
exit;
You indicate in the question that under certain conditions, you want a redirect.
To do that, you would want to alter your javascript to contain an if condition, and to watch for certain responses.
I would recommend modifying your responses to be json, so that you can pass back different information (such as a success status, as well as a redirect url, or other information you might want).
$('form').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '_ajax/add.php',
data: $('form').serialize(),
success: function (data) {
var response = $.parseJSON(data);
if (response.redirect) {
window.location = response.redirect_url;
} else {
$("input").val('Company Name');
$("form").hide();
getInfo();
}
}
});
});
As for your add.php file, you'll want to change this to be something more like so:
$json = array(
'redirect' => 0,
'url' => '',
}
if (...condition for redirect...) {
$row = mysqli_fetch_array($result);
$id = $row['id'];
$json['redirect'] = 1;
$json['redirect_url'] = "Location: http://localhost/manage/card.php?id=$id";
}
echo json_encode($json);
die();
You seem to have a miss understanding of how AJAX works. Introduction to Ajax.
The reason why your redirect appears not to working is because an Ajax call doesn't directly affect your browser. It's a behind the scenes call.
To get the data out from the AJAX call you need to do something with the returned data.
success: function (data) {
$("input").val('Company Name');
$("form").hide();
//You need to do something with data here.
$("#myDiv").html(data); //This would update a div with the id myDiv with the response from the ajax call.
getInfo();
}

Categories

Resources