AJAX to JS variable exchange - php

I used ajax to call a php to get me some values stored in my DB.
I then echo these values in my php so that i can use the responseText property to get these retrieved values (which i want to store in a JS array) for further referral.
Here's where i get stuck. I do manage to do this when I have to retrieve just 1 row from the DB (I did this by separating the fields using a ',' and subsequently using the split() function in JS to parse the string). However when my DB returns more than 1 row then I reach a deadend as this method of mine doesn't seem to work. Kindly advice the easiest way to overcome this hurdle.

use
var jsArray = {};
$.each(response, function(i, item) {
jsArray[i] = item;
});
the above JQuery loop is equivalent to PHP loop:
foreach($response as $i => $item) {
$jsArray[$i] = $item;
}

You can convert the PHP array of multiple DB rows to json using json_encode on server side and parse JSON on the client side using javascript reading help from here. A more code oriented answer needs some code in question to work with.

Related

Serialising a form data in jquery gives unnecessary symbols.How to avoid them?

Serialise() function in jquery adds unnecessary symbols to the data.
In my script i'm doing serialize() in jquery .Then sending this value to another php file through jquery ajax function as one of the parameter.Then inserting into database through queries.The variables are converting into unnecessary variables.Please let me know how to resolve this issue.
$params = $("#admit_order").serialize()
Actual Result : 1152%2BHidden%2BRidge
Expected Result : 115 Hidden Bridge
You can decode the serialised data by using decodeURIComponent().
$params = $("#admit_order").serialize();
decodeURIComponent($params);

Can't assign jquery value to session variable in Yii

In the following code the value item.rmid is provided by jQuery. The value is fetched from database, displayed in item.rmid and has to be stored in Yii::app()->SESSION["rid"] but it's not working.
In view I have the following code:
$("#pct").html('');
$.each(<?php echo $ar; ?>, function (i, item) {
$("#pct").append('
<div class="title">
fss"
<?php Yii::app()->SESSION["rid"]=' + item.rmid + ' ; ?>"
<?php echo Yii::app()->SESSION["rid"];?>
</div>')
}
What am I doing wrong?
UPD
when i var_dump($ar);
following is what i get
string '[{"pimg":"12.jpg","pid":"3","createdate":"2014-01-15 12:12:47","rid":"25"},{"pimg":"WP9.JPG","pid":"1","createdate":"2014-01-15 12:14:23","rid":"26"},{"pimg":"n2.jpg","pid":"4","createdate":"2014-01-16 11:01:27","rid":"54"}]
but the am unable to assign the rid value ......... know i got it i have multiple rid and am assign it to one Yii::app()->SESSION["rid"] which cant store all value at each iteration...
how do i pass it in the querystring but the valueto be hidden
You can't update stuff on the server via javascript without AJAX.
Use ajax to send a request to the server and update the session value using
Yii::app()->session['var'] = $_POST['received_value'];
Read up about ajax here.
The main thing to note is that PHP part of the code is already finished working when your browser runs your javascript. What your code doing is just assigning the string ' + item.rmid + ' to some PHP variable. It's just a constant string which is not connected to your javascript at all. After that your browser gets something like the following javascript:
$("#pct").html('');
$.each(some_array_from_php, function (i, item) {
$("#pct").append('
<div class="title">
fss""
+ item.rmid +
</div>')
}
Notice how it gets "preprocessed" by PHP. It's not even good javascript really, because you can't use multiline string literals in javascript.
What you can do is to push some value from javascript to your server. So you need to feed javascript code to your browser first, get your value available in javascript and then somehow make another HTTP request passing the value as a GET parameter or something. There is a technology for this purpose, it's called AJAX. Check this out.
But from your code example it looks like you already have all the values on the server (in $ar variable, in JSON format), so you can just assign session variable on PHP and use javascript only for client-side visualization.
First you need to decode JSON:
$decoded = json_decode($ar);
Now $decoded is just an array of PHP objects, so you can do something like:
Yii::app()->session["rid"] = $decoded[0]->rid;
Above we are storing the "rid" of the first object to session. If you want to store all of them just loop through $encoded while pushing values to session like this:
foreach ($decoded as $obj) {
Yii::app()->session["rids"][] = $obj->rid;
}

How to POST a multi-dimensional PHP array via a hidden input field using $.ajax?

I realise there are a few other questions regarding this and I have read them and attempted the solutions however they are not working for me. It may be because I am serializing the post twice because I am passing the entire form serialized by jQuery/JavaScript.
My PHP array is a 2 dimensional? one containing filenames:
$aDocumentFilesArrayFileName[0][0];
I generally have 1 dimensional arrays in my PHP so I pass them by using:
<input type="hidden" name="arrayName[]" value="$value[$i]"> // (while in a loop
I am not sure what syntax I should use when I reference the first array in terms of name and also what value I should use.
I've tried to use the value as: serialize($aDocumentFilesArrayFileName) and decode at the other end but I get an error saying string expected found array?
** EDIT **
I think I could have made the question clearer but just to clarify. Here is my jQuery Ajax submit function:
var conflictData = $("input, select", conflictsTable.fnGetNodes()).serialize(); // fnGetNodes is just a datatables function to go through every row in a table - don't worry about that
$.ajax(
{
type: 'POST',
url: 'sqlHandleConflictsDocumentRegister.php?node='+nodeType+'&id='+nodeId,
cache: false,
data: conflictData,
success: function(result)
{
// Do stuff here
}
});
I have tried the solution to use json_encode rather than serialize on my PHP input statement. That isn't working. Here is the exact code I use in the PHP form. Please be aware that this line is within a loop that occurs for each row of the table in the form.
<input type="hidden" name="arrayFileName[]" value="<?php echo json_encode($aDocumentFilesArrayFileName[$i]); ?>">
Here is the code I use on the PHP ajax script:
$fileNames = json_decode($_POST['arrayFileName']);
Error is:
json_decode() expects parameter 1 to be string, array given in C:\wamp\www\document\sqlHandleConflictsDocumentRegister.php on line 65
Is the problem that I am serializing (in JavaScript) varying dimensions of array data?
My other inputs are from rows that have simple array data (one value for each row) and they work fine. This particular array input has an unlimited number of filenames associated per table row, so the input value is an array.
I also pass the value of the quantity of files (per table row) in another input. Perhaps I can use this to help extract the array on the other side.
<input type="hidden" name="quantityFiles[]" value="<?php echo $aDocumentQuantityFiles[$i]; ?>">
** UPDATE **
I used alert(conflictData) and found that the array data is fine apart from it is empty for the arrayFileName field.
If I echo json_encode($aDocumentFilesArrayFileName[$i]) then I get the expected result.
Hence, it looks as if the jQuery serialize() is destroying this data. Perhaps there is a way I can prepare the data variable better for ajax submission?
** UPDATE 2 **
Thank you all for your assistance and contributions to the answer. I was already using json_encode to get the data into javascript for operating on it there so I have abandoned using an input field to serialize and send the data and instead directly used the data parameter of $.ajax to send the array for processing.
As there was no distinctly correct solution provided I have posted a solution below and will mark it as the correct answer since I am now able to obtain the multidimensional array data in the destination PHP file.
Serialize over ajax(user involved) opens a range of security vulnerability's because the user could make you unserialize a object and try to execute that.
Try to use the appropriate function json, http://php.net/manual/en/book.json.php. Json is the way to go for using with Ajax(Javascript).
You can use json_encode function of php to send php array to javascript.
Please use
echo json_encode($phpArray);
and you have to set last parameter of $.post() is 'json' if you are using $.post() method or if you are usig $.ajax() method than you have to set dataType: 'json'
http://api.jquery.com/jQuery.post/
jQuery serialize works fine for regular arrays but not multidimensional arrays in this scenario. It seems to corrupt when mixing the data from various arrays.
Solution:
json_encode the multidimensional PHP array data and pass to javascript using the code below:
<script>
var aQuantityFiles = <?php echo json_encode($aDocumentQuantityFiles); ?>; // this is a regular array which is also related to the multidimensional array
var aDocumentFilesArrayFileName = <?php echo json_encode($aDocumentFilesArrayFileName); ?>; // this is a multidimensional array
</script>
Use the data parameter in the $.ajax request to individually pass the prepared javascript variable:
$.ajax(
{
type: 'POST',
url: 'sqlHandleConflictsDocumentRegister.php?node='+nodeType+'&id='+nodeId,
cache: false,
data:
{
aQuantityFiles: aQuantityFiles,
aDocumentFilesArrayFileName: aDocumentFilesArrayFileName
},
success: function(result)
{
//Do Something
}
});
On the destination PHP side it is now very simple (no need to decode)
<?php
$aQuantityFiles = $_POST['aQuantityFiles'];
$fileNames = $_POST['aDocumentFilesArrayFileName'];
for ($i = 0; $i < $numberRows; $i++)
{
// This is the bigger loop cycling through the rows of data which contain the multiple files
for ($j = 0; $j < $quantityFiles; $j++)
{
// Echo to illustrate that data is extracted multidimensionally as expected
echo $fileNames[$i][$j];
echo "<br/>";
}
}
?>
Optional
Now the multidimensional array data is accepted by the destination PHP file but you may need to bundle the additional form data with the extended array data before you send it with $.ajax. I found out how to do this using the $.param function from the site below.
http://www.jblotus.com/2011/07/12/combine-serialized-form-post-data-with-arbitrary-object-in-jquery/

Access php array variable (from ajax call) in javascript

I'm having trouble accessing an array created in php, to use in a javascript block.
I know about
<?php echo json_encode($myArray); ?>
but I'm not getting any results out of it.
I have a 'index.html' file where I try to access the array through javascript.
The html page exists out of a drop down menu. When the user chooses an item in that drop down menu, the chosen item is used as an argument to retrieve data from a database.
The 'ajax.js' file contains the code to execute the 'retrieve.php' file which constructs the array ('$myArray') from database content. So the array is retrieved through an ajax call.
Can I 'echo' to the javascript code from my php file:
echo 'dataArray = ' . json_encode($data_array) . ';';
and use that javascript variable?
In other words, how can I execute my javascript code using that new 'dataArray' variable?
To get the bigger picture: I'm trying to use that array for use in a 'Google Chart', for which I need to use javascript to display the chart.
I can query all data and put it in a php array, but I'm not succeeding in transfering it properly to my html page with javascript and reload the chart.
Edit: I use an ajax call to no to reload the entire page.
Instead of " echo 'dataArray = ' . json_encode($data_array) . ';'; ", you should just write this-
"echo json_encode($data_array)"
And then interpret it in the client using JSON.parse(response) where response the response you received from the server (the json)
I found that the best way to do this is like so:
Client code:
<script>
var phpdata = <?=json_encode($jsData)?>;
</script>
Server code:
$jsData = '';
$jsData->first = $first;
$jsData->second = $second_array;
Client side usage:
alert(phpdata.second[1]);
EDIT:
To get an array from php using AJAX, use jQuery http://api.jquery.com/jQuery.getJSON/
Client side:
var stored_array;
$.getJSON(url, function(data){
stored_array = data;
// run any other code you wish to run after getting the array.
});
Server side:
print(json_encode($array));
this will get a json encoded variable and store it for your use.
Yes you can use this array of php by assigning the above json_encode function
You can use it as associative array if the array is associative or object used in php and if no-associative you can use it as normal array.

Help with jQuery grabbing json data

I am having some trouble here, my json data is outputting as follows:
{"date":[{"day_w":"Tuesday","day_n":"28","month":"Dec"}],"subscriptions":[{"subscribe":"example1"},{"subscribe":"example2"},{"subscribe":"example3"}]}
I am using the jQuery code:
$.getJSON("example.php",function(data){
$.each(data.subscriptions, function(i, item) {
var subscribeData = "<li>"+ item.subscribe +"</li>";
$('#list').append(subscribeData);
});
but I am having an issue grabbing the date array. I don't want to have to use .each because there is only one array holding the date. Does this make sense? Can anyone please help?
Why is date an array at all? Why not just have the object in there directly?
{"date":{"day_w":"Tuesday","day_n":"28","month":"Dec"},"subscriptions":[...
If that's not an option, you can just access date[0]:
doSomethingWith(data.date[0].day_w);
You can write data.date[0] to get the first object in the array.
Try this - http://jsfiddle.net/FloydPink/bAtEW/

Categories