I'm trying to figure this out from 2 hours with no luck, maybe it's not that technical but I need help!
I've an AJAX script that needs to send a GET request to a php script that's on the same page.
The PHP script terminates like this
if ($success) {
print( $state );
}?>
The Javascript is rightly under the php termination and is this.
<script>
$('table button').click( function() {
var button = $(this);
/* if button inside the table is clicked */
var username = button.parent().parent().children('td').html();
var state = button.html();
/* send GET request */
$.ajax({
type: "GET",
url: 'index.php',
data: 'username='+username+'&state='+state,
success: function(response) {
alert(response);
}
});
});
</script>
What I don't understand is why I get the alert containing this text
inside // this is the state, so it's good
<script> // this is the script, not good
$('table button').click( function() {
var button = $(this);
/* if button inside the table is clicked */
var username = button.parent().parent().children('td').html();
var state = button.html();
/* send GET request */
$.ajax({
type: "GET",
url: 'index.php',
data: 'username='+username+'&state='+state,
success: function(response) {
alert(response);
}
});
});
</script>
I've to manipulate the HTML on success by I'm not able to do that because of the messy response that I get from my php code. I'm not sure if I've to post other code. If you need to know more just ask, I'll reply as soon as possible.
Any characters outside <?php ?> tags are sent back in the response. That's how you get that <script> tag in the first place when you access index.php from the browser.
echo and print are obviously going to also send data.
So I guess you should have that if($success) at the begining of index.php and exit; inside it, after print.
Characters outside <?php ?> tags are sent as part of the response for historical and practical reasons.
In our days having PHP code mixed with HTML is a bad practice (as some people already pointed out in the comments bellow). You either use a templating engine (most people know about Smarty) or use PHP itself as a templating engine.
But "back in the day" PHP started out as just a simple templating engine (no classes, external modules, namespaces, autoloaders, etc.), so mixing HTML with PHP was basically the purpose of this language.
As I said, today we still use PHP as a templating language so mixing PHP (control structures, loops) and HTML works.
A quick, but not recommended fix is to avoid the javascript content on an ajax request
Just demonstrating, how it could be,
if($success) {
print( $state );
}
if(!isset($_GET['ajax_call']))
{ ?>
<script>
$('table button').click( function() {
var button = $(this);
/* if button inside the table is clicked */
var username = button.parent().parent().children('td').html();
var state = button.html();
/* send GET request */
$.ajax({
type: "GET",
url: 'index.php?ajax_call=1',
data: 'username='+username+'&state='+state,
success: function(response) {
alert(response);
}
});
});
</script>
<?php
}?>
.....
and you should note that the new ajax call has an additional variable, ajax_call,
This is a quick fix, for you to move on, but i suggest you to use an MVC framework.
Related
I'm trying to figure out how I can load a partial page (div) into another div using AJAX in my php page.
basically I have a div with some php output stuff, and I need to put that div's content into another one using ajax but my code doesn't do anything (it doesn't put the div's content into the other one).
this is my current code:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({
type: "GET",
url: "<?php echo $actual_link; ?>",
dataType: "html",
success: function(response) {
// $("#ajaxContent").html(response);
$("#issomeone").html($(response).find("#notis"));
setTimeout(load, 4000);
}
});
}
load();
});
</script>
so the #notis div holds the php output and the #issomeone div is the div that i need to put the stuff in using ajax.
is there something missing in my code or I'm just doing it all wrong?
any help would be appreciated.
Thanks
EDIT:
THIS DOESN'T DO ANYTHING:
<script type="text/javascript">
$(document).ready(function () {
function load() {
$.ajax({
type: "GET",
url: "<?php echo $actual_link; ?>",
dataType: "html",
success: function(response) {
// $("#ajaxContent").html(response);
//$("#issomeone").html($(response).find("#notis"));
$('#issomeone').load("<?php echo $actual_link; ?> #notis");
setTimeout(load, 4000);
}
});
}
load();
});
</script>
You are finding the DOM element and then trying to set that as target element's innerHTML with html(). You in essence have a type mismatch.
You would need to get the innnerHTML of #notis to pass as the parameter to this function so:
$("#issomeone").html($(response).find("#notis").html());
Alternately, you could append the node if you want to keep the whole #notis element
$("#issomeone").append($(response).find("#notis"));
But really, since you are using a straight GET, you might be better off simply doing:
$('#issomeone').load('<?php echo $actual_link; ?> #notis');
This provides a more simple abstraction to what you are trying to do more manually with .ajax()
I would however encourage you to not get in the habit of loading full HTML pages and then scraping them for some particular element. It is better design architecture to have the AJAX target script serve up only content that is needed when possible.
I have a PHP file which has code to echo some HTML. I would like to provide the PHP file to some end users which can be done like this:
<?php include 'file.php'; ?>
Unfortunately my users will for instance have index.html and this will not work. I don't want to ask my users to change there HTML file in to PHP. Another approach is to modify the .htaccess file:
<Files index.html>
AddType application/x-httpd-php .html
</Files>
I don't want to ask this of them as well. So what are my other options? Is it possible to show the echoed results in HTML file? Maybe with the help of some Javascript?
You can do this with AJAX. It might look a bit challenging, but it is frankly much simpler than many think. In fact, it's pretty easy.
Ajax goes in your javascript code, and looks like this:
$('#stSelect').change(function() {
var sel_stud = $(this).val();
//alert('You picked: ' + sel_stud);
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'theOption=' + sel_stud,
success: function(whatigot) {
alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END dropdown change event
Note that the data from the PHP file comes into your HTML document in the success function of the AJAX call, and must be dealt with there. So that's where you insert the received data into the DOM.
For example, suppose your HTML document has a DIV with the id="myDiv". To insert the data from PHP into the HTML document, replace the line: alert('Server-side response: ' + whatigot); with this:
$('#myDiv').html(whatIgot);
Presto! Your DIV now contains the data echoed from the PHP file.
The ajax can be triggered by a change to an control's value (as in the above example), or just at document load:
$(function() {
//alert('Document is ready');
$.ajax({
type: "POST",
url: "your_php_file.php",
data: 'Iamsending=' + this_var_val,
success: function(whatigot) {
//alert('Server-side response: ' + whatigot);
} //END success fn
}); //END $.ajax
}); //END document.ready
Look at this example for ideas on how it works.
Note that the above examples use jQuery, and therefore require this reference in the tags of your page:
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
This will replace the body of the html page with the contents of the url called.
$('body').load( url,[data],[callback] );
If they can add javascript, an ajax request should do the work...
<script>
var req = new Request({
method: 'get',
url: 'file.php',
onRequest: function() { // loading image
},
onSuccess: function(response) {
document.getElementById("destination").innerHTML = response;
}
}).send();
</script>
They will also need a div for the code to get in:
<div id="destination"></div>
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Calling a JavaScript function returned from a Ajax response
var url = "showpdf.php";
$.ajax({
type: "post",
url: url,
data: {academic:academic,uni:uni,course:course,lan:lan,sem:sem,subject:subject,type:type,clz:clz},
success: function(response)
{
alert(response);
document.getElementById("alldata").innerHTML = response;
}
});
inside response i have bellow html code with simple JavaScript function
<label onclick="popup()"> clickme </label>
<script>
function popup()
{
alert("hello");
}
</script>
here, this popup()function is not working please help me.
The problem is you expect that Javascript contained within an ajax response is executed. This isn't the case, the browser doesn't execute any Javascript contained within ajax responses. It might be possible to try to parse out the Javascript and execute it in some way, such as eval() but that would be nasty and not a good idea. Using eval() you also have to consider that it will only accept valid Javascript, so you couldn't just pass your response to it because that includes some HTML.
A possible solution could be to have the popup() function already defined in the page or an external Javascript file, and to assign the click handler after you add the HTML to the DOM.
For example:
function popup()
{
alert(this.id);
}
document.getElementById("alldata").innerHTML = response;
document.getElementById("myNewLabel").onclick = popup;
Make that string hidden in your page and just display it on success. like:
<label onclick="popup()" id="mylable" style="display:none"> clickme </label>
<script>
function popup()
{
alert("hello");
}
</script>
var url = "showpdf.php";
$.ajax({
type: "post",
url: url,
data: {academic:academic,uni:uni,course:course,lan:lan,sem:sem,subject:subject,type:type,clz:clz},
success: function(response)
{
// alert(response);
$("#mylable").show();
}
});
Better way to try with DOM. Let me know if above code is work for you.
I just want to pass my variable data.company_name from callback function:
<script>
function AjaxInsert() {
var company_name = $("#company_name").val();
dataToSend = {};
dataToSend.company_name = company_name;
$.ajax({
url: 'insert.php',
data: dataToSend,
dataType: "json",
success : function(data) {
console.log("my variable: "+data.company_name);
}
});//ajax*/
}
</script>
,below in the same script into a PHP (PHPExcel) method:
<?php
$var_needed = 'I need that data.company_name here';
$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$var_needed);
?>
How can be this achieved?
The "same script" has been executed already, so you won't be able to interact with it anymore after page load.
You either want to manipulate your spreadsheet client side with a JS library, or to drop ajax and reload the whole page [and ruin your user experience by the way].
<?php
$var_needed = $_REQUEST['company_name'];
$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$var_needed);
?>
$objWorksheet->setCellValueByColumnAndRow(0,$num_rows+1,$_POST['company_name']);
UPDATE: Wow that was the fastest response ever and so many answers in minutes of each other. Amazing. Ok here is what I am trying to do. http://edvizenor.com/invoice33/
I want to edit this invoice on the fly but when I hit the BLUE BOX at the top I want to preview or see this content on the next page contained php var echoed out.
This blue box will change later to be a button at the bottom but for testing I am using it.
As you see it calls the ajax script but I need the edited content of the div to be sent a php var to I can echo it on the preview page. If I can put it in a php var I do what I will with it on the next page. Does that make sense? Thanks guys for your quick responses.
OLD POST
Is it possible to get the contents of a div using jQuery and then place them in a PHP var to send via GET OR POST?
I can get the contents of the div with jQuery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#MyButton").click(function()
{
var htmlStr = $("#MyDiv").html();
});
});
</script>
But how do I put the jQuery var in a php var. I need to do this by a BUTTON press too. This is not included in the code above. I need because the div file is changeable and when I hit UPDATE and send via PHP it needs to have the latest content.
According to your situation,
You are trying to send JavaScript variable to PHP.
The only common way to do this is to exchange in JSON format,
for example, suppose we have basic text editor
Jquery:
$($document).ready(function(){
$("#submit-button").click(function(){
$.post('yourphpscript.php', {
//this will be PHP var: //this is JavaScript variable:
'text' : $("#some_text_area").text()
}, function(response){
//To avoid JS Fatal Error:
try {
var result = JSON.parse(response);
//get back from PHP
if ( result.success){ alert('successfully changed') }
} catch(e){
//response isn't JSON
}
});
});
});
PHP code
<?php
/**
*
* So we are processing that variable from JavaScript
*/
if ( isset($_POST['text']) ){
//do smth, like save to database
}
/**
* Well if you want to show "Success message"
* that div or textarea successfully changed
* you can send the result BACK to JavaScript via JSON
*/
$some_array = array();
$some_aray['success'] = true;
die( json_encode($some_array) );
You'll need to use ajax to send the value to your server.
var html = $('#myDiv').html();
$.ajax({
type: 'POST',
url: '/SomeUrl/MyResource.php',
data: JSON.stringify({ text: html }),
success: function(response)
{
alert('Ajax call successful!');
}
});
The thing you need is AJAX (see http://en.wikipedia.org/wiki/Ajax_(programming))
The basic idea is to send a http request with javascript by e.g. calling a php script and wait for the response.
With plain Javascript AJAX requests are a bit unhandy, but since you are already using jQuery you can make use of this library. See http://api.jquery.com/jQuery.ajax/ for a complete overview.
The code on client side would be something like this:
$.ajax({
url:'http://example.com/script.php',
data:'var=' + $('#myDiv').html(),
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
In your script.php you could do something like this:
$var = $_GET['var'];
// Do some processing...
echo 'response';
and in your javascript console the string response would occur.
In modern ajax based applications the best practise way to send and receive data is through JSON.
So to handle bigger datasets in your requests and responses you do something like this:
$.ajax({
url:'http://example.com/script.php',
data:{
var:$('#myDiv').html()
},
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
And in your PHP code you can use the $someArray = json_decode($_GET['var']) to decode JSONs for PHP (it will return an associative array) and $jsonString = json_encode($someArray) to encode an array to a JSON string which you can return and handle as a regular JSON in your javascript.
I hope that helps you out.
You can use hidden form fields and use jQuery to set the value of the hidden field to that, so when the button is clicked and form submitted, your PHP can pick it up as if it were any other form element (using $_POST). Alternatively, you can use AJAX to make an asynchronous request to your PHP page. This is probably simpler. Here's an example:
$("#myButton").click(function() {
var htmlStr = $('#myDiv').html();
$.post("mypage.php", { inputHTML : htmlStr },
function(data) {
alert("Data returned from mypage.php: " + data);
});
}
Yes, Its possible
<script type="text/javascript">
$(document).ready(function(){
$('#MyButton').click(function(){
$.post('sendinfo.php',
{
data: $('#data').html()
},
function(response){
alert('Successfully');
});
});
});
</script>
<div id="data">Here is some data</div>
Use ajax for sending value to php (server).. here's a good tutorial for ajax with jquery http://www.w3schools.com/jquery/jquery_ajax.asp
you should just use Ajax to send your variable.
$.ajax({
url:'whateverUrl.php',
type:'GET',
data:{
html : htmlStr
}
});
Using AJAX:
$("#MyButton").click(function() {
var htmlStr = $("#MyDiv").html();
$.ajax({
url: "script.php",
type: "POST",
data: {htmlStr : htmlStr},
success: function(returnedData) {
//do something
}
});
});
Something like below should work.
Read more: http://api.jquery.com/jQuery.post/
$("#YourButton").click(function(e){
e.preventDefault();
var htmlStr = $("#YourDiv").html();
$.post(
url: 'YourPHP.php',
data: '{"htmlStr" : "'+htmlStr+'"}',
success: function(){
alert("Success!");
}
);
});
Send the data via XmlHttpRequest ("ajax") to your php page either via POST or GET.