Codeigniter AJAX JQuery csrf_protection star rating script - javascript

I am using the star rating script here but I am using with Codeigniter with CSRF_PROTECTION turned on. I am receiving 500 Internal Server Error when I click on the stars and the script is called. I found a few similar post here but none that helped me solve my issue.
I tried one fix which I found online that stated to create ajaxSetup (see below) function first to merge the "data" with the data in my function to send the token.
I do not know JavaScript so it is taking me days to figure out the issue. The ajaxSetup is not working. If I turn CRSF_PROTECTION off, the script works.
Help! Please, I am struck on this and want to get it to work because there are other Jquery scripts that I would like to use.
$.ajaxSetup({
data: { <?php echo $this->config->item('csrf_token_name'); ?>:
$.cookie('<?php echo $this->config->item('csrf_cookie_name'); ?>')
}
});
Here is all of the Java script.
<script type="text/javascript">
$.ajaxSetup({
data: {
<?php echo $this->config->item('csrf_token_name'); ?>: $.cookie('<?php echo $this->config->item('csrf_cookie_name'); ?>')
}
});
$(function() {
$("#rating_star").codexworld_rating_widget({
starLength: '5',
initialValue: $('#rating_star').val(),
callbackFunctionName: 'processRating',
imageDirectory: '<?php echo base_url(); ?>i/icon',
inputAttr: 'postID'
});
});
function processRating(val, attrVal){
$.ajax({
type: 'POST',
url: '<?php echo base_url(); ?>rating/rate',
data: 'postID='+attrVal+'&ratingPoints='+val,
dataType: 'json',
success : function(data) {
if (data.status == 'ok') {
$('#avgrat').text(data.average_rating);
$('#totalrat').text(data.rating_number);
}else{
alert('Some problem occured, please try again.');
}
}
});
}
</script>

you set default value for data here
$.ajaxSetup();
and you are overriding it here
$.ajax();
so value of token not sending to your server, also you didn't send your data as JSON only you need to send it with with data
data:{"<?=$csrf['name'];?>":"<?=$csrf['hash'];?>"}
you need to send your data in json format
data: 'postID='+attrVal+'&ratingPoints='+val,
to
data:{"<?=$csrf['name'];?>":"<?=$csrf['hash'];?>", "postID":attrVal, "ratingPoints":val}

In your javascript that fires when the page initially loads, set up like this:
$.ajaxSetup({ headers: { 'X-CSRF-TOKEN' : '<?php echo $token; ?>' } });
The 'X-CSRF-TOKEN' might be different depending on if you changed that name etc.,

Related

AJAX Internal 500 Error in Wordpress Children-Theme

I got this Ajax code on Js/Jq block (/buscador/menuLateral/menu-libros.php):
$.ajax({
url: '<?= get_stylesheet_directory_uri(); ?>' +
'/buscador/buscador-functions.php',
type: 'POST',
data: {
sendCheckedVal: 'yes',
tipo: 'editorial',
valor: valor_recogido,
archivo: this_file_id.toString()
},
success: function(data) {
alert('Checked value !');
}
});
Values on this file exists and got some value, I tried seeing it with a GET on a Stringify.
And this, must be getted in a file like this (/buscador/buscador-functions.php) :
<?php
if (ISSET($_POST['sendCheckedVal'])){
echo 'hi, u reached here' ;
}
?>
The values doesn't passes from js code file to next.
I get this error on console:
POST
[WP-URL-HIDDEN-ON-PURPOSE]/themes/ChildrenNewspaper/buscador/buscador-functions.php
500 (Internal Server Error)
On right side of the line-error :
jquery.min.js:2
Someone knows how to repair this on ajax working on a wordpress theme.Thanks
Issue is here : alert('hi, u reached here');. alert() is not PHP function it is javascript function. So instead of it you can use echoor return
<?php
if (isset($_POST['sendCheckedVal'])){
echo 'hi, u reached here';
}
?>
To start you off, alert is a javascript function.
In php you need to echo out values to the page;
If you want to do it with JS you need to print out js.
echo "<script type='text/javascript'>alert('hi, u reached here');</script>";
Or you can echo out the vars to the page.

Wordpress ajax call is returning an entire page of html

I have the following piece of javascript which runs in my wordpress site :
var PostData = "Action=refresh-cart";
jQuery.ajax({
dataType: "text",
type: 'POST',
url : location.href,
cache: false,
data : PostData,
complete : function() { },
success: function(data) {
// jQuery("#loading-img").hide();
// jQuery("#join-class-div-3").html(data);
}
});
The php is :
<?php
if(isset($_POST['Action'])) {
$Action = $_POST['Action'];
if($Action == "refresh-cart") {
echo '<div id="stuff"><p> done LOL </p></div>';
}
}
?>
So I expect to be sent back :
<div id="stuff"><p> done LOL </p></div>
But instead I receive an entire page of html!? Why!?
It will return all contents from the page rendered at your url "location.href"
Try adding a exit() to your php code to stop it after your echo.
<?php
if(isset($_POST['Action'])) {
$Action = $_POST['Action'];
if($Action == "refresh-cart") {
echo '<div id="stuff"><p> done LOL </p></div>';
exit;
}
}
?>
<div>html content here will not be displayed</div>
The problem was occuring because location.href was a high level URL, so wordpress was injecting loads of html around the ajax request.
Through altering location.url to a call to plugins.url() which is part of the wordpress PHP API - the AJAX call goes directly to my PHP page and I get the correct response :)

do not receive the POSTed data in php code ( cakephp)

I am trying to use ajax for retrieving data from my server. I use cakephp and jquery.
The ajax code is as follows:
<script>
$(document).ready(function(){
$(".viewMode").click(function(){
$.ajax({
type: "POST",
url:"viewModeSwitching",
data: {
mobileViewCookie:12,
},
success:function(result){
// window.location.href = result;
}
}
);
});
});
</script>
...
<?php
echo "<br>";
echo $this->Form->button(__('Desktop View'), array('type' => 'button','class' =>"viewMode",));
echo "<br>";
?>
This works well, in firebug I see that the POST is sent with value mobileViewCookie=12.
The point is that my cakephp controllerfunction 'viewModeSwitching' cannot retrieve that data.
I checked $this->data, $this->params, $_POST, etc but no sign of the data that had been send in the POST message.
Any suggestions?
/Antoine

javascript array in php using Ajax on submit not working

I have an array that i pass from javascript to php and in php page i am trying to put it in session to be used in the third page. The code is as below
JavaScript:
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
var jsonString = JSON.stringify(table_row);
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: jsonString},
success: function(data) {
alert("It is Successfull");
}
});
test1.php
<?php
session_start();
$check1 = $_POST['myJSArray'];
$_SESSION['array']= $check1;
echo $check1;
?>
test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
on submit i call the function in javascript and the form takes me to test2.php. It is giving error on test2.php page Notice: Undefined index: array in C:\xampp\htdocs\test\test2.php on line 13
Any suggestions please do let me know.
You don't need to stringify yourself, jquery does it for you, if you stringify it, jQuery will believe you want a string instead
var table_row = [];
table_row[0] = [123,123,123];
table_row[1] = [124,124,124];
table_row[2] = [125,125,125];
$.ajax({
type: "POST",
url: "test1.php",
dataType: "json",
data: {myJSArray: table_row},
success: function(data) {
alert("It is Successfull");
}
});
However, on the php side, you still need to decode it as it is always a string when you get it from $_POST. use json_decode to do it.
$check1 = json_decode($_POST['myJSArray']);
look at your test2.php
<?php
session_start();
$test = $_SESSION['array'];
echo $test;
?>
if it's only the code in the file then the error you got C:\xampp\htdocs\test\test2.php on line 13 is mindless, because there is not line 13,
but if you have something about the code you show us, may there be something echoed before?
because session has to be started before any output,
otherwise I've tested whole script and works fine...
To check if session really started (otherwise $_SESSION will not work), try this:
if(session_id())
{
echo "Good, started";
}
else
{
echo "Magic! strangeness";
}
if problem not found in test2.php you can check test1.php echo $_SESSION['array'] after saving it, and in your javascript callback function alert data param itself,
I'm sure you can catch the problem by this way.
i got it to work, the code is below
Javascript file: in page index.php
Either you can call this function and pass parameter or use code directly
var table_row = []; //globally declared array
var table_row[0]=["123","123","123"];
var table_row[1]=["124","124","124"];
var table_row[2]=["125","125","125"];
function ajaxCode(){
var jsonArray = JSON.stringify(table_row)
$.ajax
({
url: "test1.php",
type: "POST",
dataType: 'json',
data: {source1 : jsonArray},
cache: false,
success: function (data)
{
alert("it is successfull")
}
});
}
Page: test1.php
session_start();
unset($_SESSION['array']);
$check1 = $_POST['source1'];
$_SESSION['array']= $check1;
echo json_encode(check1);
Page: test2.php //final page where i wanted value from session
if(session_id())
{
echo "Session started<br>";
$test = $_SESSION['array'];
echo "The session is".$test;
}
else
{
echo "Did not get session";
}
?>
In index page i have a form that is submitted and on submission it calls the ajax function.
Thank you for the help, really appreciate it.

JQuery, Ajax submit with Mysqli validation

How can I submit a form dynamically where I run mysqli to check if an email exists. If it exists, echo an error ALL DYNAMICALLY.
I would like to run a jquery ajax submit but echo out php errors. I can submit but nothing will echo.
function DYNAMIC_CHECK(X)
{
$.ajax(
{
url:'<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>',
type:'POST',
data:X,
});
}
X is the formdata. It all works, but the PHP echo will not show up nor will any vars that are created and echoed out throughout the page as errors.
if(isset($_POST['REGISTER']))
{
$COUNT = mysqli_num_rows(mysqli_query($CON, "SELECT * FROM USER WHERE EMAIL='$EMAIL'"));
if($COUNT == 1) { $EMAIL_ERROR='EMAIL ALREADY EXISTS'; }
}
echo $EMAIL_ERROR;
Is this possible to dynamically show $EMAIL_ERROR?
You can use the shorthand function jQuery.post() which sends the serialized data of the form and returns the result into a variable.
$.post( "test.php", $( this ).serialize(), function ( data ) {
...what to do with data (returns the result of test.php)...
});
You can modify your ajax function to display result from the request.
$.ajax(
{
url:'<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>',
type:'POST',
data:X,
success: function(data) {
alert(data);
}
});
The echo of the request will be returned in the data variable in the success: function. Use the alert(data) to see what info is returned from the request.

Categories

Resources