Send javascript array with strings to php action - javascript

I want to send an array with image strings to my php action. This is what I do so far:
$('#savepdf').click(function() {
var imagesarray = new Array();
var count = 4;
var quizid = <?php echo json_encode($quizid); ?>;
for (var i=0; i<count; i++)
{
var chart = Highcharts.charts[i];
var canvasname;
if(i == 0){
canvasname = "canvas";
}
else{
canvasname = "canvas" + i;
}
// get highcharts
canvg(document.getElementById(canvasname), chart.getSVG())
var canvas = document.getElementById(canvasname);
var img = canvas.toDataURL("image/png");
imagesarray[i] = img;
}
imagesarray = JSON.stringify(imagesarray);
// AJAX CALL TO ACTION
$.download('/results/savepdf','quizid=' + quizid + '&image=' + imagesarray);
});
The array that I send looks like this:
["data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQCAYAAAByNR6YAAAgAElEQ…197b1kPfJ5y3guHO4WLEyAAAECBAgcEFjz7y+zZJ6ttf8GC0YA4ro/bucAAAAASUVORK5CYII=","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQCAYAAAByNR6YAAAgAElEQ…9v2cl0YeqeBTqMAAIIIIAAAgMINO3aT3a+sfNxGIa7fwBwOTGmIk2OYgAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQCAYAAAByNR6YAAAgAElEQ…xdLNBhIkAEiAARIAJEIA8I7FRlf1T/XlD/hhcoUOCv/we6Hn4A9659wwAAAABJRU5ErkJggg==","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAlgAAAGQCAYAAAByNR6YAAAgAElEQ…BdGOlYwAkjASSABJAAEkACBgm8UI89qf6sUX9GRIkS5cr/AFfL9D3Dad7CAAAAAElFTkSuQmCC"]
In my PHP action I do the following:
if(isset($_POST['quizid']))
$quizid = $_POST['quizid'];
if(isset($_POST['image']))
$image = $_POST['image'];
var_dump(json_decode($image));
The dump just shows "NULL". When I do this :
var_dump($image);
I just get : string(1) "["

Try to:
imagesarray = encodeURIComponent( JSON.stringify(imagesarray) );
UPDATE
and in php use
$image = json_decode(urldecode($_POST['image']));

I'm not familiar with the $.download method. Presumably it is an AJAX extension that allows for file downloads. I can guess how it probably works.
The problem is that you are not sending a valid HTTP request. JSON needs to be escaped to be sent over HTTP. You could do this yourself using encodeURIComponent, or you could let jQuery's $.param method handle it for you.
var data = $.param({
quizid: quizid,
image: imagesarray
});
$.download('/results/savepdf', data);

Related

why attachment_url_to_postid returns 0 when given value through variable in wordpress functions.php

I'm trying to get post id of image and then get specific size of image.
If I give hardcode single image url then it works fine but if I give url through variable then it returns 0.
It is strange behaviour
here is function
function get_image_id_and_size($image_url)
{
//return $image_url;
$image_id = attachment_url_to_postid($image_url);
return $image_id;
$image_large = wp_get_attachment_image_src($image_id, 'large');
return $image_large[0];
}
and here is javascript code
var picture = document.querySelectorAll(".active");
for (var i = 0; i < picture.length; i++)
{
var src = picture[i].src;
if (typeof src !== 'undefined')
{
var res;
if (src.includes('bedbase') && src.includes('12in_'))
{
var imgurl = src.split('12in_');
var imgres = imgurl[1].split('-');
var orgurl = imgurl[0] + "12in_" + currentcolor + ".png";
//console.log(orgurl);
res = <?php echo get_image_id_and_size(orgurl); ?>;
console.log(res);
//picture[i].src = res;
}
}
}
I checked if I return the urls it works, as you can see I commented that return line. But it don't get the post id it returns 0.
But if I give hardcode single link in argument then it works and returns post id.
I had a similar problem where the domain did not have a www. but the file url did, and that would return a 0.

Get a single string out of a php array via jquery and load it inside a html div

I am trying to get the string "Name n" out of the php array $F[], which is randomised inside the function DataInit1(), and put it in a div inside my html file. However, the PHP file cannot be changed because the arrays are randomised and used to plot a series of graphs.
PHP file:
<?php
$Return = array();
$P = array();
$S = array();
$F = array();
$P[] = [0];
$S[] = [[0.00,111],[0.50,104.74],[1.00,91.29],[1.50,93.28],...];
$F[] = "Name 1";
$P[] = [0];
$S[] = [[0.00,199],[0.50,84.06],[1.00,82.43],[1.50,83.02],...];
$F[] = "Name 2";
for($i=0; $i<count($P); $i++)
{
$Return[] = $P[$i];
$Return[] = $S[$i];
$Return[] = $F[$i];
}
die(json_encode($Return));
?>
HTML file:
<div id="GRAPH">
<div id="title"><h1 id='graphtitle'></h1></div>
<h1 id='GraphNum'></h1>
<div id="chart"></div>
<h1 id='PointNum'></h1>
</div>
The string should be placed in the "ARRAY $F" as shown below in the JS file:
function DataInit1()
{
$.ajaxSetup({cache: false, async: false});
$.getJSON("data1.php",
function(Data1)
{
SeriesList = [];
CurrentGraph.Series = 0;
for(var i=0; i<Data1.length; i+=3)
{
var P = Data1[i+0];
var S = Data1[i+1];
var F = Data1[i+2];
var NewSeries = new SeriesClass(P,S,F);
NewSeries.SeriesNumber = (i/3)+1;
SeriesList.push(NewSeries);
}
}
);
for(var i=SeriesList.length-1; i>0; i--)
{
var j = Math.floor(Math.random() * (i+1));
var x = SeriesList[i];
SeriesList[i] = SeriesList[j];
SeriesList[j] = x;
}
}
........
function Title()
{
$("#title").show();
$.ajaxSetup({cache: false, async: false});
$.getJSON("data1.php",
function(data)
{
var name = ARRAY $F;
});
$("#graphtitle").html(name);
}
Any other idea or suggestion on this issue will be very welcome. Thank you.
UPDATE:
Based on the suggestion by ironpilot. Could the solution be something like this?:
function Title()
{
$("#title").show();
$.ajaxSetup({cache: false, async: false});
$.getJSON("CurrentGraph.Series",
function(data)
{
var titleGraph = (json_decode($F, true));
var name = data.titleGraph[0];
$("#graphtitle").html(name);
});
}
You have a few issues in your code that you would need to correct before this is possible. First let's look at your PHP code. It appears that you want to create a few parallel arrays and then return them to your front-end code. However, the way that you add each array into the $Return array makes predicting where the elements are nearly impossible.
Let's start by converting the $Return variable to an object of stdClass. This will allow you to specify arbitrary properties on the object and make them accessible via a JavaScript object.
<?php
$Return = new stdClass();
$Return->P = array();
$Return->S = array();
$Return->F = array();
$P = array();
$S = array();
$F = array();
$P[] = [0];
$S[] = [[0.00,111],[0.50,104.74],[1.00,91.29],[1.50,93.28],...];
$F[] = "Name 1";
$P[] = [0];
$S[] = [[0.00,199],[0.50,84.06],[1.00,82.43],[1.50,83.02],...];
$F[] = "Name 2";
for($i=0; $i<count($P); $i++)
{
$Return->P = $P[$i];
$Return->S = $S[$i];
$Return->F = $F[$i];
}
die(json_encode($Return));
?>
Now that we have a little more predictable object to work with we can correct the jQuery code:
function Title()
{
$("#title").show();
$.ajaxSetup({cache: false, async: false});
$.getJSON("data1.php",
function(data)
{
var name = data.F[0]; //Select the first element of the $F array.
$("#graphtitle").html(name);
});
}
Now that we have an object that is returned from PHP you can access the array of names specifically to get the value that you need with var name = data.F[0];. Additional since this variable was declared with the var keyword inside the success function it's value would not be accessible outside of that function where it was set.
We also needed to move your selector for #graphtitle inside the jQuery success method. Since this method is actually a promise and doesn't execute until the AJAX request completes, what would have happened is that the function to set the html content of the element you were selecting would have executed before you received a response from the server with the content to place. This is called a Race Condition: https://en.wikipedia.org/wiki/Race_condition.
I hope that helps!

Variable not saving on .txt (medium)

I was wondering why my variable from my php page isn't saving to my .txt. I have posted the code below. All the variables match.
Everytime the new page refreshes, the message disappears and I've checked my txt file, the variables are not saved in an array as it should be.
function updateData() {
$.getJSON("#host/information.txt",
function(data) {
var senator = data[0];
var cmicrophone = data[1];
var microphone = data[2];
var words = data[3];
$("#java").text(senator + cmicrophone + microphone + words);}
);
}
<?php
session_start();
if(isset($_POST["senator"]) && isset($_POST["cmicrophone"]) && isset($_POST["microphone"]) && isset($_POST["words"])) { // If the page receives POST data, it needs to be stored
$senator = $_POST["senator"];
$cmicrophone = $_POST["cmicrophone"];
$microphone = $_POST["microphone"];
$words = $_POST["words"];
$data = json_encode(Array($senator, $cmicrophone, $microphone, $words)); // Put values into an array and encode it for storage
file_put_contents('information.txt', $data); // Put the JSON-encoded array into a text file. This function replaces the contents of the text file, which is exactly what is needed in this application. To append instead of replacing the contents, you need a FILE_APPEND flag.
} else { // If there's no POST data, the values are retrieved from the storage
$data = json_decode(file_get_contents('information.txt')); // Retrieve the contents of the text file and decode them back into an array
$senator = $data[0];
$cmicrophone = $data[1];
$microphone = $data[2];
$words = $data[3];
}
echo "". $senator. "" .$cmicrophone. "" .$microphone. "";
$wordformat = wordwrap($words, 32, "\n", false);
echo "".$words. "";
?>
If the code is correct, would it just be the
$.getJSON()
location isn't correct? The variables are all correct.

How to send array in Ajax and get it in PHP as array

I want to send in ajax array in js, get it in php as an array and insert into with sql.
My ajax call looks like:
jQuery("#Save").click(function () {
$(".linesView").each(function () {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if(window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = json_encode([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": data }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
The PHP code that needs to get the ajax call and add the data (by sql insert) looks like:
if(isset($_POST['action_name','data'])) {
$action_name = $_POST['action_name'];
$data=json_decode($_POST['data']);
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}
The accountid coming from the top of the page, I already do delete action and it works fine, so the accountid is ok. All others, I don't know.
I tried to do encode and then decode. I am not sure if the syntax is right. Anyway if I didn't write elegant code, please show me how it needs to look. Maybe i need to take each param from the data and not to call data[x]?
Use JSON.stringify()
var data = ([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": JSON.stringify(data) }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
Encode the data array to JSON string using JSON.stringify() in javascript. At server side use json_decode() to decode the data.
jQuery:
jQuery("#Save").click(function() {
$(".linesView").each(function() {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if (window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = JSON.stringify([category, date, amount, repeated, note]);
//-----------------^--- Array to JSON string
$.post("AjaxHandler.php", {
"action_name": action_name,
"data": data
}, function() {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
PHP :
if(isset($_POST['action_name','data'])){
$action_name = $_POST['action_name'];
$data=json_decode(json_decode($_POST['data']));
//-----^--- decoding JSON string
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}

jquery post form and variables together

I used this Code to send a form + a variable to a php-script.
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos }).done(function (data) {
alert(data);
});
}
now the PHP-Code:
$data = $_POST['infos'];
echo $data;
returns: formfield1=value1&formfield2=value2&formfield3=value3&test
All values are in this variable...
But how i can use them seperatly with PHP?
For example:
$data = $_POST['formfield1'];
didn't worked :(
Use jQuery's serializeArray(). It will return you with array of objects that contain 2 properties: name and value. You can then parse it and pass it as data.
It could look like this
var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
infos[formdata[i].name] = formdata[i].value;
}
// To add separate values, simply add them to the `infos`
infos.newItem = "new value";
$.post("ajax.php", infos).done(function (data) {
alert(data);
});
Then in PHP, you'll retrieve values using $_POST["formfield1"].
Try to explode them with -
$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();
foreach ($form_data as $value) {
list($key, $val) = explode('=', $value);
$posted_data[$key] = $val;
}
var_dump($posted_data);
You can use the parse_str method to convert the query string into an array.
In your case, you can do something like this:
parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need
More details here: http://php.net/manual/en/function.parse-str.php
// here is the jquery part
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos },function (data) {
alert(data); // the fetched values are alerted here.
});
}
//the php part is here
$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
foreach($form_data_val AS $form_vals){
$vals=explode($val_seperator,$form_vals);
echo $vals[1];// here the value fields of every form field and the test is fetched.
}
try this .

Categories