Passing PHP Array to AJAX (Success) Function - javascript

I want to pass an array to my AJAX function within the success function of an AJAX call. This array is data from my database using a global $wpdb; because this is easy to use and I know how to. Is there a way to pass this array to the AJAX function? Or is there a way to just get the data in AJAX?
I got this in my script tag and it is working:
jQuery(document).ready(function(){
jQuery('#date-select').on('change',function(){
var seldate= jQuery(this).val();
if(seldate!=''){
var seldateEdited = seldate.replace("T", " ");
jQuery.ajax({
type:'POST',
url:'http://esr-berlin.de/wp-admin/admin.php?page=einteilung_erstellen',
data:'var='+seldate,
success:function(html){
var output = '<option value="">Wähle HSR1</option>';
jQuery.each(html.data, function(i,s){
var newOption = s;
output += '<option value="' + newOption + '">' + newOption + '</option>';
});
jQuery('#hsrPop').empty().append(output);
}
});
}
});
});
EDIT
I forgot something important. For the array or especially for the sql query I need a variable that I have in javascript. So I basically need another AJAX Call, right? How would I do that?

You can encode the array in the PHP file and return this. It will just return a string to your AJAX function
json_encode($array)
https://www.php.net/manual/en/function.json-encode.php
You can then use to convert it into a Javascript array for processing
JSON.parse(json)
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

Assuming Your server side code(admin.php) something like:-
$result = array();
//your code here to fetch data dynamically
$result['status'] = True; //based on your conditions optional
$result['data'] = array(0=>"option1",1=>"option2",2=>"option3") ;
echo json_encode($result);
Hope this will help.
jQuery(document).ready(function()
{
jQuery('#date-select').on('change',function()
{
var seldate= jQuery(this).val();
if(seldate!='')
{
var seldateEdited = seldate.replace("T", " ");
jQuery.ajax({
type:'POST',
dataType:'json', //added to receive json format data
url:'http://esr-berlin.de/wp-admin/admin.php?page=einteilung_erstellen',
data:'var='+seldate,
success:function(html)
{
//here you can check if html.status is True/False .. optional
var output = '<option value="">Wähle HSR1</option>';
jQuery.each(html.data, function(i,s)
{
var newOption = s;
output += '<option value="' + newOption + '">' + newOption + '</option>';
});
jQuery('#hsrPop').empty().append(output);
}
});
}
});
});

Related

Handle <select> values with ajax in module class, prestashop 1.6

I'm developing a ps module which let you classify the product attachment in categories an display them in the front product page.
I'm using a draggable list with the attachment, and when you drop them to the category it turns to an option tag, each category has a select tag where to drop the attachment.
I want to save the attachments and the category where they was dropped, so I thought make an ajax call to bring the data to my module class but I'm new with ajax and cant approach it.
this is what I've made:
the js code (inside the proper .tpl):
<script>
$( ".droptrue" ).droppable({
drop: function( event, ui ) {
//add <option> tag when an attachment is dropped to category's select
$(event.target).append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>');
//remove the <li> wich contained the attachment data
ui.draggable.fadeOut("slow").remove();
var val = $('#categoryAttachmentArr').val();
//var tab = val.split(',');
//for (var i=0; i < tab.length; i++)
//if (tab[i] == $(this).val())
// return false;
//create an array with the next format: 'id_category(1)'-'id_attachment(1)','id_category(2)'-'id_attachment(2)'[....]
//the comma will be the main character that will be splitted
$('#categoryAttachmentArr').val(val + ui.doppable.attr('id') + '-' + ui.draggable.attr('id') +',');
}
});
$('#submitAddProduct').click(function(e){
$.ajax({
type: 'POST',
url: baseDir + 'modules/adjuntos/classes/CategoryAttachment.php',
data: {
ajax: true,
action: \'CategoryArray\',
cat_array: $('#categoryAttachmentArray').val(),
}
dataType: 'json',
success: function(json) {
console.log($('#categoryAttachmentArray').val());
}
});
})
$( ".ui-state-default" ).draggable({
revert: "valid",
});
</script>
And my class:
class CategoryAttachment extends Objectmodel
{
//other functions
public function ajaxProcessCategoryArray()
{
$CategoryAttachmentArr = Tools::getValue('cat_array')
}
}
you can't connect directly to any class. you have to use the controller to do this.
Ajax send data to controller
Controller save data using class
Controller return result to browser (javascript)
Finaly I got the solution, maybe one of you guys will have this problem in the future.
My code in the .tpl:
$( ".ui-state-default" ).draggable();
$( ".droptrue" ).droppable({
drop: function( event, ui ) {
//add <option> tag when an attachment is dropped to category's select
$(event.target).append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>');
$('#selectAttachment1').append('<option value="' + ui.draggable.attr('id') + '" selected>'+ui.draggable.text()+'</option>')
//remove the <li> wich contained the attachment data
ui.draggable.fadeOut("slow").remove();
var val = $('#categoryAttachmentArr').val();
//make a serialize() type array
$('#categoryAttachmentArr').val(val + $(this).attr('id') + "=" + ui.draggable.attr('id') +"&");
var value = $('#arrayAttachments').val();
var tab = value.split(',');
for (var i=0; i < tab.length; i++)
if (tab[i] == ui.draggable.attr('id')){
return false;
}
$('#arrayAttachments').val(value+ui.draggable.attr('id')+',');
}
});
$('#submitCategories').click(function(e){
var array = $('#categoryAttachmentArr').val()
$.ajax({
url: '../modules/adjuntos/ajax-call.php',
data: {
action: 'handlearray',
token:new Date().getTime(),
cat: array
},
method: 'POST',
success:function(data){
$('#result').html(data);
}
});
});
the ajax call goes to my ajax-call.php file:
<?php
//load ps config
require_once(dirname(__FILE__).'../../../config/config.inc.php');
require_once(dirname(__FILE__).'../../../init.php');
require_once('adjuntos.php');
//adjuntos.php is the name of my module main file
if(Tools::getIsset('token') && Tools::getIsset('action'))
{
$mp = new Adjuntos;
echo $mp->handleArray();
}
The handleArray function in my module main file:(it make a call to my custom class)
public static function handleArray()
{
$html = '';
$array = Tools::getValue('cat');
$arrayExplode = explode("&", $array);
foreach($arrayExplode as $value)
{
$finalArr = explode("=", $value);
if (!CategoryAttachment::postProcess($finalArr))
{
$html .= '<p style="color:red;>Fallo</p>"';
}
}
$html .= '<p style="color:green;>Correcto</p>"';
return $html;
}
The function in my custom class:
public static function postProcess($finalArr)
{
return Db::getInstance()->execute(
'UPDATE ps_attachment SET id_category = '.$finalArr[0].' WHERE id_attachment = '.$finalArr[1]
);
}//end
This way is working like a charm, and make the code more scalable

How to assign option value for select after ajaxcall

I have this html:
<select id="test"></select>
And This ajax code:
<script>
function get(name){
if(name=(new RegExp('[?&]'+encodeURIComponent(name)+'=([^&]*)')).exec(location.search))
return decodeURIComponent(name[1]);
}
//url: localhost/web/index.php?name='whatever'
var value = get('name');
$(document).ready(function(){
$('select').select2();
$.ajax({
type: "POST",
url: 'getValues.php',
data: {'test': $("#test").val(),'isAjax':true},
dataType:'json',
success: function(data) {
var select = $("#test"), options = '';
select.empty();
for(var i=0;i<data.length; i++)
{
options += "<option value='"+data[i].id+"'>"+ data[i].name +"</option>";
}
select.append(options);
}
});
});
</script>
I need to set the value of select as taken from the url,which is (var value).
The value is working fine,as I tested it in alert.
Any help is appreciated
1) You can use .val() after appending options:
select.append(options);
select.val(value);
2)
or add attribute selected to option having same value while building the options html string.
options += "<option value='"+data[i].id+"' "+(data[i].id == value ? "selected" : "") +">"+ data[i].name +"</option>";
Chances are its the AJAX that is causing the issue. you need to trim() the response to remove a whitespace at the end of the returned data. Try the following :
success: function(data) {
var response = data.trim(), select = $("#test"), options = '';
select.empty();
for(var i=0;i<response.length; i++)
{
options += "<option value='"+response[i].id+"'>"+ response[i].name +"</option>";
}
select.append(options).val(value);
}
My problem is solved.
The problem was that the returned value has space,which is taken from url as +
So I replaced "+" by " "
Thanks all !

Getting the returned variables from an executed JavaScript/jQuery function

I have this simple code as part of a PHP file, the purpose of this code is to execute the job1.js file on the client side (has to be done so), in this file I have a function called job1() that returns 3 variable back. The returned variables must be passed to the Server for further work.
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script type = "text/javascript" >
$(document).ready(function() {
// $jobJSPath[0] holds the path to the job1.js file
var scriptPath = "<?php echo $jobJSPath[0]; ?>";
$.getScript(scriptPath, function(data, textStatus, jqxhr) {
// Call the function
job1();
window.alert( data ); // Data, actually it has only the content of the file as a string
window.alert( textStatus ); // Success
window.alert( jqxhr.status ); // 200
});
});
</script>
The function is being executed without any problems, it’s doing some internal string operations (very boring :) ) and returns 3 variables back.
My question is how do I get the 3 return variables from the job1() function with their input back. I searched a lot and even tried
var result = eval('(' + data + ')');
console.log(result);
Because the data variable holds the function as a string but still without any success, this option was suggested on some other page on this site.
EDIT: the data and the job1 have same text:
´function job1() {
var text = "";
var vocabulary = "ABCDEFGHIJKLMNOPQRSTUVWXYZ abcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 1; i <= 500; i++) {
text += vocabulary.charAt(Math.floor(Math.random() * vocabulary.length));
}
var subText1 = text.slice(0, Math.floor(Math.random() * text.length));
var subText2 = text.slice(subText1.length, text.length);
//test for output
alert("This is JavaScript");
var nextJob = "job2, job3";
var prevJob = "null";
return {
text_RT : text,
subText1_RT : subText1,
subText2_RT : subText2
};
}´
java script is for the client side, php is for the server side, just use ajax call and pass the data using post, after job1() is done and you got the returned array, just use an ajax call like this:
var yourdata=job1();
var postdata= [{"1": yourdata[0], "2": yourdata[1], "3": yourdata[2]}];
$.ajax({
type: POST,
data: postdata,
url: "test.php", //stands for the php file you want to send the data to
}).done(function() {
//do something.....
})
on the server side fetch the data using $_POST["1"] for example
Well that what I have until now
<script type = "text/javascript" >
$(document).ready(function() {
// $jobJSPath[0] holds the path to the job1.js file
var scriptPath = "<?php echo $jobJSPath[0]; ?>";
$.getScript(scriptPath, function(data, textStatus, jqxhr) {
// Call the function
var job = job1();
window.alert( data ); // Data, actually it has only the content of the file as a string
console.log(job); // shows all the return parameters from job1();
window.alert( textStatus ); // Success
window.alert( jqxhr.status ); // 200
// push the return parameters into result array
var result = [];
$.each(job, function(index, value) {
//window.alert(index + ": " + value);
result.push(value);
});
// post the results back to the same page
$.ajax({
type: 'POST',
data: {result : result},
url: 'executedJobs.php',
}).done(function(data) {
var redirectUrl = "executedJobs.php";
var form = $('<form action="' + redirectUrl + '" method="post">' +
'<input type="hidden" name="result" value="'+ data +'" />' +
'</form>');
$('body').append(form);
$(form).submit();
});
});
});
</script>
And after that to get the results on the the executedJobs.php page I used
<?php
$myArray = $_REQUEST['result'];
echo "myArray:<br/>";
print_r($myArray);
?>
It works that way, the only thing is I get the word myArray echoed twice every time before the print_r($myArray);.

How do you input a javascript variable into php function using ajax?

What am I doing wrong here?? Everything works fine and there are no errors in the console but there are also no console logs saying it succeeded
index file with script:
<script type="text/javascript">
function upVote(picNum)
{
var pictureNumber = parseInt($("#" + picNum).attr("id"));
$.ajax({
url: "upload/pics/changeVote.php",
data: {"picNum":pictureNumber},
type:'post',
dataType:'json',
success: function(output_string){
PictureNumber = output_string['picturenumber'];
alert(PictureNumber);
}
});
var currentVote = parseInt($("#" + picNum).attr("value"));
alert("pictureNumber is " + pictureNumber + "and currentVote is " + currentVote); //here to help me, no functionality
$newVote = currentVote + 1;
alert($newVote); //here to help me
}
</script>
/upload/pics/changeVote.php
<?php
$picNum = $_POST['picNum'];
function otherFileFunc($pic){
$final = $pic + 1;
return $final;
}
$outputnumber = function($picNum);
$array = ('picturenumber' => $outputnumber);
echo json_encode($array);
?>
Mistake in /upload/pics/changeVote.php
$outputnumber = function($picNum);
has to be:
$outputnumber = otherFileFunc($picNum);
you can't use function(), you should use the function name instead.

Ajax returning an undefine value

I have a search function that is suppose to search a name from the database, and then when the user clicks add, the item choosen has to appear below the search field, in short it has to be posted back so that the user can re-select his/her second option from the search element so that all the selected options can be saved in the database. The problem im facing is that after I click add im getting undefined value back instead of the one I choose and my response is a name instead of an Id number, here is my code and a picture below.
MODEL
public function getName($id)
{
$select = $this->select()
->where('service_provider_id LIKE "' . $id . '%"')
->order('service_provider_name');
return $this->fetchAll($select);
}
CONTROLLER
{
$id = $this->getRequest()->getParam('id');
$mdlserviceprovider = new Model_ServiceProviders();
$serviceprovider = $mdlserviceprovider ->getName($id);
$arr_rtn = array();
if (count($results) > 0){
foreach($results as $result)
{
$myarr = array( 'label' => $result->service_provider_name,
'value' => $result->service_provider_name,
'id' => $result->service_provider_id
);
array_push($arr_rtn, $myarr);
}
}
echo Zend_Json::encode($arr_rtn);
}
PHTML/AJAX
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
var row = '<tr><td>' + data["serviceprovider"] + '</td></tr>';
$('#t1').append(row);
//alert();
}
});
});
Thanks in advance
You can use data["value"] instead of data["serviceprovider"]:
var row = '<tr><td>' + data["value"] + '</td></tr>';
Since you've encoded the array which contains three keys: label, value and id. So there's no serviceprovider key at this moment for Zend to encode.
You are looking for a key that doesn't exist in the array you are returning try this
var row = '<tr><td>' + data['label'] + '</td></tr>';
Or this
var row = '<tr><td>' + data['value'] + '</td></tr>';
As those are the two keys you defined in your PHP page
Try
var row = '<tr><td>' + data[0].value + '</td></tr>';
Also try to put an alert() in the success function like,
alert(JSON.stringify(data));
and see what is included in it..
From what I see I think you are ruturning a multidimensional array from php so I would try something like this in javascript:
$('#add1').click(function(){
var data = {};
data['sp'] = $("#search").val();
$.ajax({
url:'<?php echo $this->baseUrl()?>/ajax/postserviceprovider/id',
type:'post',
dataType: "json",
data: data,
success:function(data){
data.each(function(index, el){
var row = '<tr><td>' + el.label + '</td></tr>';
$('#t1').append(row);
//alert();
}
}
});
});
In your controller try:
$this->disableLayout();
$this->_helper->viewRenderer->setNoRender(true);
return $this->_helper->json(array('key1' => $val1, 'key2' => $val2, ...));

Categories