I drow some objects with canvas KineticJS,
I tried
canvas.toDataURL("image/png");
but i don't know how to get params values when i click on submit button I want send some params to server,
thanks
$.ajax({
type: "POST",
url: url,
data: "yourData="+encodeURIComponent(canvas.toDataURL());,
complete: function (result) {
//your response
},
error: function () {
//if error occured
}
});
//Accept your data serverside in your function or method or model according to technology
eg in php: -echo($_POST["yourData"]);
All the objects on the Kinetic.Stage can be serialized into a JSON string:
First, serialize the stage to JSON:
var json = stage.toJSON();
Then that json string can be sent to your server using jquery's ajax method:
$.ajax({
type: "POST",
url: "http://yourSite.com/saveTheStage.php",
data: {stageJSON: stage.toJSON()}
})
.done(function(respond){alert("done: "+respond);})
.fail(function(respond){alert("fail");})
.always(function(respond){alert("always");})
On the server, read the received json and save it to a unique filename (this example uses PHP).
<?php
if ( isset($_POST["stageJSON"]) && !empty($_POST["stageJSON"]) ) {
// get the stage data
$json = $_POST['stageJSON'];
// create a filename for the new image
$file = md5(uniqid()) . '.json';
// decode the image data and save it to file
file_put_contents($file, $json);
// return the filename
echo $file;
}
?>
Note that stage.toJSON serializes the Kinetic.Stage's properties, but does not save elements that were external to Kinetic.
For example, if your stage has a Kinetic.Image, the Kinetic.Image's properties will be serialized (x,y,etc), but the .png data of the image you injected into the Kinetic.Image will not be serialized.
Therefore is you later de-serialize the stage you must do myImage.setImage to reset the .png data into the re-hydrated Kinetic.Image.
Also note that stage.toJSON will not serialize any javascript variables, so if your LIGHT is a javascript variable, it will not be serialized.
You can add more data to your ajax packet to include LIGHT
data: {
stageJSON: stage.toJSON(),
LIGHT: LIGHT
}
Related
I was wondering if you could help. I am attempting to pass a variable to a PHP file, then run a SQL query, using that variable, then pass back the result as a variable to the javascript. Currently, I have successfully received the PHP back to the javascript using Ajax, but not able to sending the ServiceName to the PHP File. It is essential that the files stay separate. Also just to clarify I have replaced certain sections for privacy, however, they are correct and working in the code. I have also used a $_GET method already, however, I could only get the javascript to access a new window and not return the PHP variable.
My current code is as follows:
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
// Declare the value of the new Service name and save it in the variable A.
a = sender.getValue();
{
// if it equals a new variable.
if (sender.getValue() == a) {
// Place it within the URL, in order for it to be processed in the php code.
window.location.href = "http://IP/development/Query01.php?service=" + a;
// Attempted code
// echo jason_encode(a);
// $.ajax({var service = a;
// $.post('http://IP/development/Query01.php', {variable: service});
// }
//use AJAX to retrieve the results, this does work if the service name is hard coded into the PHP.
$.ajax({
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data) { // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
}
}
}
<?php
$serverName = "SeverIP"; //serverName\instanceName, portNumber (default is 1433)
$connectionInfo = array( "Database"=>"DatabaseName", "UID"=>"Username", "PWD"=>"Password
$conn = sqlsrv_connect( $serverName, $connectionInfo);
$service = $_GET['service'];
if ($conn)
{
//echo "Connection established.<br />";
}
else
{
echo "Connection could not be established.<br />";
die( print_r( sqlsrv_errors(), true));
}
$sql = ("SELECT DefaultContact2 FROM tblServices WHERE ServiceName = '$service'");
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die( print_r( sqlsrv_errors(), true));
}
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC))
{
$dC2 = $row['DefaultContact2'];
}
echo json_encode ($dC2);
sqlsrv_free_stmt( $stmt);
?>
Any help would be greatly appreciated.
You could send data using your Ajax request like so.
$.ajax({
url: "http://IP/development/Query01.php",
method: "POST" // send as POST, you could also use GET or PUT,
data: { name: "John", location: "Boston" }
dataType: "json",
success: function(data) {
editors['Contact2'].setValue(data);
}
});
Then in PHP access the sent data:
<?php
print_r($_POST);
/*
[
"name" => "John",
"location" => "Boston"
]
*/
?>
You cannot pass the javascript's variable to php on same page.
You can do this with ajax call with POST or GET method, and then you can send the manipulated data back to you browser and store it in your javascript's object or variable.
You can do it in a single Ajax call.
Remove from your code this line:
window.location.href = "http://IP/development/Query01.php?service=" + a;
And modify a bit the Ajax call
$.ajax({
type: 'GET'
data : {
service: sender.getValue();
},
url: "http://IP/development/Query01.php",
dataType: "json", //the return type data is jsonn
success: function(data){ // <--- (data) is in json format
editors['Contact2'].setValue(data);
//alert(data);
//parse the json data
}
});
I put the same variable name for the Get in the Ajax call. But I don't know if your query01.php should accept to do now both actions in the same call.
Thank you guys for your help. Just thought it would be useful, if I posted of what I went with in the end, regardless of whether it is the right way, it certainly done the job.
// If the user changes the ServiceID field.
if (sender.getFieldName() == 'ServiceID')
{
// Variable Declaration
serviceName = sender.getValue();
{
// Use JQuery.Ajax to send a variable to the php file, and return the result.
$.ajax({
// Access the PHP file and save the serviceName variable in the URL, to allow the $_GET..
// method to access the javascript variable to apply it within the SQL Query.
url: "http://ServerName/development/DefaultContact1.php?service=" + serviceName,
// retrieve the result, using json.
dataType: "json", // the return type data is jsonn
success: function(data)// <--- (data) is in json format
{
// pre-fill the contact1 field with the result of the PHP file.
editors['Contact1'].setValue(data);
}
// End of Ajax Query
});
// End of function to prefill Contact1 field.
Thank again for your responses!
I seem to be struggling with sending POST data to my PHP script.
My AJAX sends data (an ID of a blog post) to my PHP script, which then finds the row that contains a matching ID from a database.
The script then sends back the title of the blog post and the content of the post in an array, which AJAX picks up and inserts into a form in the DOM.
I can successfully:
insert sample data (for example, if I simply store strings into the array I'm passing back to AJAX, it will successfully insert those strings into the form); and
insert the correct data from the database when a static ID is specified (for example, if I switch out $_POST['editpostid'] and specify the integer 5 instead, the query successfully finds the row with ID = 5 and AJAX inserts this data into the form).
Therefore, from my point of view, the problem is that the ID is never reaching the PHP script, or my script cannot see the ID inside the JSON object.
Please take a look at my code and let me know what you think. I'm new to all this, so I'd appreciate your feedback - if it fixes the problem or not.
Javascript/jQuery:
// When edit button is clicked
$('li.edit').click(function() {
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
alert(oldpostid); // Returns the correct postid, for example 5
var jsonObj = { 'postid': oldpostid };
alert(jsonObj); // Returns 'object Object'
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
data: { 'editpostid': jsonObj },
success: function() {
// Fetch post data back from script
$.getJSON('../scripts/fetchpost.php', function(data) {
alert(data.title); // Returns null
alert(data.content); // Returns null
// All of the below code works if the PHP script returns sample text,
// or if an ID is specified in the PHP script itself
var title = data.title;
var content = data.content;
// Insert data into editor
$('#titlehead').text(title);
$('#edittitle').val(title);
var editor = 'editpost-content';
tinymce.get(editor).setContent(content);
});
},
error: function( e ) {
console.log(e.message);
}
});
});
PHP:
<?php
// Specifies connection details
include('../scripts/config.php');
// Fetch data from AJAX
$postid = $_POST['editpostid']; // Where I think the problem lies. Returns null.
// Again, this works if I switch out $_POST with an integer, such as 5
// Find rows in database that match postid
$postedit_qry = mysqli_query( $dbconnect, "SELECT * FROM posts WHERE postid='$postid'" );
// Store results in an associative array
$row = mysqli_fetch_assoc( $postedit_qry );
// Split array into variables
$title = $row['title'];
$content = $row['content'];
// Organise data into an array for json
$postedit = array(
'title' => $title,
'content' => $content
);
// Return array as json object for ajax to pick up
echo json_encode( $postedit );
// Close connection
mysqli_close( $dbconnect );
?>
Update - Solution:
Fixed jQuery/Javascript:
// Snip
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
data: { "editpostid": oldpostid },
success: function(data) {
var title = data.title;
var content = data.content;
// Snip
The PHP script remains the same.
Many thanks for your help!
MrPupper
I think you missed the index 'postid' and need to replace this
$postid = $_POST['editpostid'];
with this line :
$postid = $_POST['editpostid']['postid'];
Or instead of sending
data: { 'editpostid': jsonObj },
send this
data: { 'editpostid': oldpostid },
Looking over your code, it seems like you are getting null because you are requesting the fetchpost.php script twice. Once when you contact the script via $.ajax(...); and once more when you call $.getJSON(...);. When you contact via $.getJSON(...);, though, you are not POSTing data and it seems like your script does not have a properly defined way to handle GET requests, so the script doesn't know how to react and it returns null information.
I would change the JavaScript/jQuery to the following:
// When edit button is clicked
$('li.edit').click(function() {
// Get class (postid inserted with PHP) of edit button, excluding edit class
var oldpostid = $(this).attr('class').split(' ')[1];
alert(oldpostid); // Returns the correct postid, for example 5
var jsonObj = { 'postid': oldpostid };
alert(jsonObj); // Returns 'object Object'
// Send postid to PHP script
$.ajax({
type: 'POST',
url: '../scripts/fetchpost.php',
dataType: 'json',
data: {'editpostid': jsonObj },
success: function(sData) {
var data = JSON.parse(sData);
alert(data.title); // Returns null
alert(data.content); // Returns null
// All of the below code works if the PHP script returns sample text,
// or if an ID is specified in the PHP script itself
var title = data.title;
var content = data.content;
// Insert data into editor
$('#titlehead').text(title);
$('#edittitle').val(title);
var editor = 'editpost-content';
tinymce.get(editor).setContent(content);
},
error: function( e ) {
console.log(e.message);
}
});
});
Additionally, PHP is going to be expecting an application/x-www-form-urlencoded value to be able to interact with $_POST[...]. As such, if you want to feed it JSON, then in your PHP, you will need to implement a solution such as: $postedData = json_decode(file_get_contents('php://input')); (See more about that in this answer; for more about json_decode, see the official PHP documentation for json_decode.)
Note: While outside of the scope of your question, and you may know this already, I find it important to point out that your MySQL is insecure and vulnerable to SQL injection due to just blindly trusting that the postId has not been tampered with. You need to sanitize it by saying $postid = $dbconnect->real_escape_string($postid); after you initialize $dbconnect and connect to the database, but before you put the $postid into your SQL query string.
I'm making an interpreter for a mini language, and I'm storing related information in hash maps. I'm convering those hash maps with JSON stringify, to send them over via ajax to the server side.
This is is the post-JSON stringify code I'm sending over to the server side:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
On the server side, how could I easily make a php array out of the "kv":["24","23","20"] bit without searching for certain characters?
Before sending it over ajax the output of json array is:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
After receiving it, the data is:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
after the htmlspecialchars_decode function, it becomes:
{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}
json_decoding that gives me null
The ajax code:
function addValues(jsonArray) {
alert(jsonArray);
$.ajax({
url: 'insertTree.php',
type: 'POST',
data: 'dataToReceive=' + jsonArray,
success: function(data) {
//called when successful
alert(data);
window.location.reload();
},
error: function(e) {
//called when there is an error
console.log(e.message);
}
});
}
the php receiving code:
$dataReceived = htmlspecialchars(strip_tags($_POST["dataToReceive"]));
$dataRefined = htmlspecialchars_decode($dataReceived);
$var = json_decode($dataRefined, true);
var_dump($var['kv']); //null
Use json_decode to get the value. Since your base string isn't valid JSON, I massaged it a bit to get it to be
$string = '{"kv":["24","23","20"],"interface":"dropdown"},{"ma":["2","3","4"],"interface":"button"}';
$data = explode('|', str_replace('},{', '}|{', $string));
foreach($data as $str) {
$var = json_decode($str, true);
if(isset($var['kv'])) var_dump($var['kv']);
}
I've written a jQuery-AJAX function as follows :
$('#request_form').submit(function(e) {
var form = $(this);
var stud_id = $('#stud_id').val();
var reg_date = $('#reg_date').val();
var formdata = false;
var fileInput = $("#receipt_image")[0];
/*I want to pass values of below variables to the PHP file.*/
var ImgSizeInBytes = fileInput.files[0].size;
var filename = $('input[type=file]').val().split('\\').pop();
var customer_id = $('#customer_id').val();
/*These values need to send to PHP file and access there */
if(window.FormData) {
formdata = new FormData(form[0]);
}
var formAction = form.attr('action');
$.ajax({
url : 'student_request.php',
type : 'POST',
cache : false,
data : formdata ? formdata : form.serialize(),
contentType : false,
processData : false,
success: function(response) {
var responseObject = $.parseJSON(response);
if(responseObject.error_message) {
if ($(".alert-dismissible")[0]) {
$('.alert-dismissible').remove();
}
var htmlString = "<div class='alert alert-danger alert-dismissible' role='alert'><button type='button' class='close' data-dismiss='alert' aria-hidden='true'>×</button>"+responseObject.error_message+"</div>";
$(htmlString).insertBefore('div.modal-body #request_form');
} else {
alert("Student successfully registered...!!!");
}
}
});
e.preventDefault();
});
Now I'm able to access the values filled in by user on a form by means of $_POST array in PHP file. But I also want to pass the values I put in comment in my code above to the PHP file.
The values/parameters which I want to send are not part of a form fields. I've manipulated the values of these variables. So they can't come in $_POST array.
My issue is how should I send these values to PHP file and how should I access these values in PHP file?
You should change this: formdata ? formdata : form.serialize()
Store this in a variable and concatenate the values you want to send.
For Example:
var pars = formdata ? formdata : form.serialize();
pars += "&myField1=myValue1&myField2=myValue2"
As #chris said, all you need to do is to concatenate your own hidden variables to post variables. As I see, you are confused about how to use those extra variables in your php file, here's simple example:
var params = formdata ? formdata : form.serialize();
params += "param1=myExtraVar1¶m2=myExtraVar2";
So now you have all variables ready to be sent to your php file, modify your data parameter in ajax call like this:
...data: params,
So far, so good. Let's see the other side (PHP)
<?php
// get the variables you want to treat.
$param1 = $_POST['param1']; // now you have access to this variable from ajax call
// Notice you can display all variables you have in superglobal variable POST
// by dumping it using either var_dump($_POST) or print_r($_POST)
Hope this helps understand better the process, and feel free to comment and I'll get back to you
Another thing I captured and I'd like to share with you is that you can use datatype to JSON instead of casting your returned response, so you can put this code anywhere inside your ajax call:
dataType: "json", // if you put this in last line, omit the comma, otherwise leave as it is
How to access the serialized data in a PHP file in following situation?
The code and the serialized data is as follows:
$(document).ready(function() { $(document).on('click', '#delete_url', function (e) {
e.preventDefault();
var items = new Array();
$("input:checked:not(#ckbCheckAll)").each(function() {
items.push($(this).val());
});
var str = $("#user_filter").serialize();
$.ajax({
type: "POST",
url: "manage_users.php?op=delete_bulk_users&items="+items,
data: str,
dataType: 'json',
success: function(data) {
//var message = data.success_message;
var redirect_link = data.href;
alert(redirect_link);
window.location.href = redirect_link;
}
});
});
});
The data I'm getting in after serialize in str is as follows:
op=group_filter&page=1&from_date=11%2F10%2F2000&social_login=&to_date=11%2F10%2F2013&login_criteria=all&user_name=&user_state=&user_email_id=&user_city=
Now the PHP file(manage_users.php) is as follows:
/*The code is actually one of the switch casees*/
prepare_request();
$request = empty( $_GET ) ? $_POST : $_GET ;
$op = $request['op'];
switch( $op ) {
case "delete_bulk_users":
print_r($request);/*For printing the received array of values after form submission
Here I'm not getting serialized data */
}
Thanks in advance.
The serialize function is intended to be used to create a query string for a URL from a collection of inputs (or an entire form), and will out of necessity encode characters such as / (which denotes a directory in a URL). There's no way to tell .serialize() to convert to the "proper" format because it already is.
If you're using the result of .serialize() as part of an AJAX request it's fine to do that like so:
$.ajax({
url: 'yourpage.php',
data: str, // the string returned by calling .serialize()
... // other options go here
}).done(function(response) {
// do something with the response
});
Your server should handle decoding those characters when it receives the request and provide the correct values to you.
If you're using it for something else you could try using the native JavaScript decodeURIComponent function to convert those encoded characters back, like so:
str = decodeURIComponent(str);
Note that calling decodeURIComponent and then trying to use it for an AJAX request won't work.
For more information on URI encoding take a read through the MDN entry for encodeURIComponent.