I tried to get a simple ajax-test working but without success. I am trying to pass a variable($add1) from PHP to JS, then let the JS calculate the sum and return it back to a PHP variable via $_POST and ECHO it out in the html.
index.php:
<?php
echo "<script type='text/javascript' src='script.js'></script>";
$add1 = 3;
echo "<script>sum($add1)</script>";
$sum = $_POST['variable'];
echo $sum;
?>
script.js:
function sum(param) {
var sum = 3;
sum = 3 + param;
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
});
}
For some reason this code doesn't work. Any help is appreciated.
I want the php file to pass the $add1 to the Javascript and then i want the javascript to return the var sum back to the php and the php to echo the $sum from the $POST.
$sum from $_POST is actually echoed, but not shown in HTML page, but handled as a response back to Ajax.
You have to add a success function in Ajax closure
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
success: function (data){
document.write(data);
}
});
You will see the answer show in page.
php:
if (isset($_POST['variable'])) {
$sum = some_futher_function($_POST['variable']);
echo $sum;
} else {
echo "<script type='text/javascript' src='script.js'></script>";
$add1 = 3;
echo "<script>sum({$add1})</script>";
}
function some_futher_function($param){
//do some thing
return $return;
}
Include this on your page before your script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
PHP code
<?php
if ($_POST['variable']) { // If ajax request only
$sum = $_POST['variable'] + $add1;
echo $sum;
} else { // Loading in the browser
$add1 = 3;
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="script.js"></script>';
echo "<script>sum(".$add1.")</script>";
}
?>
Javascript
function sum(param) {
var sum = 3;
sum = 3 + param;
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
success: function(result) {
alert(result)
},
error: function(e) {
console.log(e);
}
});
}
Related
Is there a way to get updates from a PHP process while it's not finished and it has been called by ajax? By updates i mean flushed output from the PHP script.
var proc;
$('#start').click(function () {
proc = $.ajax({
type: 'POST',
url: 'execute.php',
// getData function that will get me updated data
getData: function (update){
alert(update);
}
});
});
UPDATE:
Lets say we want to get that echo before this ends.
execute.php
<?php
$progress = 0;
while(1){
$progress++;
echo $progress;
flush();
sleep(5);
if($progress == 100){
break;
}
}
?>
FINAL:
myScript.js
var strongcalcs;
var source;
$('#start').click(function () {
strongcalcs = $.ajax({
type: 'POST',
url: 'execute.php',
beforeSend: function () {
rpm_percent();
},
success: function(result){
source.close();
},
complete: function () {
source.close();
},
error: function () {
source.close();
}
});
});
function rpm_percent() {
source = new EventSource("execute.php");
if(typeof(EventSource) !== "undefined") {
source.onmessage = function(event) {
console.log(event.data);
};
} else {
alert("nono");
}
}
execute.php
<?php
$coco = 0;
function sendMsg($msg, &$coco) {
echo "id: " . $coco . "\n";
echo "data: " . $msg;
echo "\n";
echo "\n";
ob_flush();
flush();
$coco++;
}
header("Content-Type: text/event-stream");
header("Cache-Control: no-cache");
$progress = 0;
while(1){
sendMsg($progress++, $coco);
ob_flush();
flush();
sleep(5);
if($progress == 100){
break;
}
}
?>
I've in the past used Server Sent Events for this (https://www.w3schools.com/html/html5_serversentevents.asp). Internet Explorer is not supported out of the box, but there are polyfills that can solve the issue.
I think Websockets do something similar but don't have experience with those myself.
you can use Ajax callback when success load file from server..
$('#start').click(function () {
proc = $.ajax({
type: 'POST',
url: 'execute.php',
success: function (respon){
//do what u want to do here.
if(respon.status == 0){
alert("failed");
}
else{
alert("ok");
}
},
error: function(xhr, error){
//for error handling
}
});
});
and in your php you can echo what u want to show
<?php
$var["status"] = 0;
//if(your condition){ $var["status"] = 1;}
return json_encode($var);
?>
for more information you can see on here and here
<script>
$("#submit").click(function () {
var newhour= [];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]); // output: each: 07:00,08:30
each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
var jsonString = JSON.stringify(newhour);
$.ajax({
type: "POST",
url: "exp.php",
data:{data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
});
<script>
I want to pass the newhour array values to php and use them to insert into a table.
so php file, exp.php:
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
$sql = "insert into exp_table (hour) values ('$d')";
mysql_query($sql);
}
However I can not take the values. What is wrong with the code?
Could you please help me?
Thanks in advance.
according to the answers i tried this on php side, but it returns NULL.
$data = json_decode($_POST['data'],true);
//$data = explode(",", $_POST['data']);
echo "data: " .$data;
var_dump($data); // no output
foreach($data as $d){
echo $d; // no output
}
You do not have to stringify an array in the javascript.
.ajax looks after all that.
pass
data: {newhours: newhour},
then you will get $_POST['newhours'] in the PHP code which will be the array you had in javascript.
In Ajax there is not "type" params, use "method".
Beside that everything should works, you might need to decode the json using json_decode($_POST['data']) on in your php file.
Hopes it helps !
Nic
Pass the array without JSON.stringify in ajax data post. And fetch the data in php file using $_POST['data'].
I just have tried below code and it working great.
<?php
if(isset($_POST['data'])){
print_r($_POST);exit;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var newhour= [];
arrayNumbers = [['07:00','08:30'],['08:30','18:00','19:00']];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]);
// output: each: 07:00,08:30 each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
$.ajax({
type: "POST",
url: "abc.php",
data:{data: newhour},
cache: false,
success: function(data){
console.log(data);
}
});
});
</script>
Hi I pass an array from php to another to used it on a javascript function using json, but not return nothing, gives me "null" all time.
php code
function getParents($id_child){
include "conexion.php";
$query = $conexion->query('SELECT person_id FROM children WHERE children_id='.$id_child.';');
$query->execute();
while ($res = $query->fetch()) {
$id_parents[] = $res[0]; //family_id
}
return $id_parents;
echo json_encode($id_parents);
}
getParents($_POST['id_child']);
Php who takes the json:
<?php
$json_data=json_encode($id_parents);
?>
function sacarPadres(id_child){
$.ajax({
data: {"id_child" : id_child,
},
url: 'php/functions_sql.php',
type: 'post',
success: function(output) {
}
});
var an_obj= "<?php echo $json_data;?>";
alert(an_obj); // always null
}
<div id="form">
<FORM NAME=form1>
<INPUT TYPE='button' NAME='myFamily' value='add new family' onclick="sacarPadres(70);">
</FORM>
After return type everything is vanish
just remove return type
//return $id_parents;
echo json_encode($id_parents);
Updated
function getParents($id_child){
include "conexion.php";
$query = $conexion->query('SELECT person_id FROM children WHERE children_id='.$id_child.';');
$query->execute();
while ($res = $query->fetch()) {
$id_parents[] = $res[0]; //family_id
}
return json_encode($id_parents);
}
echo $val=getParents($_POST['id_child']);
Ajax
$.ajax({
data: {"id_child" : id_child,
},
url: 'php/functions_sql.php',
type: 'post',
success: function(output) {
alert(output);//alert here
}
});
The return statement causes the program to exit the function. All statements after return will not be executed. Move return to the end of the function or remove at all.
There are quite a few similar problems I could find, but nothing helped, so have to post my own version of this question.
I have 2 php files:
playing.php (contains the web form and sends the ajax call)
plug_search.php (has the form processing code)
Before I started trying to use ajax, the form processing worked perfectly, the query worked as expected and the proper result was returned, based on the search parameters. Now, I want to use ajax, so the results are returned to the same page and it always returns '0'. I tried (seems like) everything I could, ruled out the most probable reasons (incorrect function/call name) - no luck. Feels like something very simple is missing, I suspect the problem is in the declaration of the function, but can't see what's wrong (it seems like the call never reaches processing function in plug_search.php). I stripped all the query code and just trying to return a simple string - still same '0'.
If you could help, I'd appreciate that a lot!
playing.php
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
function search(){
var plug=$("#autocomplete-dynamic").val();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
if(plug!==""){
$("#result").html();
$.ajax({
type: "GET",
url: ajaxurl,
data: {
action: 'ajax_return_search_results',
plug: 'country'
},
success:function(data){
alert(data);
}
});
}
}
$("#button").click(function(){
search();
});
$('#search').keyup(function(e) {
if(e.keyCode == 13) {
search();
}
});
});
</script>
plug_search.php
<?php
add_action( 'wp_ajax_ajax_return_search_results', 'myajax_return_search_results' );
add_action( 'wp_ajax_nopriv_ajax_return_search_results', 'myajax_return_search_results' );
function myajax_return_search_results() {
echo "Success";
die();
}
?>
plug_search.php - Full version
function myajax_return_search_results() {
$value = $_GET['plug'];
$value2 = $_GET['country'];
$sql = "SELECT name, image_url, amazon_url, plug_type FROM adapters_list WHERE plug_type = '$value' AND country LIKE '%$value2%'" or die("Error in the consult.." . mysqli_error($link));
$result = $link->query($sql);
while($row = mysqli_fetch_array($result)) { ?>
<div id="output-product" style="border: 1px solid #333; font-family: Helvetica, sans-serif; font-size: 20px;"><?php echo $row["name"] . "<br />";?>
<?php echo "</div>";
die();
}
Add this code in your functions.php
add_action( 'wp_ajax_ajax_return_search_results', 'myajax_return_search_results' );
add_action( 'wp_ajax_nopriv_ajax_return_search_results', 'myajax_return_search_results' );
function myajax_return_search_results() {
echo "Success";
die();
}
data is returning an error code because you are using .success instead of .done
$.ajax({
type: "GET",
url: ajaxurl,
data: {
action: 'ajax_return_search_results',
plug: 'country'
}
}).done(function(data){
alert(data);
});
You are missing datatype in ajax
Try adding it
$(document).ready(function(){
function search(){
var plug=$("#autocomplete-dynamic").val();
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
if(plug!==""){
$("#result").html();
$.ajax({
type: "GET",
url: ajaxurl,
dataType: 'html',
data: {
action: 'ajax_return_search_results',
plug: 'country'
},
success:function(data){
alert(data);
}
});
}
}
$("#button").click(function(){
search();
});
$('#search').keyup(function(e) {
if(e.keyCode == 13) {
search();
}
});
});
I have an javascript array variable in my view file , how can i send the array to different controller ?
this is html code:
<button id=<?php echo $key ?> onclick="movebutton(this)" class='li'><?php echo $officers['Officer']['name'] ?> </button>
and this is my javascript code:
function movebutton(elem){
var teamMember=new Array();
if( $(elem).parent().attr("class") == "officers_list" ){
$(elem).detach().appendTo('.add_member');
teamMember.push($(elem));
}
else{
$(elem).detach().appendTo('.officers_list');
teamMember.pop($(elem));
}
You can pass any data to controller using ajax -:
Get values you want to a javascript variable and check a sample ajax
$.ajax({
dataType: "html",
type: "POST",
evalScripts: true,
url: '<?php echo Router::url(array(
'controller'=>'controller','action'=>'action'));?>',
data: ({type:variable-value }),
success: function (data){
return true;
// $("#div").html(data);
}
});
To pass data from view to controller:
You can use form but in form your data won't be sent as an array
Using ajax
.
var data = {
val1 = '<?php echo $string ?>';
val2 = '<?php echo $number ?>';
}
$.post( 'controller/action', data , function(response) {
if (response == true) {
// Do this
} else {
// Do that
}
});