Error when search a file in CodeIgniter - javascript

I have an error when I have tried search a file get from url. I want to search a file in directory it will match with the value get from url if matched controller will return value 'ok' to browser. But I can not see anything appear in my browser.
jquery transmit url to server
var qr_download = function(e){
var img = $('#display').attr('src');
if(img == ''){
alert('Generate a code first!');
return;
}else{
var fn = img.substr(img.lastIndexOf('/')+1,img.length-img.lastIndexOf('/'));
$.ajax({
url: 'download_file/' + fn,
dataType: 'json',
success: function(data){
if(data.error)
alert('Error: ' + data.error);
if(data.success)
alert('Success: ' + data.success);
}
});
return false;
}
my controller
public function download_file($filename){
$this->load->helper('download');
$ext = substr(strrchr($filename,'.'),1);
$list = array();
if(in_array($ext,array('png','jpg','jpeg'))){
$files = scandir('temp/');
for($i=0;$i<count($files);$i++){
if(is_file($files[$i]) && !in_array($files[$i],array('.','..'))){
if($files[$i] == $filename){
//$content = file_get_contents(base_url().'temp/'.$files[$i]);
//force_download($files[$i],$content);
$this->result['success'] = 'ok';
exit();
}
}
}//end for
}else{
$this->result['error'] = 'Not allowed file type';
}
echo json_encode($this->result);
}
Please help me resolve it. Thanks.

Related

error :[object HTMLParagraphElement], when assignin a variable from a function

i have a function that shows me if a file exists, if so he will return me the file path if it doesnt exist he will still give me the path so he can create the file:
function getnamechats($user1,$user2){
$filename1="chats/chat".$user1."&".$user2.".json";
$filename2="chats/chat".$user2."&".$user1.".json";
if (file_exists($filename1)) {
return $filename1;
}
else if (file_exists($filename2)) {
return $filename2;
}
else{ return $filename1;}
}
it works fine on creating/opening the file to write on it,ive tested a lot of times and my json file gets updated everytime:
function send_chat($nick,$chat){
global $userid;global $chatparse;
$heasda=getnamechats($userid,$chatparse);
$ok=$heasda;
// read/write
$filename = "$heasda";
$fopen = fopen($filename,"r");
$fgets = fgets($fopen);
fclose($fopen);
$decode = json_decode($fgets,true);
// limit 10
end($decode);
if(key($decode) >= 10){
array_shift($decode);
$new_key =10;
}
else{
$new_key = key($decode);
$new_key++;}
$format = array($nick,$chat);
$decode[$new_key] = $format;
$encode = json_encode($decode);
// write
$fopen_w = fopen($filename,"w");
fwrite($fopen_w,$encode);
fclose($fopen_w);
}
but in the function that opens/create it to read i get the following error the first variable is right(1) but the second one (suppost to be after the &) just doesnt work, and the error HTMLParagraphElement appears,example:
chats/chat1&[object HTMLParagraphElement].json
i then called again the getnamechats() function as soon as a new msg is triggered just to check if the file still exists, if it does, it will send me the variable $heasda to show_chat($heasda) and basically it will do the same as send_chat, but instead writing on it, it will read it:
function show_chat($heasda){
print_r($heasda);
$filename = $heasda;
$fopen = fopen($filename,"r");
$fgets = fgets($fopen);
fclose($fopen);
$decode = json_decode($fgets,true);
$val .= "<table id='table' class=\"table table-condensed\">";
foreach($decode as $post){
$val .= "<tr><td><b style=\"color:#{$post[0]}\">{$post[0]}</b>: {$post[1]}</td></tr>";}
$val .= "</table>";
return $val;
}
if(isset($_POST["chat"]) && $_POST["chat"] != ""){
$nick = $_SESSION['iduser'];
$chat = $_POST["chat"];
send_chat($nick,$chat);
}
if(isset($_GET["chat"]) && $_GET["chat"] != ""){
global $userid;global $chatparse;
$heasda=getnamechats($userid,$chatparse);
echo show_chat($heasda);
exit;
}
?>
As someone said it can be JavaScript heres the code too, ive read about it but i still dont understand properly:
function autoloadpage() {
$.ajax({
url: "?chat=1&chat-pars="+secnum,
type: "POST",
success: function(data) {
$("div#chat").html(data);
}
});
}
secnum is a DOM element, not the text inside it. You need to get the text.
You should also call encodeURIComponent in case it contains characters that have special meaning in a URL.
function autoloadpage() {
$.ajax({
url: "?chat=1&chat-pars="+encodeURIComponent(secnum.innerText),
type: "POST",
success: function(data) {
$("div#chat").html(data);
}
});
}

Get specific section of AJAX response

When i inspect the response from my AJAX request to index.php, I get back some data that i want (some json, a return value i need the value of) but also a load of HTML as the index.php class is used to call a view which is responsible for loading up some HTML.
Here is the first two lines of the response:
{"returnVal":"registered"}<!DOCTYPE html>
<html lang="en">
Due to my code being MVC, i cannot just create a separate file to handle the AJAX request, so i need a way for my login.js class (where the AJAX request is generated) to go through the whole response and find the value of "returnVal" that I need. Do you know of a way I can do this?
Login.js
var loginData, urlPath;
// Allow users to log in or register
function Login() {
if(!document.getElementById("usernameField")) { // If we have no username field on this page, we are just logging in
loginData = "email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "loggingIn";
urlPath = "index.php";
} else { // we are registering
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "register";
urlPath = "../index.php";
}
// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert(result); // i need to get the value of 'returnVal' from the response
if(result.returnVal=="registered") {
document.getElementById('notification').innerHTML = "You have been registered";
} else if (result.returnVal=="username") {
document.getElementById('notification').innerHTML = "Username already taken";
} else if (result.returnVal=="email") {
document.getElementById('notification').innerHTML = "Email already taken";
} else if (result.returnVal=="notRegistered") {
document.getElementById('notification').innerHTML = "Please enter registered email";
} else if (result.returnVal=="loginFail") {
document.getElementById('notification').innerHTML = "Please enter correct password";
} else if (result.returnVal=="loggedIn") {
$('#myModal').modal('hide');
document.getElementById('loginButton').innerHTML = "Account Settings";
} else { // Something wrong, tell us
//alert(result);
}
},
error: function(xhr, status, error) {
alert(xhr.responseText);
}
})
})
}
index.php
<?php
ini_set("log_errors", 1);
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
}
}
$view->Begin();
?>
Ultra simple way is just exit() after you echo the json so the view never gets sent. If this controller is never intended to render a view get rid of $view->Begin();
if(isset($_POST['action'])) {
if($_POST['action'] == "register") {
$controller->Register($_POST['username'], $_POST['email'], $_POST['password']);
echo json_encode($controller->GetReturned());
exit();
}
}
This is a (messy but still) way to extract the data you need.
But please consider my first comment. You should do it the other way round.
var result = '{"returnVal":"registered"}<!DOCTYPE html>someother grap';
var n = result.indexOf("<!DOCTYPE");
var jsonString = input.substring(0, n);
var json = JSON.parse(jsonString);
console.log(json);
// your values are here:
// json.returnVal;
This relies on the strict convention, that every return has a '

Do I need a captcha for my contact form (to stop spam) if the message is only sent when a user token is validated?

I am building an app for a company with javascript, html and php.(packaged up with phonegap)
The app is only for paying subscribers of the company and the user will only gain access to the app after login details
are validated.
Once login details are validated (on the server side), a JWT token is generated with the user's ID (using the JWT.class.php)
include_once '../includes/JWT.class.php';
$token = array();
$token['userID'] = $loginDetails['userID'];
$data['usertoken'] = JWT::encode($token, 'secret_server_key');
This token is then sent back to client side and stored in local storage.
On every subsequent http request (with ajax) the token is sent to the server side and validated before any
processes are carried out.
I was about to add a captcha to a contact form I have in the app, however now I am wondering if it is necessary?
When the form is submitted all fields are validated first.
If fields are valid then they are sent to story_form_handler.php.
Here is my javascript function called when the form is submitted.
function submitContactForm(e){
e.preventDefault();
var story_subject = $('#contact_input3').val();
var story_message = $('#contact_input4').val();
var contact_email_address = $("#contact_input1").val();
var contact_full_name = $("#contact_input0").val();
var contact_phone = $("#contact_input2").val();
var subjectIsValid = validateInput(story_subject, subjectRegex);
var messageIsValid = validateInput(story_message, messageRegex);
var emailIsValid = validateInput(contact_email_address, emailRegex);
var fullNameIsValid = validateInput(contact_full_name, displayNameRegex);
var phoneNumberIsValid = validateInput(contact_phone, phoneNumberRegex);
if((story_subject == "" || story_subject == null) ||
(story_message == "" || story_message == null) ||
(contact_email_address == "" || ccontact_email_address == null) ||
(contact_full_name == "" || contact_full_name == null)){
//display error
}else if((!subjectIsValid) || (!emailIsValid) || (!phoneNumberIsValid) || (!messageIsValid) || (!fullNameIsValid)){
if(!subjectIsValid){
//display error
}else if(!phoneNumberIsValid){
//display error
}else if(!emailIsValid){
//display error
}else if(!fullNameIsValid){
//display error
}else if(!messageIsValid){
//display error
}
}else{
var token = localStorage.getItem("usertoken");
var params = {'usertoken': token, 'story_subject': story_subject, 'story_message':story_message, 'contact_full_name':contact_full_name, 'contact_email_address':contact_email_address, 'contact_phone':contact_phone};
$.ajax({
url: app_root_url + 'story_form_handler.php',
data: JSON.stringify(params),
type: "POST",
dataType: "json",
contentType: "application/json;charset=utf-8",
success: function(data){
var result = data;
var token_is_valid = result.token_is_valid;
console.log("token_is_valid" + token_is_valid);
},
error: function(xhr, status, error) {
//error
}
});
}
}
story_form_handler.php
include_once '../includes/JWT.class.php';
$rawPostData = file_get_contents('php://input');
$json = json_decode($rawPostData);
if(isset($json->usertoken)){
try{
$token = JWT::decode($json->usertoken, 'secret_server_key'); //this will return an error if token has been tampered with
$data = array();
if($token->userID){
//token is valid and therefore user is valid so we go ahead submit the form.
$data['token_is_valid'] = true;
//send contact form
}else{
//token is set but is not valid
$data['token_is_valid'] = false;
echo json_encode($data);
}
}catch(Exception $e) {
$data['token_is_valid'] = false;
echo json_encode($data);
}
}else{
//token is not set.
$data['token_is_valid'] = false;
echo json_encode($data);
}
?>

Error on Ajax javascript

When I click on the button the data are sent, no problem with that but I don't see the success message and when I look the console, it write this error.
SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data mailchimp_v3.js:100:16
The error is in relation with this line on the javascript
data = jQuery.parseJSON(response);
How to resolve this error and to have the message success.
Thank you.
the form to send information
<?php echo HTML::form('mailchimp', OSCOM::link('ext/api/mailchimp_v3/subscribe.php'), 'post', 'novalidate data-mailchimp="' . $mailchimp_list_anonymous . '" data-redirect="'. OSCOM::link('index.php') .'"'); ?>
<div class="col-md-12">
<?php echo HTML::inputField('email', '', 'required id="email" placeholder="' . OSCOM::getDef('entry_email_address') . '" email data-validation-email-message="' . OSCOM::getDef('enter_valid_email_address') . '" required data-validation-required-message="' . OSCOM::getDef('enter_email_address') . '""', 'email'); ?>
</div>
<div class="col-md-12">
<?php echo HTML::button(OSCOM::getDef('button_submit'), 'fa fa-send', null, 'info',null,null); ?>
</div>
<?php
echo '</form>';
?>
the script
$(document).ready(function(){
var re = /^(([^<>()\[\]\\.,;:\s#"]+(\.[^<>()\[\]\\.,;:\s#"]+)*)|(".+"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
function validateField(element,name,value){
var required = element.attr('required');
var email = element.attr('email');
if(typeof required !== typeof undefined && required !== false){
if(value.length == 0){
element.addClass('error');
element.after('<span class="field-error">' + element.attr('data-validation-required-message') + '</span>')
return false;
}
}
if(typeof email !== typeof undefined && email !== false){
if(!re.test(value)){
valid = false;
element.addClass('error');
element.after('<span class="field-error">' + element.attr('data-validation-email-message') + '</span>')
return false;
}
}
return true;
}
$('form[data-mailchimp]').each(function(){
var form = $(this);
var list = form.attr('data-mailchimp');
var url = form.attr('action');
var redirect = form.attr('data-redirect');
function success(){
if(typeof redirect !== typeof undefined && redirect !== false){
window.location = redirect;
}
}
if(!list) return;
form.submit(function(e) {
e.preventDefault();
//Reset errors and such
form.removeClass('loading');
form.find('.field-error').remove();
form.find('.form-error').html('');
var fields = form.serializeArray();
var data = {
list : list,
email : "",
timestamp_signup : (new Date).getTime(),
merge_fields : {},
interests : {}
}
//Validate all of the fields
for(var i = 0; i < fields.length; i++){
var field = fields[i];
if(!validateField(form.find('[name='+field.name+']'),field.name,field.value)) return;
if(field.name.indexOf('email') > -1){
data.email = field.value;
}
}
//All good
form.addClass('loading');
if(data.email == ""){
form.find('.form-error').html('Please provide a valid email address.');
return;
}
$.post(url, data, function(response) {
data = jQuery.parseJSON(response);
form.removeClass('loading');
//Member already exists
if(data.status != null && data.status == 400 && data.title == "Member Exists"){
form.addClass('success');
success();
console.log('member exists already');
}
else if(data.id && data.id.length > 0){
form.addClass('success');
success();
console.log('member added');
}
else{
form.find('.form-error').html('There was an error submitting the form.');
}
});
});
});
});
More information
<anonyme> http://...../mailchimp_v3.js:100:16
r.Callbacks/i https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:27978
r.Callbacks/j.fireWith https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:2:28749
A https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:4:14201
.send/c/< https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js:4:16491
Foolow to comment data = response; seems correct, and I have no error, but I don't see the message : success
It could be either of the 2 things.
Not a valid JSON (maybe invalid JSON string)
Your response is already a JSON, and you are trying to parse it again.
Get rid of data = jQuery.parseJSON(response); and try using the response as is.
Simplest thing to do is to console.log(response) to see what the response is.

Trigger a php script using ajax - how and where to program this?

Good day,
I have a php file (db.php) which contains the following function
function edit_record($id, $value){
if($this->db->query('UPDATE tbl_prototype SET value = ' . $value .' WHERE id_component = '.$id)){
$this->register_changes();
return TRUE;
}
return FALSE;
}
Besides, I have some checkboxes in my html page as follows :
<input id="chk01" type="checkbox" data-onstyle="success" data-toggle="toggle">
<input id="chk02" type="checkbox" data-onstyle="success" data-toggle="toggle">
the html page contains also the following script.
<script>
/* AJAX request to checker */
function check(){
$.ajax({
type: 'POST',
url: 'checker.php',
dataType: 'json',
data: {
counter:$('#message-list').data('counter')
}
}).done(function( response ) {
/* check if with response we got a new update */
if(response.update==true){
var j = response.news;
$('#message-list').html(response.news);
sayHello(j);
}
});
};
//Every 1/2 sec check if there is new update
setInterval(check,500);
</script>
<script>
function sayHello(j){
var json=$.parseJSON(j);
var techname = "";
var techname1 = "";
var c;
var w;
$(json).each(function(i,val){
$.each(val,function(k,v){
if (k=="tech_name")
{
techname = "#" + v;
techname1 = v;
}
else
{
console.log("Mon nom est " + techname + " et ma valeur est " + v);
c=document.getElementById(techname1);
if (c.checked)
{
w = 1;
}
else
{
w = 0;
}
console.log(w);
console.log("techname : " + techname1);
if (v != w)
{
console.log ("Pas identique");
if (v==0)
{
// false
uncheckBox(techname);
}
else
{
// true
checkBox(techname);
}
}
else
{
console.log ("Identique");
}
}
});
});
}
function checkBox(pCtrl)
{
toggleOn(pCtrl);
}
function uncheckBox(pCtrl)
{
toggleOff(pCtrl);
}
</script>
Now for my question: where and how should I specify that I would like to run the function 'edit_record' stored in the 'db.php' file with the two parameters ($id and $value).
Contents of 'checker.php' :
<?php require('common.php');
//get current counter
$data['current'] = (int)$db->check_changes();
//set initial value of update to false
$data['update'] = false;
//check if it's ajax call with POST containing current (for user) counter;
//and check if that counter is diffrent from the one in database
//if(isset($_POST) && !empty($_POST['counter']) && (int)$_POST['counter']!=$data['current']){
if(isset($_POST)){
$data['news'] = $db->get_news2();
$data['update'] = true;
}
//just echo as JSON
echo json_encode($data);
/* End of file checker.php */
Thanks a lot for your valuable inputs. Sorry if the question sounds silly (I'm a newbie in php/ajax/jquery programming).
In modern web apps with rich interface You should go for REST API and create controller which should be in You case in checker.php. Example ( checker.php ):
if ($_SERVER['REQUEST_METHOD'] == 'POST'){
//update code
edit_record($_POST['id'],$_POST['counter]);
}
if ($_SERVER['REQUEST_METHOD'] == 'GET'){
//get code
}
ps. i do not see passing id in ajax, you send only counter, so you should add id like:
...
data: {
id:yourId //here your id
counter:$('#message-list').data('counter')
}
Next thing remove from js:
setInterval(check,500);
and create bind:
$("yourcheckboxselector").on("click",function(e){
check($(this).prop("checked") ) //here you have it was checked or not as boolean
});

Categories