cant post value using ajax in zend framework 2 - javascript

I'm using ajax to post a value as given below,
but data I post wont reach the controllers ajaxAaction
view script (which is a tpl file)
<input type="text" id='taska'>
<button id='submitTo'>button</button>
script
$(document).ready(
function(){
//controller via ajax
$("#submitTo").click(function() {
var message = $('#taska').val();
if (message != '') {
//run ajax
//alert ('not empty');
$.post('index/ajax',
{'message' : message},
//callback function
function (respond) {
//put respond in class show-msg
$(".show-msg").html(respond);
}
);
}
});
and the action
public function ajaxAction() {
//get post request (standart approach)
$request = $this->getRequest()->getPost();
//referring to the index
//gets value from ajax request
$message = $request['message'];
// makes disable renderer
$this->_helper->viewRenderer->setNoRender();
//makes disable layout
$this->_helper->getHelper('layout')->disableLayout();
//return callback message to the function javascript
echo $message;
}
} );
$.post('index/ajax', is the part where I think the error is.
Am I defining the controller and action in the wrong way?
I've been stuck here for a while.
please help

try it with $this->basePath() in <?php echo $this->basePath();?>index/ajax

Solved it by prefixing the rootPath as below
if (message != '') {
//run ajax rootPath
{/literal} $.post("{eval var=$rootPath}/index/ajax", {literal}
{'message' : message},
//callback function
function (respond) {

Related

Ajax call not working properly when used with Recaptcha

I am using PHP and AJAX together in my website to fetch data from a JSON URL and to display it on the webpage. When I use it without implementing recaptcha, it works fine but when I integrate Google's Recaptcha, the results get displayed only when the captcha puzzle is solved twice everytime. I am not sure where the bug actually lies and I even tried to implement a custom captcha and in that case also it is the same. Here is the code with recaptcha,
Captcha and Ajax code snippet :
<?php
if ($resp != null && $resp->success): ?>
echo"hi";
<script>
$(document).ready(function(){
$("#submit").click(function(){
$.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(), function(response) {
$("#success").html(response);
});
return false;
});
});
</script>
<?php
else:
echo "Failed";
?>
Full code :
http://pastebin.com/UynEiYng
This part should be moved to retrieve_train_between_stations.php.
require_once "recaptchalib.php";
// your secret key
$secret = "My secret key";
// check secret key
$reCaptcha = new ReCaptcha($secret);
$resp = false;
if (isset($_POST["g-recaptcha-response"])) {
$resp = $reCaptcha->verifyResponse(
$_SERVER["REMOTE_ADDR"],
$_POST["g-recaptcha-response"]
);
}
if ($resp) {
//display the record
} else {
echo 'Recaptcha can not be verified.';
}
The if/else should be removed and prevent the default event for the script
<script>
$(document).ready(function(){
$("#submit").click(function(event){
event.preventDefault();
$.post("retrieve_train_between_stations.php", $("#get_train_running").serialize(), function(response) {
$("#success").html(response);
});
return false;
});
});
</script>

Secure ajax GET/POST request for server

suppose I work with some kind of API and my file server.php handles the connection to the API service. on my client side I use AJAX call like this:
$http({
url : 'server/server.php',
method : 'GET',
data : { getContent : true }
});
in my server.php I handle it like this:
if(isset($_GET['getContent'])){
$content = get_content();
}
function get_content(){...}
i just wonder what prevents any one send AJAX call with the same getContent parameter and get all my data? how can i secure it and make sure only calls from my application will get the relevant data back?
thank you!
I guess you are concerned about CSRF attacks. Read more about this here: https://www.owasp.org/index.php/Cross-Site_Request_Forgery_%28CSRF%29_Prevention_Cheat_Sheet
One of the mostly used option to secure your request will be:
- Generate a token and send it with the request for a session. This token can be identified by your WebServer as originating from a specific client for a specific session
2022 Update
This is a 7 year old post and the link in the link-only "accepted" answer is broken.
So, I'm going to offer a basic walkthrough and a complete model.
Remember, the $_SESSION will be preserved even in the AJAX handler, if it's all from the same domain. So, you can use that to check things.
Use $_POST
I presume you're using $_POST and not $_GET since you're concerned about security. If not, then much of this might not be important anyway.
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$post_method = true;
}
Ensure the $_SERVER['HTTP_REFERER'] is from your own site
if ( (!empty($_SERVER['HTTP_REFERER']))
&& ($_SERVER['HTTP_REFERER'] === "https://example.tld/my_sending_page.php") ) {
$from_my_server = true;
}
If you're not sure what this should be, run a test on your own server to see what this should be:
echo $_SERVER['HTTP_REFERER'];
Verify XMLHTTP/AJAX request via $_SERVER array
if ( (!empty($_SERVER['HTTP_X_REQUESTED_WITH']))
&& ( strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') ) {
$ajax = true;
} else {
$ajax = false;
}
Use a token
This is the hard part, but not too hard.
Create the token
Set the token in $_SESSION
Put the token in the AJAX header
AJAX responder: confirm the AJAX header token with the $_SESSION token
send_from_me.php
// Create the token
//$token = md5(rand(10000,99999)); // Not recommended, but possible
$token = bin2hex(random_bytes(64));
// Store in SESSION
$_SESSION["token"] = $token;
// Assuming your AJAX is this
const AJAX = new XMLHttpRequest();
// This goes inside your AJAX function somewhere before AJAX.send
//
AJAX.setRequestHeader("ajax-token", "<?php echo $_SESSION["token"]; ?>");
//
// That creates $_SERVER['HTTP_AJAX_TOKEN'] which we can use later
ajax_responder.php
session_start(); // Must have
if ($_SERVER['HTTP_AJAX_TOKEN'] === $_SESSION["token"]) {
$token_match = true;
} else {
echo "No script kiddies!";
exit();
}
// Now it's safe for your AJAX responder to proceed
Let's put all of this into a working example
sending_from.php
<?php
session_start();
$token = bin2hex(random_bytes(64));
$_SESSION["token"] = $token;
?>
<!DOCTYPE html>
<html>
<head>
<title>My AJAX Sender</title>
</head>
<body>
<script>
function ajaxFormData(formID, postTo, ajaxUpdate) {
// Bind a new event listener every time the <form> is changed:
const FORM = document.getElementById(formID); // <form> by ID
const FD = new FormData(FORM); // Bind to-send data to form element
const AJAX = new XMLHttpRequest(); // AJAX handler
// This runs when AJAX responds
AJAX.addEventListener( "load", function(event) {
document.getElementById(ajaxUpdate).innerHTML = event.target.responseText;
} );
// This runs if AJAX fails
AJAX.addEventListener( "error", function(event) {
document.getElementById(ajaxUpdate).innerHTML = 'Oops! Something went wrong.';
} );
// Add your token header
AJAX.setRequestHeader("ajax-token", "<?php echo $_SESSION["token"]; ?>");
// Open the POST connection
AJAX.open("POST", postTo);
// Data sent is from the form
AJAX.send(FD);
}
</script>
<div id="ajax_changes">Replace me with AJAX</div>
<form id="ajaxForm">
<input type="text" name="the_simple_response">
<button type="button" onclick="ajaxFormData('ajaxForm', 'ajax_responder.php', 'ajax_changes');">Send my Secure AJAX</button>
</form>
</body>
</html>
ajaxcheck.inc.php
<?php
$mysite = 'https://example.tld';
// All in one test
if (($_SERVER['REQUEST_METHOD'] == 'POST')
&& ((!empty($_SERVER['HTTP_REFERER'])) && ($_SERVER['HTTP_REFERER'] === "$mysite/my_sending_page.php"))
&& ((!empty($_SERVER['HTTP_X_REQUESTED_WITH'])) && ( strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'))
&& ($_SERVER['HTTP_AJAX_TOKEN'] === $_SESSION["token"])) {
$ajax_legit = true;
} else {
echo "No script kiddies!";
exit();
}
?>
ajax_responder.php
<?php
session_start();
// Do all that checking we're learning about by neatly including the file above
require_once('ajaxcheck.inc.php');
// Process your AJAX
echo $_POST['the_simple_response'];
?>
i just wonder what prevents any one send AJAX call with the same getContent parameter and get all my data?
Nothing. This URL is public thus anyone can make requests to it.
how can i secure it and make sure only calls from my application will get the relevant data back?
You can pass additional data (for example, some hashed value) that is verified on the server side.
$http({
url : 'server/server.php',
method : 'GET',
data : { getContent : true, hash : '0800fc577294c34e0b28ad2839435945' }
});
and
if(isset($_GET['getContent']))
{
if(isset($_GET['hash']) && validateHash($_GET['hash']))
{
$content = get_content();
}
}
function get_content(){...}
i just wonder what prevents any one send AJAX call with the same getContent parameter and get all my data?
The same way you would protect the data in any other request (e.g. with user authentication). There's nothing special about Ajax in regards to HTTP as far as the server is concerned.
how can i secure it and make sure only calls from my application will get the relevant data back?
You can't. The user can always inspect what their browser is asking the server for and replicate it.
Generally, people authenticate users rather than applications.

Combination JQuery and PHP

I'm making a project with the slides of text.
I have in the page a main div that contain the text of each slide.
I saved the content in a database.
I want do this operation:
When I click the arrow for view the next slide, PHP catch from database the content and save it in a variable.
Then with JQuery, I replace the maindiv's content with variable.
It is possible? If not, How can I do it?
Use a ajax request to simulate a post request, and parse the information with php. You will end up with someting like this:
<?php
if( isset( $_POST["slide"] ) {
// Database stuff
// Echo back
echo "Information that you need to get in jQuery";
}
?>
<script>
$("button.next_slide").click(function(){
var ajax;
if (window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
} else {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax.onreadystatechange = function() {
if (ajax.readyState==4 && ajax.status==200) {
document.getElementById("some_element").innerHTML = ajax.responseText;
}
}
ajax.open("POST","this_page.php?slide=1&foo=bar&bar=foo",true);
ajax.send();
});
</script>
<button class="next_slide">Next slide</button>
<div id="some_element"></div>
Note: This could be done without jQuery, or with jQuery's $.ajax method. Read more here: http://api.jquery.com/jquery.ajax/
In my understanding, you want to load some data when user click on a particular button and then load it into a div we can achieve it via jQuery ajax and PHP.
HTML
<div class="main_div">
<ul id="list"><!-- Our content will load here --></ul>
Next
</div>
jQuery
jQuery(document).ready(function($){
$('.call_ajax').on('click', function(e){
e.preventDefault();
$.post('ajax.php', { get_slide: true }, function(response){
// We are telling jQuery to parse response as json because in ajax.php we have used json_encode function.
var data = jQuery.parseJSON(response);
$("#list").append('<li>' + data['slide'] + '</li>');
});
})
})
PHP ajax.php
if(isset($_POST['get_slide'])){
//Get slide from db and output it as json, but currently for example purpose we assume that we have a array.
$data['slide'] = 'Your slide text';
echo json_encode($data); die(); // We have used die because we don't won't our script to run any more.
}
I've not tested it, but it will work.

Why the success alert message is appearing many times in an AJAX call made to a PHP script in following scenario?

Following are two code blocks, each one is responsible for AJAX call to a PHP file onclick of respective hyperlink:
<script language="javascript" type="text/javascript">
$(".fixed").click(function(e) {
var action_url1 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$(".fixed").colorbox({inline:true, width:666});
$("#fixedPop_url").click(function(event) {
event.preventDefault();
$.get(action_url1, function(data) {
alert("Question status updated successfully");
$("#fix_"+qid).hide();
$("#notfix_"+qid).show();
});
});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});
$(".notfixed").click(function(e) {
var action_url2 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$(".notfixed").colorbox({inline:true, width:666});
$("#notfixedPop_url").click(function(event) {
event.preventDefault();
$.get(action_url2, function(data) {
alert("Question status updated successfully");
$("#notfix_"+qid).hide();
$("#fix_"+qid).show();
});
});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});
</script>
Now the PHP code snippet from a file is written below to which the AJAX request is made. Actually, the PHP file name to which the AJAX request is going and the parameters passed required are contained in variables action_url1 and action_url1. These are working fine. Until now there is no issue for me. Also the PHP code is working fine.
<?php
$objQuestionIssue = new QuestionIssue;
$op = $_GET['op'];
switch( $op ) {
case "fixed":
$que_issue_data = $objQuestionIssue->UpdateQuestionIssueStatus($question_id, $op);
die();
break;
case "notfixed":
$que_issue_data = $objQuestionIssue->UpdateQuestionIssueStatus($question_id, $op);
die();
break;
}
?>
But the issue I'm facing is getting the alert success message multiple times. It is expected to show the alert message only once but in current scenario it's showing multiple times. Can anyone hep me in correcting this issue please?
You have nested click handlers -
Every time you click on .fixed you are binding a new click handler on #fixedPop_url. And that is why your .get is executing multiple times
you can use .off() to fix this -
$("#fixedPop_url").off('click').on('click',function(event) {

running a php function inside javascript code [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I hope to run a php code inside a javascript code too and I do like that :
<?php function categoryChecking(){
return false;
}?>
....
function openPlayer(songname, folder)
{
if(<?php echo categoryChecking() ?> == true)
{
if (folder != '')
{
folderURL = "/"+folder;
}else
{
folderURL = '';
}
var url = "/users/player/"+songname+folderURL;
window.open(url,'mywin','left=20,top=20,width=800,height=440');
}else{
alerte('you should click on a subcategory first');
}
}
....
<a href='javascript:void();' onClick="openPlayer('<?php echo $pendingSong['id']; ?>','')">
finally I get this error instead the alert message "you should click on a subcategory first"
ReferenceError: openPlayer is not defined
openPlayer('265','')
You're reduced your test case too far to see for sure what the problem is, but given the error message you are receiving, your immediate problem has nothing to do with PHP.
You haven't defined openPlayer in scope for the onclick attribute where you call it. Presumably, the earlier JS code is either not inside a script element at all or is wrapped inside a function which will scope it and prevent it from being a global.
Update: #h2ooooooo points out, in a comment, that your PHP is generating the JS:
if( == true)
Check your browser's error console. You need to deal with the first error messages first since they can have knock on effects. In this case the parse error in the script will cause the function to not be defined.
Once you resolve that, however, it looks like you will encounter problems with trying to write bi-directional code where some is client side and some is server side.
You cannot run PHP code from JavaScript, because PHP is a server-side language (which runs on the server) and JavaScript is a client-side language (which runs in your browser).
You need to use AJAX to send a HTTP request to the PHP page, and then your PHP page should give a response. The easiest way to send a HTTP request using AJAX, is using the jQuery ajax() method.
Create a PHP file ajax.php, and put this code in it:
<?php
$value = false; // perform category check
echo $value ? 'true' : 'false';
?>
Then, at your JavaScript code, you should first add a reference to jQuery:
<script type="text/javascript" src="jquery.js"></script>
Then, use this AJAX code to get the value of the bool:
<script type="text/javascript">
$.ajax('ajax.php')
.done(function(data) {
var boolValue = data == 'true'; // converts the string to a bool
})
.fail(function() {
// failed
});
</script>
So, your code should look like this:
function openPlayer(songname, folder) {
$.ajax('ajax.php')
.done(function (data) {
var boolValue = data == 'true'; // converts the string to a bool
if (boolValue) {
if (folder != '') {
folderURL = "/" + folder;
} else {
folderURL = '';
}
var url = "/users/player/" + songname + folderURL;
window.open(url, 'mywin', 'left=20,top=20,width=800,height=440');
} else {
alert('you should click on a subcategory first');
}
})
.fail(function () {
// failed
});
}

Categories