I have an several online application forms built into a (they differ per country) and I need to switch from one to the other with a users button click.
The code I have does this however it also produces a 500 error which breaks any other scripts.
Can anyone give me an idea of what I am doing wrong?
//Update appURL
if (jQuery('button[id="ukApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/uk/uk-application.php";
} else if (jQuery('button[id="itlApp"]').hasClass( "checked" )) {
appURL = "wp-content/plugins/GoMarkets_application/itl/it-application.php";
}
//Get URL path
function getContextPath() {
var ctx = window.location.pathname,
path = '/' !== ctx ? ctx.substring(0, ctx.indexOf('/', 1) + 1) : ctx;
return path + (/\/$/.test(path) ? '' : '/');
}
//Country Application URL
function getOutput() {
jQuery.ajax({
url: getContextPath() + appURL,
complete: function (response) {
jQuery('#output').html(response.responseText);
},
error: function () {
jQuery('#output').html('Bummer: there was an error!');
}
});
return false;
}
here is your ajax function
$.ajax({
url: ajax.url,
...
dataType: "json",
success: function(response) {
$('#myDiv').html(response.html);
},
})
and the php function
function my_ajax_load() {
$post_id = $_POST['post_id'];
ob_start();
include(locate_template('my-template-file.php',false,false));
$page_template = ob_get_contents();
ob_end_clean();
$response['html'] = $page_template;
wp_send_json($response);
}
in your template file you can use your variables declared in the function, in this example you can you $post_id inside the my-template-file.php
For example:
<?php /* Template name: My template */
if($post_id) {
echo get_the_title($post_id);
}
?>
500 error is caused by php error not ajax or jquery, check out your template file for a php errors
There was a missing image being called by the page I was trying to load, the error only showed up in the logs. Thanks all :)
I am new to the world of Kohana/php and am having some issues understanding how to get the result of an ajax request. This request is being called from a click action and is invoking the following method.
function addClickHandlerAjax(marker, l){
google.maps.event.addListener(marker, "click",function(){
console.log(l.facilityId);
removeInfoWindow();
//get content via ajax
$.ajax({
url: 'map/getInfoWindow',
type: 'get',
data: {'facilityID': l.facilityId },
success: function(data, status) {
if(data == "ok") {
console.log('ok');
}
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
}); // end ajax call
});
}
Inside of my controller I have a method
public function action_getInfoWindow(){
if ($this->request->current()->method() === HTTP_Request::GET) {
$data = array(
'facility' => 'derp',
);
// JSON response
$this->auto_render = false;
$this->request->response = json_encode($data);
}
}
I see an HTTP request in fiddler and it passed the correct facilityID parameter. However I am having some disconnect about how to connect all the pieces together.
To send a response to the browser, you should user Controller::response instead of Controller::request::response. So your code should look like this:
public function action_getInfoWindow() {
// retrieve data
$this->response->body(json_encode($data));
}
That should give you some output.
Checkout the Documentation for more detailed info.
Edit
What you could do, to make your life a bit easier, especially if you gonna use ajax requests a lot, is to create an Ajax controller. You can stuff all checks and transforms in it, and never worry about it anymore. An example controller could look like below. Also checkout the Controller_Template which is shipped as an example by Kohana.
class Controller_Ajax extends Controller {
function before() {
if( ! $this->request->is_ajax() ) {
throw Kohana_Exception::factory(500, 'Expecting an Ajax request');
}
}
private $_content;
function content($content = null) {
if( is_null( $content ) ) {
return $this->_content;
}
$this->_content = $content;
}
function after() {
$this->response->body( json_encode( $this->_content ) );
}
}
// example usage
class Controller_Home extends Controller_Ajax {
public function action_getInfoWindow() {
// retrieve the data
$this->content( $data );
}
}
I would like to send data by POST method , which will be send by $.ajax metod on JQuery from formulage. I am trying to send this data to controler writted in PHP. I dont know much about MVC but I have read that controller is responsible for collecting data from user for example by completing formulage.
Here is the code :
`$.ajax({
type: 'POST',
url: 'http://www.somepage.pl/index.php?strona=uzytkownicy',
data: {
login: hLogin_u,
nazwaOddzialu: hNazwaOddzialu,
haslo: hPassword,
nazwa: hNazwa_u,
tylkozip: hTylkoIP,
uprawnienia: myDataCheck
},
timeout: 5000,
cache: false,
success: function(msg){
alert('Zapytanie zakonczylo sie sukcesem! Zwrócone dane to '+msg);
},
beforeSend: function() {
$('#errorDiv').show();
//alert('zaraz wysle sie ajax');
},
error: function(){
$('#errorDiv').html('<p>Przepraszamy wystąpił błąd!</p>').show();
//alert('error nastapil');
}
});
I know that only wrong is URL address but I don't know how to send this data to controller. How is correct url.
For example controller name is controler.php and is in directory /contr/controler.php
How is correct url for this configuration.
Am I doing something incorrect sending this data to controller?
I am giving you the code of controller : Maybe this will help to solve the problem.
class Controller // kontroler
{
// składowe
private $strona;
private $model;
private $widok;
// konstruktor
public function __construct()
{
$this->loadModel();
$this->takeData();
$this->loadView();
$this->runView();
}
// załadowanie odpowiedniego modelu
private function loadModel()
{
if (Autoryzacja::czyZalogowany() == false)
{
$this->strona = "logowanie";
}
else
{
if (!isset($_GET['strona']))
{
$this->strona = "glowna";
}
else
{
$this->strona = Narzedzia::security_get($_GET[strona]);
global $baza;
$baza->execute("SELECT 1 FROM wiadomosci WHERE
wiadomosci.pracownik in (1,8) AND
NOT EXISTS
(SELECT 1 FROM wiadomosci_przeczytania WHERE
wiadomosc=id_wiadomosci AND
pracownik=$_SESSION[zalogowany_id_c9])");
if ($baza->count() > 0)
{
$this->strona = "glowna";
}
}
}
$dane=array("logowanie","glowna","dodajw","kalkulator","hasla","zarzadzaj","edycja","chat"," skan",
"logi","ajax_logi","kalendarz","ajaxkalendarz","uzytkownicy");
if (!in_array($this->strona,$dane))
{
$this->strona = "glowna";
}
$this->model = new $this->strona();
}
// załadowanie danych przez model
private function takeData()
{
$this->model->loadData();
}
// załadowanie odpowiedniego widoku
private function loadView()
{
$w = $this->strona."_widok";
$this->widok = new $w($this->model);
}
// uruchomienie widoku
private function runView()
{
$this->widok->show();
}
}`
How to call a PHP class function from an ajax call
animal.php file
class animal
{
function getName()
{
return "lion";
}
}
Then in my ajax.php file I have an ajax request, need to get values from getName function
How to do that getName() function can I do like this?
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animal/getName",
beforeSend: function() {
},
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
My answer is the same as Surreal Dreams answer, but with the code.
First. Class animal is OK. Leave it like that:
animal.php
<?php
class animal
{
function getName()
{
return "lion";
}
}
Next. Create a new animalHandler.php file.
<?php
require_once 'animal.php';
if(isset( $_POST['invoiceno'] )) {
$myAnimal = new animal();
$result = $myAnimal->getName();
echo $result;
}
Finally. Change your Javascript.
<script type=text/javascript>
$.ajax({
type: "POST",
data: {
invoiceno:jobid
},
url: "animalHandler.php",
dataType: "html",
async: false,
success: function(data) {
result=data;
}
});
</script>
That's is.
You need one additional script, because your animal class can't do anything on its own.
First, in another script file, include animal.php. Then make an object of the animal class - let's call it myAnimal. Then call myAnimal->getName() and echo the results. That will provide the response to your Ajax script.
Use this new script as the target of your Ajax request instead of targeting animal.php.
OOP Currently with php:
ajax.html program(client tier) -> program.php (middle tier) -> class.php (middle tier) -> SQL call or SP (db tier)
OOP Currently with DotNet:
ajax.html program(client tier) -> program.aspx.vb (middle tier) -> class.cls (middle tier) -> SQL call or SP (db tier)
My real-life solution:
Do OOA, do not OOP.
So, I have one file per table -as a class- with their proper ajax calls, and select the respective ajax call with a POST parameter (i.e. mode).
/* mytable.php */
<?
session_start();
header("Content-Type: text/html; charset=iso-8859-1");
$cn=mysql_connect ($_server, $_user, $_pass) or die (mysql_error());
mysql_select_db ($_bd);
mysql_set_charset('utf8');
//add
if($_POST["mode"]=="add") {
$cadena="insert into mytable values(NULL,'".$_POST['txtmytablename']."')";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//modify
if($_POST["mode"]=="modify") {
$cadena="update mytable set name='".$_POST['txtmytablename']."' where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
//erase
if($_POST["mode"]=="erase") {
$cadena="delete from mytable where code='".$_POST['txtmytablecode']."'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
};
// comma delimited file
if($_POST["mode"]=="get") {
$rpta="";
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while($row = mysql_fetch_array($rs)) {
$rowCount = mysql_num_fields($rs);
for ($columna = 0; $columna < $rowCount; $columna++) {
$rpta.=str_replace($row[$columna],",","").",";
}
$rpta.=$row[$columna]."\r\n";
}
echo $rpta;
};
//report
if($_POST["mode"]=="report_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
while ($row=mysql_fetch_array($rs)) {
echo $row['code']." ".$row['name']."<br/>"; // colud be a json, html
};
};
//json
if($_POST["mode"]=="json_a") {
$cadena="select * from mytable where name like '%".$_POST['txtmytablename']."%'";
$rs=mysql_query($cadena,$cn) or die(mysql_error().' : '.$cadena);
$result = array();
while ($row=mysql_fetch_array($rs)) {
array_push($result, array("id"=>$row['code'],"value" => $row['name']));
};
echo json_encode($result);
};
?>
Can you please mention which are you using any Framework?
You method is correct but I want to mention two things over here. First try your URL from the browser and check if its working correctly. Secondly don't use return, in *success: function(data) * data will contain only the output. so use Echo rather then return
For what it is worth, I have used a PHP proxy file that accepts an object as a post -- I will post it here. It works by providing class name, method name, parameters (as an array) and the return type. This is limited as well to only execute classes specified and a limited set of content types to return.
<?php
// =======================================================================
$allowedClasses = array("lnk","objects"); // allowed classes here
// =======================================================================
$raw = file_get_contents("php://input"); // get the complete POST
if($raw) {
$data = json_decode($raw);
if(is_object($data)) {
$class = $data->class; // class: String - the name of the class (filename must = classname) and file must be in the include path
$method = $data->method; // method: String - the name of the function within the class (method)
#$params = $data->params; // params: Array - optional - an array of parameter values in the order the function expects them
#$type = $data->returntype; // returntype: String - optional - return data type, default: json || values can be: json, text, html
// set type to json if not specified
if(!$type) {
$type = "json";
}
// set params to empty array if not specified
if(!$params) {
$params = array();
}
// check that the specified class is in the allowed classes array
if(!in_array($class,$allowedClasses)) {
die("Class " . $class . " is unavailable.");
}
$classFile = $class . ".php";
// check that the classfile exists
if(stream_resolve_include_path($classFile)) {
include $class . ".php";
} else {
die("Class file " . $classFile . " not found.");
}
$v = new $class;
// check that the function exists within the class
if(!method_exists($v, $method)) {
die("Method " . $method . " not found on class " . $class . ".");
}
// execute the function with the provided parameters
$cl = call_user_func_array(array($v,$method), $params );
// return the results with the content type based on the $type parameter
if($type == "json") {
header("Content-Type:application/json");
echo json_encode($cl);
exit();
}
if($type == "html") {
header("Content-Type:text/html");
echo $cl;
exit();
}
if($type == "text") {
header("Content-Type:text/plain");
echo $cl;
exit();
}
}
else {
die("Invalid request.");
exit();
}
} else {
die("Nothing posted");
exit();
}
?>
To call this from jQuery you would then do:
var req = {};
var params = [];
params.push("param1");
params.push("param2");
req.class="MyClassName";
req.method = "MyMethodName";
req.params = params;
var request = $.ajax({
url: "proxy.php",
type: "POST",
data: JSON.stringify(req),
processData: false,
dataType: "json"
});
Try this:
Updated Ajax:
$("#submit").on('click', (function(e){
var postURL = "../Controller/Controller.php?action=create";
$.ajax({
type: "POST",
url: postURL,
data: $('form#data-form').serialize(),
success: function(data){
//
}
});
e.preventDefault();
});
Update Contoller:
<?php
require_once "../Model/Model.php";
require_once "../View/CRUD.php";
class Controller
{
function create(){
$nama = $_POST["nama"];
$msisdn = $_POST["msisdn"];
$sms = $_POST["sms"];
insertData($nama, $msisdn, $sms);
}
}
if(!empty($_POST) && isset($_GET['action']) && $_GET['action'] == ''create) {
$object = new Controller();
$object->create();
}
?>
For every ajax request add two data, one is class name and other is function name
create php page as follows
<?php
require_once 'siteController.php';
if(isset($_POST['class']))
{
$function = $_POST['function'];
$className = $_POST['class'];
// echo $function;
$class = new $className();
$result = $class->$function();
if(is_array($result))
{
print_r($result);
}
elseif(is_string($result ) && is_array(json_decode($result , true)))
{
print_r(json_decode($string, true));
}
else
{
echo $result;
}
}
?>
Ajax request is follows
$.ajax({
url: './controller/phpProcess.php',
type: 'POST',
data: {class: 'siteController',function:'clientLogin'},
success:function(data){
alert(data);
}
});
Class is follows
class siteController
{
function clientLogin()
{
return "lion";
}
}
I think that woud be a sleek workaround to call a static PHP method via AJAX which will also work in larger applications:
ajax_handler.php
<?php
// Include the class you want to call a method from
echo (new ReflectionMethod($_POST["className"], $_POST["methodName"]))->invoke(null, $_POST["parameters"] ? $_POST["parameters"] : null);
some.js
function callPhpMethod(className, methodName, successCallback, parameters = [ ]) {
$.ajax({
type: 'POST',
url: 'ajax_handler.php',
data: {
className: className,
methodName: methodName,
parameters: parameters
},
success: successCallback,
error: xhr => console.error(xhr.responseText)
});
}
Greetings ^^
I have made what is essentially a lightbox whereby if a change requires the user to confirm their password, this lightbox pops up and the user enters there password etc.
I am triggering the function like this:
if(verifyPassword())
{
//apply change
}
The verify function is:
function verifyPassword() {
$('#confirmpasswordoverlay').fadeIn(300);
$('#submit').click(function() {
$.post('', { password: $('input[name=password]').val() },
function(check) {
if(check.error)
{
if(check.password)
{
//show password error
return false;
}
else
{
//show error
return false;
}
}
else
{
return true;
}
}, 'json');
});
}
Basically I am needing the function to wait until #submit is clicked to return either true or false.
Thanks in advance
Since jQuery 1.5.0, you can do apply some magic with Deferred objects:
$.when( verifyPassword() ).done(function() {
// do something
});
You would need to re-write verifyPassword() a little:
function verifyPassword() {
var Notify = $.Deferred();
$('#confirmpasswordoverlay').fadeIn(300);
$('#submit').click(function() {
$.post('', { password: $('input[name=password]').val() },
function(check) {
if(check.error) {
if(check.password) {
//show password error
Notify.resolve();
}
else {
//show error
Notify.reject();
}
}
else {
return true;
}
}, 'json');
});
return Notify.promise();
}
This might not be the most elegant way of achieving your goal here, I'm just saying you could do it in a way like this :-)
Don't stall, instead provide a callback:
function verifyPassword(f) {
/**
* Do all your logic here, then callback to the passed function
*/
f(result);
}
verifyPassword(function (correct) {
if (correct) {
/* Continue */
}
else { /* Other */ }
});
I think you want to convert your $.post() call into the more generic $.ajax() jQuery call, and pass in async: false. Something like:
$.ajax('', { async:false, data: {password:...}, success: function() {
// ... success callback ...
}});