I have this code in my view file (searchV.php):
<html>
<head>
<title>Search Domains</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
function noTextVal(){
$("#domaintxt").val("");
}
function searchDom(){
var searchTxt = $("#searchTxt").val();
var sUrl = $("#url").val();
$.ajax({
url : sUrl + "/searchC",
type : "POST",
dataType : "json",
data : { action : "searchDomain", searchTxt : searchTxt },
success : function(dataresponse){
if(dataresponse == "found"){
alert("found");
}
else{
alert("none");
}
}
});
}
</script>
</head>
<body>
<form id="searchForm">
<input type="text" id="searchTxt" name="searchTxt" onclick="noTextVal()" >
<input type="submit" id="searchBtn" name="searchBtn" value="Search" onclick="searchDom()" />
<input type="hidden" id="url" name="url" value="<?php echo site_url(); ?>" />
</form>
<?php
var_dump($domains);
if($domains!= NULL){
foreach ($domains->result_array() as $row){
echo $row['domain'] . " " . $row['phrase1'];
echo "<br/>";
}
}
?>
</body>
</html>
and below is my controller (searchC.php):
<?php
class SearchC extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->model('searchM');
}
public function index()
{
$data['domains'] = $this->searchM->getDomains();
$this->load->view('pages/searchV', $data);
switch(#$_POST['action']){
case "searchDomain":
echo "test";
$this->searchDomains($_POST['searchTxt']);
break;
default:
echo "test2";
echo "<br/>action:" . ($_POST['action']);
echo "<br/>text:" . $_POST['searchTxt'];
}
}
public function searchDomains($searchInput)
{
$data['domains'] = $this->searchM->getDomains($searchInput);
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo json_encode($res);
}
} //end of class SearchC
?>
Now I've done a test on the controller using switch to check if the json data passed was successful but it's always showing undefined.. What's wrong here? Can someone explain why the data is not recognized in the controller??
You aren't passing the data in via the url, so you need to use $this->input->post() to retrieve the data.
For example,
public function searchDomains()
{
$data['domains'] = $this->searchM->getDomains($this->input->post('searchTxt'));
$res = "";
if($data['domains']!=NULL){ $res = "found"; }
else{ $res = "none"; }
echo $res;
}
I believe that the data is being correctly returned, but the problem is with your code check. The $.ajax function parses the JSON and transforms it into a JavaScript object. Therefore you would need to modify your code as follows:
if(dataresponse.res == "found"){ // Changed from dataresponse to dataresponse.res
alert("found");
}
else{
alert("none");
}
This should work for you.
Related
Recaptcha form is like this:
<script type="text/javascript">
var RecaptchaOptions = {"theme":"red","lang":"en"};
</script><script type="text/javascript" src="https://www.google.com/recaptcha/api/challenge?k=6LeThAsTAAAAAKYRjSpA8XZ1s4izK65hYr9ulCiD">
</script><noscript>
<iframe src="https://www.google.com/recaptcha/api/noscript?k=6LeThAsTAAAAAKYRjSpA8XZ1s4izK65hYr9ulCiD"
height="300" width="500" frameborder="0"> </iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="recaptcha_response_field"
value="manual_challenge">
</noscript>
and validator of ZF2 for ReCaptcha is like this:
$recaptcha = new ZendService\ReCaptcha\ReCaptcha(PUB_KEY, PRIV_KEY);
$html = $recaptcha->getHTML();
$result = $recaptcha->verify($_POST['recaptcha_challenge_field'], $_POST['recaptcha_response_field']);
if (!$result->isValid()) {
// invalid
} else {
// valid
}
is it possible to validate it remotely like this: https://jqueryvalidation.org/remote-method
I tried below in remote php file and it doesn't work:
$recaptcha = new ZendService\ReCaptcha\ReCaptcha(PUB_KEY, PRIV_KEY);
$result = $recaptcha->verify($_GET['recaptcha_challenge_field'], $_GET['recaptcha_response_field']);
if (!$result->isValid()) {
echo json_encode(false);
} else {
echo json_encode(true);
}
and js itself is:
$().ready(function() {
$("#contact").validate({
rules: {
recaptcha_response_field: {
required: true,
remote: "json.php"
}
}
});
});
is it possible at all or I did something wrong?
try this function to validate recaptcha
var grecaptchaId;
var onloadCallback = function () {
grecaptchaId = grecaptcha.render('grecaptcha', {
'sitekey': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'callback': function (response) {
$("#grecaptcha_error").text('');
}
});
};
function ValidateRecaptcha() {
var x;
x = grecaptcha.getResponse(grecaptchaId);
if (x != "") {
$("#grecaptcha_error").text('');
return true;
}
else {
$("#grecaptcha_error").text('The captcha is required and can\'t be empty');
return false;
}
}
I want to get data from php array and show it on same page. how to
import data from php array by using search box. This code not working properly.
What is th error of this code?
foodstore.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlHttp;
if(window.ActiveXObject){
try{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){
xmlHttp = false;
}
} else{
try{
xmlHttp = new XMLHttpRequest();
}catch(e){
xmlHttp = false;
}
}
if(!xmlHttp)
alert("cant create that object hoss!");
else
return xmlHttp;
}
function process(){
if(xmlHttp.readyState==0|| xmlHttp.readyState==4){
food = encodeURIComponent(document.getElementById("userInput").value);
xmlHttp.open("GET","foodstore.php?food="+food,true);
xmlHttp.onreadystatechange = handleServerResponse;
xmlHttp.send(null);
}else{
setTimeout('process()',1000);
}
}
function handleServerResponse(){
if(xmlHttp.readyState==4){
if(xmlHttp.status==200){
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML ='<span style="color:blue">'+message+'</span>';
setTimeout('process',1000);
}else{
alert('Something went wrong!');
}
}
}
foodstore.php
<?php
header('Content-Type: text/xml');
echo '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>';
echo '<response>';
$food = $_GET['food'];
$foodArray = array('tuna','bacon','beef','loaf','ham');
if(in_array($food,$foodArray))
echo 'We do have '.$food'!';
elseif($food =='')
echo 'Enter a food you want to buy';
else
echo 'Sorry we don't sell it '.$food'!';
echo '</response>';
?>
Index.html
<html><head>
<script type="text/javascript" src="foodstore.js"></script>
</head>
<body onload="process()">
<h3>The foods </h3>
Order your foods:
<input type="text" id="Userinput"></input>
<div id="underInput"></div>
</body>
</html>
How to show array data by searching from search box
I have changed the code using jquery its simple . You can try it.
index.html
<html>
<head>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script>
$(function()
{
$("#Userinput").keyup(function()
{
process();
});
$("#Userinput").keydown(function()
{
process();
});
$("#Userinput").focus(function()
{
process();
});
$("#Userinput").change(function()
{
process();
});
});
function process() {
var input_food = $("#Userinput").val();
$.ajax({
type: "GET",
url: "foodstore.php",
data: {food: input_food},
success: function(message)
{
$("#underInput").html('<span style="color:blue">' + message + '</span>');
},
error: function()
{
$("#underInput").html('<span style="color:red">Some error occured</span>');
}
});
}
</script>
</head>
<body >
<h3>The foods </h3>
Order your foods:
<input type="text" id="Userinput" ></input>
<div id="underInput"></div>
</body>
</html>
foodstore.php
<?php
if (!empty($_GET['food']))
{
$food = $_GET['food'];
$foodArray = array('tuna', 'bacon', 'beef', 'loaf', 'ham');
if (in_array($food, $foodArray))
echo "We do have " . $food . "!";
elseif ($food == '')
echo "Enter a food you want to buy";
else
echo "Sorry we don't sell it " . $food . "!";
}
else
{
echo "Enter a food you want to buy";
}
?>
I think its simple if you know jquery .And there was a simple error in php you did't escape the extra single quotes in (don't) so I used double quotes for echo statements. Copy paste and tell if this is it what you want or not.Got any doubt ask.
I am trying to submit a form without leaving the page using json.
However, the method below ignores the data I have entered into the CKEditor.
Any ideas (and feel free to correct my terminology)?
<script type="text/javascript">
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});
</script>
<form name="addStory" action="" method="post" id="addStory">
<label for="story_story">Story: </label><textarea id="story_story" name="story_story"><p></p></textarea>
<?php
// Include the CKEditor class.
include("ckeditor/ckeditor.php");
// Create a class instance.
$CKEditor = new CKEditor();
$CKEditor->basePath = '/ckeditor/'
$CKEditor->replace("story_story");
?>
<input type="submit" value="Submit" />
</form>
_posteddata.php:
include 'connection.php';
function check_input($value, $quoteIt)
{
// Stripslashes
if (get_magic_quotes_gpc())
{
$value = stripslashes($value);
}
// Quote if not a number
if (is_null($value) || $value=="") {
$value = 'NULL';
} else if (!is_numeric($value) && $quoteIt == 1) {
$value = "'" . mysql_real_escape_string($value) . "'";
}
return $value;
}
// CKEDITOR STUFF FOR STORY_STORY
if (isset($_POST)) {
$postArray = &$_POST;
}
foreach ( $postArray as $sForm => $value )
{
if($sForm == "story_story") {
$story_story = check_input($value, 1);
}
}
$query = "INSERT INTO story_table (story) VALUES ($story_story)";
mysql_query($query) or die(mysql_error() . $query);
$return = array();
$return['adminList'] = "New story added with ID: " . mysql_insert_id();
header('application/json');
echo json_encode($return);
mysql_close();
In this kind of situation you must force CKEditor to update the contents of the textarea
So your function would be something like this:
$(document).ready( function() {
$("#addStory input[type=submit]").click(function(e) {
e.preventDefault();
CKEDITOR.instances.story_story.updateElement(); // Update the textarea
$.post('_posteddata.php', $("#addStory").serialize(), function(result) {
alert(result.adminList);
}, "json");
});
});
I have another question:
Ajax Forms are working well. Most of them need to do mysql stuff and only return values if the entry could be written or not. I used just echo statements. For example echo "1"; if the values could be written and echo "2"; if the values could not be written.
Now I need to call back 3 variables. I know that I can write them in an array. My problem is just, that I can't return this variable into my visible site.
This is my JavaScript Code:
//Show statistic
$('.statistic_submit').click(function(){
if ($('#month').val() == 'none' || $('#year').val() == 'none') {
$("#dialog_empty").dialog( "open" );
return false;
}
var form = $('#statistic_view');
var data = form.serialize();
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
success: function (reqCode) {
if (reqCode == 1) {
//Show generated table
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
if (reqCode == 2) {
//No values found
$('.done').fadeOut('slow');
$("#dialog_error").dialog( "open" );
}
}
});
return false;
});
This is my html code:
<div>
<form id="statistic_view" action="include/scripts/user_statistic.php" method="post">
<select name="month" id="month">
<option value="none" class="bold italic">Monat</option>
<?php
for($i=1; $i<=12; $i++){
if($i == $month)
echo "<option value=\"".$i."\" selected>".$month_name[$i]."</option>\n";
else
echo "<option value=\"".$i."\">".$month_name[$i]."</option>\n";
}
?>
</select>
<select name="year" id="year">
<option value="none" class="bold italic">Jahr</option>
<?php
for($i=2012; $i<=$year; $i++){
if($i == $year)
echo "<option value=\"".$i."\" selected>".$i."</option>\n";
else
echo "<option value=\"".$i."\">".$i."</option>\n";
}
?>
</select>
<br/><br/>
<div id="user_statistic">
<input type="submit" id="small" class="statistic_submit" value="Daten anzeigen">
</div>
</form>
<br />
<div class="done">
<p class="bold center"><?php echo "Besucher ".$month_name[$month]." ".$year; ?></p>
<canvas id="cvs" width="680" height="250">[No canvas support]</canvas>
<script>
chart = new RGraph.Line('cvs', <?php print($data_string) ?>);
chart.Set('chart.tooltips', <?php print($labels_tooltip) ?>);
chart.Set('chart.tooltips.effect', 'expand');
chart.Set('chart.background.grid.autofit', true);
chart.Set('chart.gutter.left', 35);
chart.Set('chart.gutter.right', 5);
chart.Set('chart.hmargin', 10);
chart.Set('chart.tickmarks', 'circle');
chart.Set('chart.labels', <?php print($labels_string) ?>);
chart.Draw();
</script>
</div>
</div>
And this my user_statistic.php:
... (mysql stuff)
/******************************/
/** Create diagram
/******************************/
$labels = array();
$data = array();
for ($j=1; $j<=$days; $j++) {
$labels[$j] =$j;
$data[$j] = $day_value[$j];
}
// Aggregate all the data into one string
$data_string = "[" . join(", ", $data) . "]";
$labels_string = "['" . join("', '", $labels) . "']";
$labels_tooltip = "['" . join("', '", $data) . "']";
//data written
echo "1";
So echo "1"; tells my script that everything is fine. But now I need $data_string, $labels_string and $labels_tooltip. So how can I return these values from user_statistic.php into my side?
Avoid converting arrays to strings on your own. If you need to pass a PHP array back to your jQuery, you should do so with the json_encode function:
echo json_encode( $array );
This will come through as a JSON object which you can then handle client-side. Your JSON string will be returned into the callback of your $.ajax method:
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
dataType: 'json',
success: function ( response ) {
/* response is your array, in JSON form */
}
});
For instance, if our PHP script did the following:
$response = array(
'message' => 'Success',
'allData' => array( 'Jonathan', 'Mariah', 'Samuel', 'Sally' )
);
echo json_encode( $response );
We could alert the message from our jQuery like this:
success: function ( response ) {
alert( response.message );
}
The best approach here would be to return a json object. Create an array on server side -
$response['error_code'] = '1'; //everything ok. 0 if not ok
$response['data_string'] = 'this will have some data';
$response['labels_string'] = 'labels';
$response['labels_tooltip' = 'here goes the tooltips';
echo json_encode($response);
and in your javascript code, mention the return datatype as json -
$.ajax({
url: "include/scripts/user_statistic.php",
type: "POST",
data: data,
dataType: json,
success: function (reqCode) {
if (reqCode.error_code == 1) {
alert('this is the data string '+resCode.data_string);
//Show generated table
$('.done').fadeOut('slow');
$('.done').fadeIn('slow');
}
if (reqCode.error_code == 2) {
//No values found
$('.done').fadeOut('slow');
$("#dialog_error").dialog( "open" );
}
}
});
I have a problem with dynamic loading of javascript function from Ajax.
I want to update some part of HTML with Ajax. Let's say I want to place a button and to attach a javascript function to that button dynamically.
For example:
...
<head>
<script src="ajax.js" type="text/javascript"></script>
<script type="text/javascript">
function f_OnLoadMain()
{
fParseBrowserInfo();
getJSFromServer();
getHTMLFromServer();
}
</script>
</head>
<body onload="f_OnLoadMain()">
<div id="AjaxArea" width="100%" height="100%" align="left" valign="top" >
<!-- Updated with ajax -->
</div>
</body>
</html>
----- getJSFromServer() - calls to php code:
<?php
$somesource = '
function Clicked(){
alert("Clicked");
}
';
class TestObject{
public $source = "";
function TestObject()
{
$this->source = "";
}
function setSource($source){
$this->source = $source;
}
}
$ti = new TestObject();
$ti->setSource($somesource);
echo(json_encode($ti));
?>
the script is inserted with:
var oHead = document.getElementsByTagName('HEAD').item(0);
if (oScript){
oHead.removeChild(oScript);
}
oScript = document.createElement("SCRIPT");
oScript.type = 'text/javascript';
oScript.text = oScript.source;
oHead.appendChild( oScript);
And getHTMLFromServer() - call php :
<?php
$error = 0;
$someText = '
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
';
class TestObject{
public $src = "";
public $error = 0;
function TestObject()
{
$this->error = 0;
$this->src = "";
}
function setSrcString($sample){
$this->src = $sample;
}
}
$ti = new TestObject();
$ti->error = $error;
$ti->setSrcString($someText);
echo(json_encode($ti));
?>
Then the content is updated with:
var dynamicArea = document.getElementById("AjaxArea");
if(dynamicArea != null)
{
dynamicArea.innerHTML = obj.src;
}
And that works fine!
So, when the page loads the button is displayed ok, BUT pressing button doesn't call function Clicked().
Someone knows how to fix it?
Regards!
i guess you have to escape your apostrophe:
<input type="button" id="SomeBtn" name="SomeBtn" onclick="Clicked()" value="SomeBtn">
you see: onclick="Clicked()"
Together with: function Clicked(){ alert("Clicked"); }
It renders to: onclick="alert("clicked")"
Try to escape your apostrophe :)
Regards