I posted a more specific question on this yesterday, but I think my problem is more basic than what I initially asked.
I am trying to use PHP to set a setTimeout() with a wait variable from a database, but any script I echo doesn't work, even if it involves no PHP manipulation. Take a look below.
Here is the ajax call
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
success: function(html)
{
$("#contentWindow").html(html);
}
});
}
// Initial Load
loadContent();
And here is the PHP it receives.
echo '<h1>Upload content to start the show</h1>';
echo '<script>
setTimeout(loadContent, 4000);
</script>';
The is showing, so I believe the ajax and the PHP is working properly. The script works properly when I place it inside the javascript file, but the script won't run when it's echoed to the page.
My problem is the javascript I echo doesn't run. How can I use PHP to send javascript to the user? Why is what I wrote not functioning?
UPDATE: I realized that when I echo script, it echoed to the middle of the body and technically is above where the script file is loaded on the bottom of the body. Can I echo to the bottom of the body?
Here is a workaround:
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
success: function(html)
{
var myArray = html.split("|");
var message = myArray[0];
var counter = parseInt(myArray[1]); //Minor fix
$("#contentWindow").html(message);
startCounter(counter);
}
});
}
function startCounter(counter){
//counter as the value of 1000 milliseconds are equal to 1 second
setTimeout(loadContent, counter);
}
PHP File
$refreshTimer = 1000; //This is a test
echo "Upload content to start the show|".$refreshTimer; //The message and the counter
If you return just the script portion in your php file you can set the dataType in the .ajax call to 'script' and it will execute the returned javascript (http://api.jquery.com/jquery.ajax/)
So:
function loadContent()
{
$.ajax(
{
url: "controller/loadContent.php",
cache: false,
dataType: 'script',
success: function(html)
{
$("#contentWindow").html(html);
}
});
}
// Initial Load
loadContent();
Then in your PHP:
echo 'setTimeout(loadContent, 4000);';
Related
On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?
I want passing 2 parameters to PHP page via AJAX and load the response, but this code is not working.
JavaScript:
$(".show_category").click(function(){
var category_id = $(this).attr('data-category');
$.ajax({
url: "conx.php",
method: "POST",
data: {
action: "sort_category",
category_id: category_id
},
success: function(data) {
$("#con").load("conx.php");
}
});
});
PHP:
<?php
echo "1".$_POST["action"]."<br/>";
?>
You issue is here:
success: function(data) {
$("#con").load("conx.php");
}
At this point, you have already posted the data and received the HTML response. There is no need to make another HTTML request by calling .load, and doing so will mean requesting it again without the POST data, so it will not have the intended effect. Just use the HTML you already have in the data argument.
success: function(data) {
$("#con").html(data);
}
On a side note, this PHP code is a reflected XSS vulnerability:
<?php
echo "1".$_POST["action"]."<br/>";
?>
I have a small problem. I need to send a php variable from php file to second php file using setInterval. I dont know how i can write php variable in jquery code.
first.php
<?php
$phpvariable=1;
?>
In JavaScript
setInterval(function odswiez(id)
{
$('#chat').load('second.php?id=<here php variable how?>');
}, 3000);
});
second.php
<?php
$w=$_GET['id'];
echo $w;
?>
you need to echo your value
$('#chat').load('second.php?id=<?php echo $variable ?>');
}, 3000);
Alternative to do this will be..
$('#chat').load('second.php?id=<?php echo "id-{$variable}" ?>');
}, 3000);
insted of
setInterval(function odswiez(id)
{
$('#chat').load('second.php?id=<here php variable how?>');
}, 3000);
to
setInterval(function odswiez(id)
{
$.ajax({
url: "second.php",
type: "GET",
data: { id: "<?php echo $php_id; ?>" }
success: function(data){
$('#chat').load(data);
},
error: function(){}
});
}, 3000);
I think that's isn't the best way to manage this kind of Ajax calls,
First, I suggest you instead of bringing an entire PHP file passing a GET argument, you should just pass the params and receive just plain data.
var myvalue = $('.whateverinput').val();
$.ajax({
type: "POST",
dataType: "json", //can be post or get
url: "second.php", //you php who will recive data
data: {myname : myvalue},
success: function(data) {
// Callback if all things goes Ok you will recive data
$(".the-return").html("here we atach the response"+data);
},
error: function(xhr, error){
//if something wrong callback do something
console.debug(xhr); console.debug(error);
}
});
I recommend using JSON to send/receive your data between PHP and javascript.
You can find more info in :
Example using ajax php and using json
Good Luck!
I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.
(Newb here) I have a PHP function that gets 2 csv files from the server and create a new one with the difference between values contained in those files. This PHP function is inside a separate file test.php and looks like this:
<?php
require_once('libs/parsecsv-for-php-master/parsecsv.lib.php');
$csv1name = $_POST['csv1'];
$csv2name = $_POST['csv2'];
$data1 = 'data/'.$csv1name.'.csv';
$data2 = 'data/'.$csv2name.'.csv';
$csv1 = new parseCSV($data1);
$csv2 = new parseCSV($data2);
$csv = new parseCSV();
$csv->data[0] = array('label','difference');
$j = 1;
for ($i = 0; $i < count($csv1->data); $i++) {
$csv->data[$i+1] = array($j.'d',$csv1->data[$i][$csv1name] - $csv2->data[$i][$csv2name]);
if($i == 0) {$j += 20;}
else {$j += 21;}
}
$csv->save('test.csv');
?>
This function works correctly and produces the expected csv file.
I have a JavaScript function that sits on another page (namely update.html) and calls the aforementioned php function via ajax:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
error: function(requestObject, error, errorThrown) {
alert(error);
alert(errorThrown);
},
});
}
PROBLEM: The error function is always executed, that is, whenever I run callPHP() I get two alerts.
QUESTION: Why is it error always being called?
(Extra: Is it possible to work with the response variable? How can I debug it without having to upload my files to a server every time? Is it guaranteed that when the complete function is called, the $csv->data function was already resolved?)
Thanks for helping!!! :D
UPDATE 1: I changed the code above by removing the complete function from ajax and I added some extra parameters to the error function.
complete is always called no matter its success or error. So you are running into error condition and complete gets called anyway after error is executed. You can add additional params (jqXHR jqXHR, String textStatus, String errorThrown) in error function to figure out what the error is.
Try using success instead of complete, and add a JSON answer to your PHP script for example echo json_encode((object) array('success'=>true)); because your AJAX call has dataType:"json" parameter for a JSON response, so your AJAX call will try to parse a JSON.
PHP code:
header('Content-Type: application/json');
echo json_encode((object) array('success'=>true));
AJAX:
function callPHP() {
$.ajax({
type:"POST",
url:"test.php",
dataType:"json",
data:{csv1: '02-01-2015', csv2: '02-12-2014'},
success: function(response) {
alert(response);
},
error: function(response) {
alert(response);
},
});
}