Blueimp plugin fileupload Jquery: Send additional information to PHP handler - javascript

I'm trying to send information (additional Handling form data) from fileupload jquery plugin (blueimp) to PHP file. In the PHP file handle can not get the information (content of variable). I think I have a problem in the code. Can some altruistic soul enlighten the way? Thanks in advance.
Javascript file:
$(function () {
$('#fileupload').fileupload({
dataType: 'json',
formData: {idGrupo: 250}, <----I want to send this to PHP file!
done: function (e, data) {
$.each(data.result, function (index, file) {
// $('<p/>').text(file.name).appendTo('body');
});
}
});
});
PHP file (index.php ):
error_reporting(E_ALL | E_STRICT);
require('UploadHandler.php');
class CustomUploadHandler extends UploadHandler
{
protected function handle_form_data($file, $index) {
$sesionIdGrupo2 = $_REQUEST['idGrupo'];
}
protected function trim_file_name($name, $type, $sesionIdGrupo2) {
$name = parent::trim_file_name($name, $type);
$name = $seionIdGrupo2;
return $name;
}
}
$upload_handler = new CustomUploadHandler();
Again I appreciate the help, that would not do without this community (well yes, would do anything that was not code ;). Please be patient, I am newbie :(
Note:
The variable $sesionIdGrupo2 not retrieve the value. My intention is to put the contents of this variable (250) as the name of the uploaded file. ¿Could it be a problem of global variables?

To send Data to PHP UploadHandler.php just send it via url like this:
$(function () {
$('#fileupload').fileupload({
url: 'server/php/index.php?idGrupo=250',
dataType: 'json',
autoUpload: false,
});
});

....i solve that problem! ...i put the Request inside the function "trim_file_name". I think is bad idea, but seem work...
protected function trim_file_name($name, $type) {
$name = parent::trim_file_name($name, $type);
$sesionIdGrupo = $_REQUEST['idGrupo']; <------this work, recibed 250
$name = $sesionIdGrupo;
return $name;
Saludos!

Related

loading message with jquery and calling id

I made a small shoutbox for my site and I am loading the page with jquery and storing all my data in a database like usual. anyways, when a user wants to edit a post they double click on it and they can edit their post. I am using the following code to show the editor and let them do whatever they need to with it. sadly something isn't working and that something is:
i cant include my tag id in the url: on my ajax call
Here's is a look at the code
<? php
public function make_editable($shout, $id) {
$string = "<span ondblclick=\"javascript: edit_shout('".$id."'); return false;\">".$shout."</span>";
return $string;
}
?>
<script type="text/javascript">
function edit_shout($id) {
$("#panel_edit_shout").slideDown();
$('#update').val($id);
$('#delete').val($id);
$.ajax({
url : "/chat?loadModule=3&id={$id}",
dataType: "text",
success : function (data) {
$("#updateshoutmessage").val(data);
}
});
}
</script>
If i replace the {$id} with say, 1 for example, then it works correctly and loads the text of shout id 1 into the field like its supposed to, but if I try and load dynamically using $id, it just gets an error because the $id is coming up as blank... Thanks for your help :).
Uhm... if the variable is in javascript you can do:
url : "/chat?loadModule=3&id=" + $id,
If it is php then you have to do
url : "/chat?loadModule=3&id=<?=$id?>",
But like the other guys said, without more code we can't help much.
Very easy fix thanks to #Dranes for his help. Simply needed to add +
<script type="text/javascript">
function edit_shout($id) {
$("#panel_edit_shout").slideDown();
$('#update').val($id);
$('#delete').val($id);
$.ajax({
url : "/chat?loadModule=3&id=" + $id,
dataType: "text",
success : function (data) {
$("#updateshoutmessage").val(data);
}
});
}
</script>

Unable to get response from php return in ajax request

I am trying to access the output from php code to jquery ajax. But I donot know why It is returning me whole page html including the result. can anybody please tell me about it. In firefox console Its show me response of page html including php result. But In jquery code console.log does not hit.
Here is jquery code
function getprofile()
{
$.ajax({
url: 'Userpage/get_profile',
//data: {'title': title}, change this to send js object
type: "post",
dataType: 'json',
data: {'userid': 1},
success: function(data) {
console.log(data);
}
});
}
My php code
<?php
if (!defined('BASEPATH'))
exit('No direct script access allowed');
class Userpage extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("session");
$this->load->model("Userpage_model");
$this->load->view('Userpage_view');
}
public function index()
{
}
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit;
}
}
?>
Please review the code and tell me where I am going wrong
Thanks
Use exit
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
echo json_encode($data['comments']);
exit; // use exit here
}
EDIT
PHP uses a special function called header() for setting properties of the page during rendering.
you need to return from your function, using exit is fine but it's not a good practice
public function get_profile()
{
$data = array();
$post_id = $this->input->post('userid');
$data['comments'] = $this->Userpage_model->get_profile($post_id);
return json_encode($data['comments']);
}
You are using CI. From this ajax call:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
}
});
you expect an ajax call is being made to get_profile action inside Userpage controller, that probably will return:
{
"comments": [
{ ... },
{ ... },
{ ... },
...
]
}
which will be logged in browser console.
But you get unexpected result, right?
I think, your ajax call results in error. To prove this, modify your ajax call:
$.ajax({
url: 'Userpage/get_profile',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
// add this function to logs error
console.log(textStatus + ': ' + errorThrown);
}
});
Now, if the ajax call results in error, you can see the error in browser console. I am pretty sure you will get error: Not Found in browser console.
You are using CI, the URL will be something like:
http://<something>/index.php/site/index
In this page, if you make ajax call with url Userpage/get_profile, what the browser really does is make ajax call to:
http://<something>/index.php/site/index/Userpage/get_profile
instead of what you expect:
http://<something>/index.php/Userpage/get_profile
To solve this, you must change the value of url in your ajax call, to point the correct URL above.
By using CI, the absoulte URL above can be generated with the help of site_url() function:
site_url('Userpage/get_profile')
I usually print this URL somewhere in HTML, and retrieve it from javascript during ajax call.

Using Ajax, JavaScript and HTML to post some data

Hello I´m very frustated because I can´t connect to my database to retrieve some files.
I have my normal html code (index.html) which adds a javascript:
<script src="js/connection.js"></script>
The javascript (connection.js) looks something like this, which detects from a grid of elements the selected element and gets it´s text:
var texto="";
function getData($dia){
//Variable $dia is set up correctly, no problem
var dia=$dia;
/* Send the data using post*/
$.ajax({
url: "php/setup.php",
type: "post",
data: {'fecha':dia},
contentType: "application/json",
datatype: "json",
success: function(){
alert("Exito");
},
error:function(){
alert("failure");
}
});
}
//Get the desired text upon click on the grid item
$(document).ready(function(){
$(".grid__item").click(function(){
$texto=$(this).html().substring(($(this).html().indexOf(">"),($(this).html().indexOf(">")+1)),$(this).html().indexOf("</h2>"));
getData($texto);
});
});
Finally using Ajax I pass the variable 'fecha', the problem is that I think it´s not making a proper connection with my php file since nothing is printing (I have a method which prints to console)
I set the post method like this (PHP file starts here):
debug_to_console("Print Something");
$fecha = mysql_real_escape_string($_POST['fecha']);
getPageData($fecha);
Which calls this method:
function getPageData($dia){
$sql = ("SELECT * FROM Comentarios WHERE dia='$dia'");
$result = mysqli_query(connectToDb(),$sql);
$num_rows = mysqli_num_rows($result);
$html="";
$boolean=true;
if($num_rows>0) {
while($row = $result->fetch_assoc()) {
if($boolean==true){
$html.='<div class="gray"><div class="comentario">'.$row["comment"].'</div><div class="timestamp">'.$row["dia"].'</div></div>';
$boolean=false;
}else{
$html.='<div class="white"><div class="comentario">'.$row["comment"].'</div><div class="timestamp">'.$row["dia"].'</div></div>';
$boolean=true;
}
}
echo json_encode(array('html'=>($html.'<br>'.'<div class="fondo_gen"> div></div></div>'),'texto'=>$dia));
} else {
echo json_encode(array('html'=>'<div class="transparent"><div class="nada">No hay comentarios aun :(</div></div>','texto'=>$dia));
}
}
PHP file ends here
I know that it's connecting to the database since a made a "dummy.php" file which connects to the same database and table and adds a record, without problem. I´m not really sure which is the problem, I could really appreciate it if you could help me.
PS:
My folders are setup like this:
index.html
js (folder)
a. connection.js
php (folder)
a. setup.php
.
Thanks and sorry for my crappy english
Never mind, I got it fixed, I replaced the Ajax part with:
$.post("php/setup.php",
{
fecha: dia
},
function(data, status){
alert("Data: " + data + "\nStatus: " + status);
});
and received the variable using
if (isset($_POST["fecha"])){
$fecha = $_POST["fecha"];
getPageData($fecha);
}else{
echo "Got nothing";
}
Thanks anyway, I appreciate the help

Make jQuery AJAX Call to Specific PHP Functions

I am a rookie PHP developer.
I have created a PHP web project with an HTML page that contains an 'Add' button. The name of the page is awards.html. The awards.html file contains its counterpart JavaScript file, awards.js. A code is executed in this js file when the Add button is clicked. This code sends an AJAX call to a PHP class located in /controller/ folder in the project named, Award.php. This PHP file which contains code to execute a function called, addFunction() in another Award.php file located in /model/ folder in the project, which returns a JSON array and is displayed in the awards.html page.
The source code of my files is given as follows:
Awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onAdd();">Add</button>
</div>
</div>
awards.js
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
Award.php (located in /controller/ folder)
<?php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
Award.php (located in /model/ folder)
<?php
class Award
{
public function addFunction() {
$array = array(
'status' => '1'
);
return $array;
}
}
My code works perfectly and is error-free. Now I want to add another button in awards.html called, Save which when clicked will call a function onSave() in the JS file. Thus the source code of my files will change to the following:
awards.html
<div class = "divbottom">
<div id="divAddAward">
<button class="btn" onclick="onAdd();">Add</button>
<button class="btn" onclick="onSave();">Save</button>
</div>
</div>
awards.js
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
function onSave() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
Now the problem here is that since I want to call the same Award.php file from JS, how do I modify my controller Award.php file? In my opinion there should be twoo different functions which would contain code to instantiate the view Award.php class and call a different function; something like the following:
Award.php
<?php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
function add(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
}
function save(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->saveFunction();
echo json_encode($method);
}
Award.php
class Award
{
public function addFunction() {
$array = array(
'status' => '1'
);
return $array;
}
public function saveFunction() {
$array = array(
'status' => '2'
);
return $array;
}
}
But how do I call these specific PHP functions from my JS file? If the code I have assumed above is correct, then what should be my JS code? Can anyone please advise me on this? Replies at the earliest will be highly appreciated. Thank you in advance.
Okay I found the solution to the problem myself.
I sent a GET-type AJAX call with the data passed in the form of String parameters and added a success property to get a confirmation whether my code has worked or not. I also changed my Award.php code to catch the passed parameter successfully.
So the source code of my files is:
awards.js
function onAdd() {
$("#display").load(filePath);
$.ajax({
type: "GET",
url: 'controller/Action.php',
data: "functionName=add",
success: function(response) {
alert(response);
}
});
}
function onSave() {
$("#display").load(filePath);
$.ajax({
type: "GET",
url: 'controller/Action.php',
data: "functionName=save",
success: function(response) {
alert(response);
}
});
}
Award.php
$functionName = filter_input(INPUT_GET, 'functionName');
if ($functionName == "add") {
add();
} else if ($functionName == "save") {
save();
}
function add()
{
$award = new Award();
$method = $award->addFunction();
echo json_encode($method);
}
function save()
{
$award = new Award();
$method = $award->saveFunction();
echo json_encode($method);
}
You would be better off using an MVC framework in which you can have controller functions for add and save functionality. You can achieve the required behavior with your current implementation by sending a query string parameter to tell your php script which function to call:
<?php
foreach (glob("../model/community/*.php") as $filename) {
include $filename;
}
function add(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->addFunction();
echo json_encode($method);
}
function save(){
$award = new Award(); //Instantiating Award in /model/ folder
$method = $award->saveFunction();
echo json_encode($method);
}
if($_GET["action"] == "save")
save();
else if($_GET["action"] == "add")
add();
Your js code will look like:
function onAdd() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php?action=add'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
function onSave() {
$("#divAddAward").load('controller/Award.php'); //The full path of the Award.php file in the web root
$.post(
'classes/Award.php?action=save'
).success(function(resp) {
json = $.parseJSON(resp);
});
}
There is a method that I have discovered. Please read my explanation completely to continue.
In your ajax code (I think you use jQuery), include another info 'perform', with value = php function name.
$.post("something.php", {
something1: something1value,
something2: something2value,
perform: "php_function_name"
});
Then, in your PHP file, add this piece of code at the beginning :
<?php if (isset($_POST["perform"])) $_POST["perform"](); ?>
Then, when you call using ajax, you can get a particular function executed.
Example Usage :
Javascript :
$.post("example.php", {
name: "anonymous",
email: "x#gmail.com",
perform: "register"
}, function(data, status) {
alert(data);
});
PHP file example.php:
<?php
if (isset($_POST["perform"])) $_POST["perform"]();
function register() {
echo "Hai " . $_POST["name"] . " ! Your email id is " . $_POST["email"] . ".";
}
?>
When you do this, automatically, function register() will get executed.

JavaScript in CakePHP's controller

In my CakePHP view, I call method in controller, using jQuery:
function placeSensors(nk) {
$.ajax({
type:'post',
url:'/myapp/maps/placeSensors/' + nk,
success: function(r) {
if(r.status = 'ok') {
}
}
});
}
JS in controller is defined with ie.:
class MapsController extends AppController {
var $name = 'Maps';
var $helpers = array('Js');
var $uses = array('Measurings', 'Maps');
var $components = array('RequestHandler'); // added later, but still the same
function index( $id = null, $value = null ) {
$code = '';
?>
<script type="text/javascript">
alert('Hello!');
</script>
<?php
return $code;
}
So, with simple code, I can not get alert message on my web form. Very simple code I was using in some other project and it works there, and for some reason this does not work on this one...
I'm really stuck with this one, can you please help me.....
UPDATE: this is response i'm getting by Firebug:
<script type="text/javascript">
alert('Hello!');
</script>
You're trying to place code that should be viewed (javascript) by the client, inside a controller. Controller is for business logic, that the client doesn't see.
Place your javascript inside a javascript file in the /webroot/js/ directory.
For interacting with ajax, tell your controllers to use the RequestHandler component to determine that they're being called by ajax. From there you can return simple values, or return a json or xml view.
If that sounds complicated, don't worry about it for now and just start as simple as you need and slowly build up your application.
function placeSensors(nk) {
$.ajax({
type:'post',
dataType:'json',
url:'/myapp/maps/placeSensors/' + nk,
success: function(r) {
if(r.status) {
alert(r.code);
}
}
});
}
class MapsController extends AppController {
var $name = 'Maps';
var $helpers = array('Js');
var $uses = array('Measurings', 'Maps');
function index( $id = null, $value = null ) {
}
// update below code
function placeSensors( ) {
$nk = $_POST['nk'];
echo json_encode(array(
'status' => true,
'code' => "code"
));
exit();
}
Ok, i finally solved this one.
All I needed was to add one form and one text, or even better hidden element on form.
After that everything started to work.
So my mentioned code was ok, all I needed was that one text box......... Hope that somebody can tell me why?
Thank you on all your help and support.

Categories

Resources