Transferring hash maps over ajax and converting to php array - javascript

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']);
}

Related

parsing JSON inside of ajax sucess function

I am trying to parse and display this JSON data that gets returned. Basically I have an ajax call which reads an input, sends it via POST to a PHP page and the php page var_dump's the array which contains the data.
array(1) {
[0]=>
string(21) "jsmith#yahoo.com"
}
My AJAX Call looks like..
<script>
function searchDB()
{
var lookupemail = $('#lookupemail').val();
$.ajax({
type: "POST",
url: "includes/dbsearch.php",
data: {wordpress: lookupemail},
success: function(server_response)
{
var response = server.response.1;
alert(response);
}
});
}
</script>
How do I retrieve the string that is returned and assign it to a javascript variable?
Your PHP code would have to output JSON in the first place:
$array = array('jsmith#yahoo.com');
echo json_encode($array);
To make it into an array in JavaScript you can use
var newArray = $.map(server_response, function(el) { return el; });
However, you can access the JSON directly using the json_encode in PHP.
json_encode($phparray);
and then...
server_response.arraykey

Send Data to Server using Canvas

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
}

How to access the serialized data in PHP file in the following scenario?

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.

How to get the type of the returned object from .POST ajax call?

Im using ajax .POST to run php script that suppose to return true/false. Im returning true/false using "echo" in my script. But after i get the result back to JS i compare the received text in an IF statement that never works! here is my code
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
success: function(output) {
if (output == "true"){
and here is the php script that being called
include_once('class.MySQL.php');
$userid = $_POST['action'];
$oMySQL = new MySQL();
$query = "Select * FROM videotable WHERE uid = '$userid'";
$oMySQL->ExecuteSQL($query);
$bb = $oMySQL->iRecords;
$aa = $oMySQL->aResult;
if ($bb == 0){
$query = "INSERT INTO videotable VALUES ('','$userid','true')";
$oMySQL->ExecuteSQL($query);
echo 'true';
exit();
}else{
$sharing = mysql_result($aa,0,"share");
echo $sharing;
exit();
}
I made sure that i receive true\false by doing "alert(output)" and it always displays true\false so i really dont understand why my IF statement fails even when alert(output) shows true
Thanks in advance!
Trying to parse the type of an ajax response tends to be super unreliable, in my experience.
For that reason, I (now) make darn sure that whenever I write a server side function that is meant for returning ajax data, I keep it perfectly in line with my own set response "standard", and then set my response type in the ajax method to JSON.
Doing so makes handling errors much more predictable.
An example of a standardized response would be:
$ajaxResponse = array(
'data' => $someData,
'result' => true,
'message' => 'your yadayada was succesful',
'timestamp' => time()
);
print json_encode($ajaxResponse);
and in ajax, your response would be like:
success: function( response ) {
if(response.result) {
alert(response.message);
}
}
Sorry if this isn't much help but you could try:
$.ajax({ url: 'admin_checkuser.php',
data: {action: window.myId},
type: 'post',
dataType: 'json',
success: function(output) {
if (output) { ... }
and
echo json_encode(true);
// echo json_encode($sharing);
The jQuery documentation gives more detail on what this call returns: http://api.jquery.com/jQuery.ajax/.
success(data, textStatus, jqXHR)Function, Array
A function to be called if the request succeeds. The function gets
passed three arguments: The data returned from the server, formatted
according to the dataType parameter; a string describing the status;
and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery
1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
It looks like you are expecting the data that is returned from the AJAX call to be the string "true" in your test, so if that isn't passing it must be you are getting back something other than this exact string.
I recommend using the net tab of Firebug in Firefox to see the XHR request and to examine the response of what you are getting back to see if it is something other than what you expect.

Passing a javascript array to a php page using post method

I want to pass a javascript array to a php page using ajax POST request .How to achieve this.please help..Thanks in advance
Have a look into JSON encoding.
In PHP you can decode it using json_decode, not quite sure how you'll encode it in Javascript but it is possible
http://en.wikipedia.org/wiki/JSON
using jQuery
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
Edit
if you are creating ajax object and using it then I'll suggest to convert your data in query string send it through ajax object.
like :
var userdetails = [1,2,3,4];
var queryString = "";
for(i=0; i<userdetails.length; i++){
queryString = queryString + 'userdetails[]='+userdetails[i]+'&';
}
connect.send(queryString)
example posting with json
var array = [1,2,3,4,5,6];
$.ajax({
url: "mydomain.com/url",
type: "POST",
dataType: "json",
data: {arrayName: array},
complete: function() {
//called when complete
},
success: function() {
//called when successful
},
error: function() {
//called when there is an error
},
});
Then the json could be parsed server side.
arrays can also be sent using application/x-www-form-urlencoded - this is the default format for submitting.

Categories