i have to get the html reply of two php function with AJAX
Here my code
Home.php
<script>
$( document ).ready(function(){
var parameter = {
"mynumber" : $('#mynumber').val()
};
$.ajax({
data: parameter ,
url: 'script.php',
type: 'post',
dataType: 'json',
beforeSend: function () {
$("#loading").show();
},
success: function (response) {
$("#loading").hide();
$("#div1").html(response.reply1);
$("#div2").html(response.reply2);
},
}); });
</script>
And script.php
function loopone(){
for($a=0;$a<10;$a++){
?><div id="mydiv"><?php echo $a;?></div>
}
}
function casetwo(){
if($a<>$g){
?><div id="mydiv2"><?php echo $a;?></div>
}
}
$prew1=file_get_contents(loopone());
$prew2=file_get_contents(casetwo());
$reply1=prew1;
$reply2=prew2;
echo json_encode(array("reply1"=>$reply1, "reply2"=>$reply2));
what's wrong here ? I can not see the results.
file_get_contents() is for reading a file or URL into a string. You don't need to use these if you're creating the content in your script. Just have your functions return strings.
function loopone() {
$result = "";
for (a = 0; $a < 10; $a++) {
$result .= "<div class='mydiv'>$a</div>";
}
return $result;
}
function casetwo() {
global $a, $g;
if ($a != $g) {
return "<div id='mydiv2'>$a</div>";
} else {
return "";
}
}
$prew1 = loopone();
$prew2 = casetwo();
echo json_encode(array("reply1"=>$prew1, "reply2"=>$prew2));
I changed id="mydiv" to class="mydiv" because IDs are supposed to be unique, you shouldn't return the same ID in a loop.
Related
I've written an Ajax code, which calls a function in a php file.
queryURL = "http://<?php echo $_SERVER['SERVER_NAME'] ?>/MyPhpFile.php";
params = fromDate+" , "+to_Date;
$.ajax(
{
url: queryURL,
type: "post",
dataType: 'json',
async: false,
data:
{
funcName: "MyFunc",
values: params
},
complete: function (result) {
debugger;
doSth();
}
});
And in my php file:
if ($_POST) {
if (isset($_POST['funcName'])) {
if (function_exists($_POST['funcName'])) {
G::LoadClass('case');
$fName = $_POST['funcName'];
if (isset($_POST['values'])) {
$values = $_POST['values'];
$arrP = explode(",", $values);
echo call_user_func_array($fName, $arrP);
} else {
echo $fName();
}
}
}
}
fucnction MyFunc($fromDate, $toDate){
echo "1";
}
In the Network tab of my browser's debugger section, I can see that the php file just called once. Yet the response is duplicated.
If my function returns 1, the response will be 11.
Why is this happening?
how can I prevent it?
Remove echo from echo call_user_func_array($fName, $arrP);. Just use call_user_func_array($fName, $arrP);
I am trying to validate my forms by using jQuery and php .. What I am trying to achieve is pass my form inputs to process.php in the background, check if inputs pass my validation code, then return true or false back to my jQuery checkForm() function .. so far the below code is now working ..
function checkForm() {
jQuery.ajax({
url: "process.php",
data: {
reguser: $("#reguser").val(),
regpass: $("#regpass").val(),
regpass2: $("#regpass2").val(),
regemail: $("#regemail").val()
},
type: "POST",
success: function(data) {}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form action="register.php" method="post" onSubmit="return checkForm()">
send all input's in php to validate all the data.
function checkForm() {
$.ajax({
url : "process.php",
type: "POST",
data: $('#yourForm').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status)
{
alert("Success");
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
alert(data.inputerror[i] + "|" + data.error_string[i]);
}
}
}
});
};
validating the data you've sent through Ajax.
public function process()
{
$this->_validate_all_data();
echo json_encode(array("status" => true));
}
private function _validate_all_data()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = true;
if(empty($POST['reguser']))
{
$data['inputerror'][] = 'reguser'; // input name
$data['error_string'][] = 'Reguser is required'; // message for validation
$data['status'] = false;
}
if($data['status'] === false)
{
echo json_encode($data);
exit();
}
}
A PHP function should return a specific number and stored it to the variable data[i]. How to access a PHP function within a $.getJSON function? I used a PHP CodeIgniter framework. Thank you!
`$.getJSON("<?php echo site_url('some_contoller/some_funcion');?>", function (data) {
for (var i = 0; i < data.length; i++) {
var data[i] = "<?php echo $this->some_PHP_function($with_parameter)?>";
}
}`
This is my PHP function:
public function get_report_pictures($report_id) {
$this->db->select('*');
$this->db->where('report_id', $report_id);
$query = $this->db->get('report');
$data = $query->result();
return $data;
}
in javascript file (*.js) you can't use php code.
you can use $.ajax() to call function in controller .
$.ajax({
type: "post",
url: "some_contoller/some_funcion",
dataType :'json',
success: function(response){
if(response.status=='success'){
response.data.forEach( function (item)
{
var x = item.number;
console.log(x);
});
}
},error:function (jqXHR, textStatus, errorThrown) {
console.log(textStatus);
}
});
in function you mentioned 'some_funcion'
echo json_encode(array(
'status'=>'failed',
'data' => 'number you say ')
);
exit();
it's my solution.i hope so that's worked.
I'v been trying for last 2 hours to pass parameters from my jquery to PHP.
I cannot seem to figure this out.
So my code goes following
var something = getUrlParameter('month');
function Refresh()
{
$.ajax({
type: 'POST',
url: 'getCalendar.php',
data: {test:something},
success: function(data){
if(data != null) $("#calendarDiv").html(data)
}
});
}
getUrlParameter is
function getUrlParameter(sParam)
{
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return sParameterName[1];
}
}
}
I just cant seem to be able to pass anything to my php file.
Thanks.
My goal is to pass ?month=something&year=something into PHP file, so I can based on that display calendar.
Url of example:
http://chanceity.com/calendartest.html
But it doesn't work because my php file is not getting those params.
$.ajax({
type: 'POST',
url: 'getCalendar.php',
cache: false,
dataType:'json',
data: "data=" + {test:something},
success: function(data)
{
$("#calendarDiv").html(data)
},
error:function()
{
$("#calendarDiv").html('Could not get results')
}
});
and next go to your php file get the results and echo the variable back thats it
$value = htmlentities($_GET['data']);
if(!empty($value))
{
$results = 'action you want to do ';
}
else
{
$results = '';
}
echo json_encode($results);
You can also do it with just javascript
function myJavascriptFunction() {
var javascriptVariable = "John";
window.location.href = "myphpfile.php?name=" + javascriptVariable;
}
i am new to cakephp and trying to send data from ajax to my controller action..
i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh
here is my code ..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
my javascript
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
url:"/cakephp/controller/action/",
success : function(data) {
alert(value); //value right now is in this variable ... i want to send this variable value to the controller
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
myController
public function action(){
if( $this->request->is('ajax') ) {
$new = $this->request->data;
echo "ok"
return;
}
}
i want to first get the value here and then send the response to may ajax request
Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
data:{value_to_send:value},
url:"/cakephp/controller/action/",
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
public function action(){
if( $this->request->is('ajax') ) {
// echo $_POST['value_to_send'];
echo $value = $this->request->data('value_to_send');
//or debug($this->request->data);
echo "ok"
die();
}
}
For more see accessing-post-data
I will give you some example. In my case, list out book list as a smart search while typing on text box.
$( ".selectBook" ).each(function(){
$(this).keyup(function( event ) {
var tri = $(this).val();
var oPrnt = $(this).parents('.smartsearch');
var str = '';
if(tri.length > 2){
$.ajax({
type: "POST",
url: "/utility/getbooks/",
data: JSON.stringify({string: tri, activeonly:false}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function(key, val) {
str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
});
oPrnt.find("ul.result").html(str);
},
error: function (errormessage) {
oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
}
});
oPrnt.find("ul.result").slideDown(100);
}
});
});
And in the controller, action (getbooks Action in UtilityController in my case)
public function getbooks($string = '', $activeonly = true){
$this->autoRender = false;
if( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$string = $data->string;
$activeonly = $data->activeonly;
}
$aReturn = array();
// ... fetch books data from DB goes here...
$aResult = $this->Book->fetch('list');
foreach($aResult as $r){
if(isset($r['bookname'])){
$aReturn[$r['id']] = $r['bookname'];
}
}
return json_encode($aReturn);
}