Do Ajax calls and maintain class structure - javascript

Hello I am wondering what is the common method of structuring ajax and php?
I am doing a website/application which have a lot of ajax calls. Also I do have a class in php I use for my main php code for keeping track of the user.
When I do ajax calls with jquery to smaller php files I need to re-declare my object I have in other files. I want the object that I have in my "main" php file. What is a good method to get the same object? Right now I am using jquery to pass the values from a div element (which comes from the object previously).
I feel this is not the best practice. I want to do it structured.
Example: I store the user session in User.
I have a button a user can click to get some information about his data. For this I have a jquery ajax call which sends and retrieves data for display. In that php file I do have to redo everything again, even if I include the class file, because the object is declared elsewhere.
Example. User can create lists in this kind of way.
I have the main index file which includes this file of new User. This type of stuff.
$user = new User();
if($_SESSION["user_connected"])
{
$user_profile = $twitter->getUserProfile();
$displayname = $user_profile->displayName;
}
$user->username = $displayname;
// Also user has an array of lists
jQuery
$('#createlistform').submit(function(event)
{
var newlistname = $('#listname').val();
var createlistRequest = $.ajax(
{
url: "ajax/ajax_add_list.php",
dataType: "html",
type: "POST",
data: {
listname: newlistname
}
}
);
the ajax_add_list file ajax is calling below. Now what I do to get this work is sending the username through as a data parameter to the php file from picking it up by $('#username').text() then set a new user with that username. It is not in the example now... but you get the point I think.
include_once("../user.class.php");
$theUser = new User();
if(class_exists('User'))
{
echo "yes class exists";
$newlistname = $_POST['listname'];
$theUser->createList($newlistname);
}
I wish I could get the same User object that was defined in my index file. I don't wanna create a new one. Although if this is how people do it when they have ajax I'll do it. I just want to know how you usually go by when dealing with different files here and there with javascript getting data from various places, while still maintaining a good structure with class and object.

Related

Save Multiple Canvas Created Images to Server via AJAX with JavaScript

I am working on a form set for a client. In a nutshell:
The forms are filled out by my client’s customers by selecting different options on each form.
Each form can have multiple instances, depending on the customer.
At the end of the process, the customer can opt to either sign one or all the forms digitally or decline to sign them digitally and at the end of the process the forms are printed out and signed manually.
To accomplish this, I’ve created a signature plugin written in jQuery. Once the customer fills out the forms, they are presented each form separately. To sign the form digitally they simply tap (click) the signature block, a dialog with a canvas element appears, they sign the form and save it, the signature appears in the form, and they move on to the next form.
Here is the portion of the code that stores the completed signature and adds the image to the form:
$.sig = {
signatures: {},
}
function signatureSave() {
var canvas = document.getElementById("sigcanvas"),
dataURL = canvas.toDataURL("image/png");
document.getElementById($.sig.target).src = dataURL;
$.sig.signatures[$.sig.target].url = dataURL;
$.sig.signatures[$.sig.target].hasSignature = true;
};
The function is only called if the signature is saved, if there is no signature, the $.sig.signatures[$.sig.target].hasSignature remains false and the system skips the object.
This all works as intended, almost.
My problem lies in the process used to save the form information. If the customer does not sign any forms digitally the form information is simply saved and the forms are printed out, no need to save any signatures.
If the customer signs at least one form, though, the signatures must be sent to the server using the FormData() object.
I’ve used the FormData object in other projects for the client successfully, but only when the customer uploads one or more images to the browser using the input file element. It’s a pretty simple process because the resulting images have a img.file property that I send to the server.
Not so with a canvas object. All I get is the .src property, an any attempt to use anything from the resulting .png image that is created in the function above results in either a “cannot use a blob” or some other error.
Now I know if I have a single image, I can send it using AJAX with the following:
$.ajax({
type: "POST",
url: "script.php",
data: {
imgBase64: dataURL
}
})
Problem is that I am sending from one to x number of signatures.
Edit: I forgot to add this in. This is the function that is supposed to create the FormData object used to send the signatures to the server (and where my problem lies):
function getUploadData() {
var upl = new FormData();
$.each($.sig.signatures, function (e, u) {
if (u.hasSignature == true && u.url != null) {
var im = new Image();
im.src = u.url;
upl.append(u.target, im, u.target + '.png');
}
})
return upl;
}
I've tried all the tricks and nothing is working. The var im = new Image(); as well as the following line are just my latest ill fated attempt.
Picture perfect would be the ability to save the image information in the $.sig.signatures object so I can simply loop through any signatures that are signed, add them as elements of the FormData object, and then send the FormData object as the data for the AJAX call. As stated before, I use this method in other projects and works fine.
Does anyone know a way to do this?
Please note:
The server-side AJAX processor functions correctly.
The signature process works correctly (customer signs canvas, signature is displayed, signature information is stored).
All I need is how to send multiple images created using the canvas element in a FormData object to the server.
I know the answer is staring me right in the face, but I am just not getting it. Any hints or suggestions would be greatly appreciated!
Edit: Just a note. I've searched the entire afternoon for this and have found entries that either deal with sending multiple files using FormData and AJAX - but the files are uploaded to the browser (not created using Canvas), or single files sent to the server that are created using Canvas, but nothing about sending multiple files sent using FormData and AJAX that are created using Canvas. Oje!
As stated, the answer was staring me in the face, but I didn't see it because was looking behind the wrong door. FormData has nothing to do with it (Homer Dope Slap!).
Since I already have the data stored in $.sig.signature for each signature, I just need to send the information to the server as the data in the AJAX function. I updated my function above as shown:
function getUploadData() {
var upl = {};
$.each($.sig.signatures, function (e, u) {
if (u.hasSignature == true && u.url != null) {
upl[e] = u.url;
}
})
return upl;
}
Since the form information is sent as JSON I just add the signature info to the object that contains the form information, JSON.stringify it and send it on its way. This should work because the information retrieved above are strings.
Server side will look something like this:
$info = json_decode( $_POST['info'] );
// Various validation routines and checks
foreach( $info->signatures as $sig=>$data ):
$data = str_replace('data:image/png;base64,', '', $data);
$data = str_replace(' ', '+', $data);
$img = base64_decode($data);
// Do some processing, file naming, database saving and other general dodads
$success = file_put_contents( $file, $img );
endforeach;
The above function is still concept, I am reworking some of the code but this should work.
Credit is given to this post for opening my eyes:
post sending base64 image with ajaxpost sending base64 image with ajax
So question answered and yeah, I deserve a dope slap, but all comes out right in the end.
CAVEAT: Works like a charm.

How to pass resource from php to javascript

So I have three different separate files:
functions.php (all functions for the database)
main.html (my main program)
main.js (all javascript functions)
Now, I want to call a function in PHP through AJAX. To do that, I need to pass $conn.
$conn = sqlsrv_connect($serverName, $connectionInfo);
It's a resource, so I can't use json_encode.
The way I set the everything up now is that the php-file is required in the html so I can use the functions and when I change the
value of a dropdown, the js is called.
How can I pass the $conn variable to Javascript?
Regards
It doesn't work like that.
You should never be directly making calls to the database from the front-end.
Think of it as three separate levels. Your HTML/JS is the front-end, your PHP is your server, and your Database is on its own level.
So when the user does something on the front-end, say changes the value of a field and you want to update that in the database the following actions should happen:
Event triggers on JS
AJAX is called as a result of the event being triggered
PHP server receives the AJAX request and executes code to modify database
(optional) PHP server sends something back to the front-end to tell it that the request was successful
Read up on the concept of MVC: https://developer.mozilla.org/en-US/docs/Web/Apps/Fundamentals/Modern_web_app_architecture/MVC_architecture
Try this in php code as I assume functions.php
$conn = sqlsrv_connect($serverName, $connectionInfo);
echo $conn;//Don't try echo anything other
In Javascript
$.ajax({
type: "POST",
url: "functions.php",
success: function(data)
{
var conn = data; // here is your conn which comes from php file
}
});
First of all include jquery latest version from cdn
Create an API Url, and use POST method
site.com/api/insert.php // to insert into table
Use $.post() api of jquery to send data
var url = ""; // enter your URL HERE
var postData = {}; // object of post data with table name, cols and values
$.post(url, postData, function(data, status) {
// do what ever you want with data
})
ps: you can also create diff insertion / selection / update / delete api for different table. (recommended)
Read more about $.post() here

Retrieve multiple variables from an AJAX call to jQuery

I have a PHP file that requests six rows from a database. I'm using an ajax call.
I want these six rows (multiple columns) to be passed through to my main file. I was unable to find a way to get these values to my main page except for posting them in html in the request file and posting this as a table on my main page.
I don't want them on the page in a plain table for everyone to be seen.
So not like this:
success: function(html) {
$("#display").html(html).show();
}
I always need six rows at the moment but could be more later on.
One of the ideas that I had was posting it as one long string and loading this into a variable, and then reading using explode or something a-like. Not sure if this is a good way to do this...
I am basically asking for ideas to expand my horizon.
I am still learning JavaScript and jQuery so I'd rather have a good explanation than a block of working code.
Thanks in advance!
PHP Side
This is a very simple process, which you may kick yourself after grasping ;) But once you do, it opens a world of possibilities and your mind will go crazy with ideas.
The first stage is you want to adjust your data that you will be returning to the ajax call. If you have a few rows of a few fields, you would do have something along these lines (could come from db, or assignments, whatever):
$rows = [];
$rows[] = array('thing'=>'value 1','something'=>'blah','tertiary'=>'yup');
$rows[] = array('thing'=>'value 2','something'=>'yadda','tertiary'=>'no');
$rows[] = array('thing'=>'value 3','something'=>'woop','tertiary'=>'maybe');
Now, to get this rows of data out to ajax, you do this one simple operation:
echo json_encode($rows);
exit; // important to not spew ANY other html
Thats all you really need to do on the PHP side of things. So what did we do? Well, we took a multidimensional array of data (usually representing what comes from a database), and encoded it in JSON format and returned it. The above will look like this to your browser:
[{"thing":"value 1","something":"blah","tertiary":"yup"},
{"thing":"value 2","something":"yadda","tertiary":"no"},
{"thing":"value 3","something":"woop","tertiary":"maybe"}]
It will have handled all escaping, and encoding of utf8 and other special characters. The joys of json_encode()!
JAVASCRIPT Side
This side is not as difficult, but theres some things to understand. FIrst off, lets get your jquery ajax call into shape:
<div id="rows"></div>
<script>
$("#your-trigger").on('click',function(e){
e.preventDefault(); // just stops the click from doing anything else
$.ajax({
type: "POST",
url: 'your_ajax.php',
data: { varname: 'value', numrows: '6' },// your sent $_POST vars
success: function(obj) {
// loop on the obj return rows
for(var i = 0; i < obj.length; i++) {
// build a div row and append to #rows container
var row = $('<div></div>');
row.append('<span class="thing">'+ obj[i].thing +'</span>');
row.append('<span class="details">'+
obj[i].something +' '+ obj[i].tertiary
+'</span>');
$("#rows").append(row);
}
},
dataType: 'json' // important!
});
});
</script>
So lets explain a few key points.
The most important is the dataType: 'json'. This tells your ajax call to EXPECT a json string to turn into an object. This object becomes what you define in the success function arg (which I named obj above).
Now, to access each specific data variable of each row, you treat it as an object. Array of rows, each row has vars named as you named them in PHP. This is where I have the for example to loop through the array of rows.
For example obj[0].thing refers to the first row of variable thing. The use of i lets you just go through all rows automatically based on length of the object. A few handy things in there.
You can build any html you wish from the returned object and values. I just showed how to setup a <div><span class="thing"></span><span class="details"></span></div> example row. You may want to use tables, or more complex setups and code.
To keep the return data from your ajax call, you can store it in a local or global variable like so:
<script>
var globalvar;
$....('click',function(e){
var localvar;
$.ajax(.... success: function(obj){
....
localvar = obj;
globalvar = obj;
....
});
});
</script>
Do what Frederico says above. Return json from your php and get in in jQuery using ajax call.
Something like this: http://makitweb.com/return-json-response-ajax-using-jquery-php/. Just skip step #3 and do what you need with received data in step #5 if you don't need it to be printed to html.

passing JSON data and getting it back

I'm new to passing objects through AJAX, and since I am unsure of both the passing and retrieving, I am having trouble debugging.
Basically, I am making an AJAX request to a PHP controller, and echoing data out to a page. I can't be sure I'm passing my object successfully. I am getting null when printing to my page view.
This is my js:
// creating a js filters object with sub arrays for each kind
var filters = {};
// specify arrays within the object to hold the the list of elements that need filtering
// names match the input name of the checkbox group the element belongs to
filters['countries'] = ["mexico", "usa", "nigeria"];
filters['stations'] = ["station1", "station2"];
filters['subjects'] = ["math", "science"];
// when a checkbox is clicked
$("input[type=checkbox]").click(function() {
// send my object to server
$.ajax({
type: 'POST',
url: '/results/search_filter',
success: function(response) {
// inject the results
$('#search_results').html(response);
},
data: JSON.stringify({filters: filters})
}); // end ajax setup
});
My PHP controller:
public function search_filter() {
// create an instance of the view
$filtered_results = View::instance('v_results_search_filter');
$filtered_results->filters = $_POST['filters'];
echo $filtered_results;
}
My PHP view:
<?php var_dump($filters);?>
Perhaps I need to use a jsondecode PHP function, but I'm not sure that my object is getting passed in the first place.
IIRC the data attribute of the $.ajax jQuery method accepts json data directly, no need to use JSON.stringify here :
data: {filters: filters}
This way, you're receiving your json data as regular key/value pairs suitable for reading in PHP through the $_POST superglobal array, as you would expect.
http://blog.teamtreehouse.com/beginners-guide-to-ajax-development-with-php
When you use ajax the page is not reloaded so the php variable isn't of use.
You may want to look for a tutorial to help. I put one at the beginning as I don't see how to format this on my tablet
you will need to json_encode your response as the tutorial shows
you may want to print to a log on the server when you are in the php function and make it world readable so you can access it via a browser
I like to use the developer tools in Chrome to see what is actually returned from the server

How to store HTML attributes that trigger javascript commands properly to mysql using ajax?

I have problems when saving html5 data from a page into mysql through an ajax request and trying to retrieve it back with ajax. HTML attributes that trigger some javascript such as
<onload> or <iframe> will be stored as <on<x>load> and <if<x>rame> in the database and thus screw up the page when loading it.
Here's a short description of what I am trying to accomplish: I want registered users to have the ability to highlight text on my site and get the highlighted text back after refreshing the page, relogging etc.
What I have done so far: I implemented a javascript highlight library on my server that allows users to highlight text. That works well.
By clicking a button, those data are then saved into mysql through jquery ajax post. See specific code here:
Javascript
$(document).ready(function() {
//saves highlighted data in var "highlighted"
$('#savehighlights').click(function() {
var highlighted = $('.tabcontent.content1').html();
//send data to server
$.ajax({
url: 'highlight.php',
type: 'POST',
data: {highlighted: highlighted},
dataType: 'html',
success: function(result) {
console.log(result);
}
});
});
Saving the data to mysql works generally, but it looks as if certain commands are disabled through the process (e.g. onload becomes on<x>load5). The data are stored in the database as longtext and utf8_bin. I also tried blob, but problem remains. I also tried different dataTypes with Ajax such as 'text' and 'script'. 'Text' causes the same problem and 'script doesn't work at all. I also tried the ajax .serialize function, but no luck either.
I really don't know what to do about it and I am not sure what is causing the problem, Ajax or mysql? I was searching the web for an answer, including many articles in stackoverflow (which normally always give me the answer), but this time I am stuck. Either I don't know enough about it to look for the right question, or I just don't have any luck this time. So, any help would be greatly appreciated.
I was requested to add some more information. Here it is:
I am actually doing this on my local server (localhost) with XAMP, so security issues should not be a problem, right? If it is of any help, I am doing this in a Tiki Wiki CMS. The php script that is called through ajax (highlight.php) is the following:
require_once ('tiki-setup.php');
include_once ('lib/highlights/highlightslib.php');
$highlighted = $_POST['highlighted'];
$highlightslib->save_highlights($user, $highlighted);
The highlightslib library is here:
if (strpos($_SERVER["SCRIPT_NAME"], basename(__FILE__)) !== false) {
header("location: index.php");
exit;
}
class HighlightsLib extends TikiLib
{
function save_highlights($user, $highlighted) {
$saveHighlights = $this->table('tiki_user_highlights');
$saveHighlights->insert
(array(
'user' =>$user,
'highlightId' =>'',
'data' =>$highlighted,
'created' =>$this->now,
)
);
return true;
}
};
$highlightslib = new HighlightsLib;

Categories

Resources