Ajax call not passing any POST values - php

I have a table that has sortable rows. The table is generated from a mysql database that has a field called "displayorder" that oders the table. When the user drags and drops rows, I want to use AJAX to submit those changes to the database whenever a user drops a row.
Currently, I can see the console.log() output from the success part of the AJAX call, and when i output the data there (order) it looks great, like this:
["order_1=1", "order_2=2", "order_4=3", "order_3=4"]
But according to Firebug, all that's getting passed in the $_POST is "undeclared".
How do I access that order variable from my indexpage_order.php file?
I have this jquery code:
<script>
$(document).ready(function() {
var fixHelper = function(e, tr) {
var $originals = tr.children();
var $helper = tr.clone();
$helper.children().each(function(index)
{
$(this).width($originals.eq(index).width())
});
return $helper;
};
var sortable = $("#sort tbody").sortable({
helper: fixHelper,
stop: function(event, ui) {
//create an array with the new order
order = $(this).find('input').map(function(index, obj) {
var input = $(obj);
input.val(index + 1);
return input.attr('id') + '=' + (index + 1);
});
$.ajax({
type: 'POST',
url: 'indexpage_order.php',
data: order,
error: function() {
console.log("Theres an error with AJAX");
},
success: function(order) {
console.log("Saved.");
console.log(order);
}
});
return false;
}
});
});
</script>
indexpage_order.php contains:
if(isset($_POST) ) {
while ( list($key, $value) = each($_POST) ) {
$id = trim($key,'order_'); //trim off order_
$sqlCommand =
"UPDATE indexpage
SET displayorder = '".$value."'
WHERE id = '".$id."'";
$query = mysqli_query($myConnection,$sqlCommand) or die (mysqli_error($myConnection));
$row = mysqli_fetch_array($query);
}
}

You can simply rewrite the js code that are generating the data for POST.
order = {}
$(this).find('input').map(function(index, obj)
{
return order[this.id] = index;
}
)
Rest should work in PHP.

Try $_REQUEST instead of $_POST on the PHP file for POST method with ajax.

convert the js array order to json object as ajax data needs to be in json using JSON.stringify. hence, it needs to be data:JSON.stringify(order), in the ajax function.
Or, use json_encode like this data: <?php echo json_encode(order); ?>, in the ajax function

order is an array. Convert the order to query string like this in your ajax script,
data: order.join('&'),

It looks like your sending your order in a JavaScript array
And when it arrives at your PHP, its unreadable.
If its an object look into the json_decode function.
If its an array, serialize the data before it goes, then unserialize on the php side.
PHP is unable to understand JavaScript array or objects unless they are encoded/serialized correctly.

Related

Ajax - variables are seen in chrome network tab but they don't seem to pass to the PHP function

I am trying to update a php function using ajax.
I Have an array stored in localstorage.
The array contains values of clicked id's.
When I click the <tr>, the array gets updated and sent via ajax from a js file to the php file.
js file
function storeId(id) {
var ids = JSON.parse(localStorage.getItem('reportArray')) || [];
if (ids.indexOf(id) === -1) {
ids.push(id);
localStorage.setItem('reportArray', JSON.stringify(ids));
}else{
//remove id from array
var index = ids.indexOf(id);
if (index > -1) {
ids.splice(index, 1);
}
localStorage.setItem('reportArray', JSON.stringify(ids));
}
return id;
}
//ajax function
$('table tr').click(function(){
var id = $(this).attr('id');
storeId(id);
var selected_lp = localStorage.getItem('reportArray');
console.log(selected_lp);
var query = 'selected_lp=' + selected_lp;
$.ajax({
type: "POST",
url: "../inc/updatelponadvdash.php",
data: { selected_lparr : selected_lp},
cache: false,
success: function(data) {
return true;
}
});
});
updatelponadvdash.php file
<?php
require_once 'inc.php';
$selected_lparr = json_decode($_POST['selected_lparr']);
foreach($selected_lparr as $value){
$dbData = $lploop->adv_lploops($value);
}
?>
Now, in the chrome network tab, when I click the and I dump_var($selected_lparr) the array is updated and I see the values like this:
For some reason I get a 500 error.
As well I dont understand why the var_dump(inside the function below) dosent work. I seems that the function adv_lploops dosent get the variables. but i dont understand why.
This is the fuction I call:
public function adv_lploops($value){
$sql = "SELECT * FROM `lptitels` WHERE titleidNo = '$value'";
$row = $sql->fetch(PDO::FETCH_ASSOC);
var_dump($row);
}
You aren't executing the sql query, try the following:
$sth = $db->prepare($sql);
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
note: you will need the $db object which is a connection to your database

webpage content not updated through json function(data)

I am trying to update a webpage on the fly after inserting some data in the db and returning a json object to no avail.
Let's say I have
<div id="try1"> try(<span id="votes1">0</span>)</div>
When loeaded the page displays the current number of votes, (0) at the moment.
then I have a button
<button onclick="vote(1);">+</button>
that calls this function:
function vote(votes_id)
{
var div = 'try' +votes_id;
var url = 'vote.php?id=' +votes_id;
var destination = '#votes' +votes_id;
$.getJSON( url, function(data) {
$(destination).html (data.votes);
});
}
my vote.php returns this json or after correctly updating the db or, at least that is what I think
{"votes":"1"}
However my webpage doesn't get updated from 0 to 1,
I use $data = json_encode($data);
the result of which as var_dump is:
string '{"votes":"1"}'
and
{"votes":"1"}
as echo $data.
What am I possibly missing?
That's because you are putting he success callback in the wrong place.
Use:
function vote(votes_id)
{
var div = 'try' +votes_id;
var url = 'vote.php?id=' +votes_id;
var destination = '#votes' +votes_id;
$.getJSON( url, {}, function(data) {
$(destination).html (data.votes);
});
}

posting array using ajax to the controller in cakePHP

I am relatively new to cake and I am struggling with a custom filter that im making in order to display products based on which checkboxes have been ticked. The checkboxes get populated based on which attributes the user creates in the backend, i then collect all the values of the selected boxes into an array with javascript and post it to the controller, but for some reason I cannot access the controller variable named '$find_tags' in my view, it throughs undefined variable.
Here is my javascript and ajax which collects and posts correctly (when i firebug it 'data' in my controller has array values which im posting) so thats fine
$("#clickme").click(function(event){
event.preventDefault();
var searchIDs = $("#checkboxes input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var contentType = "application/x-www-form-urlencoded";
var data = 'data[ID]='+searchIDs;
$.post("",data,function(data){
console.log(data);
});
});
Here is my controller code which im assuming is where the fault lies
if ($this->request->is('post') ) {
$data = $this->request->data['ID'];
$find_tags = array();
$selected_tags = $data;
foreach($selected_tags as $tag)
{
array_push($find_tags,$this->Product->findByTag($tag));
$this->set('find_tags', _($find_tags));
}
}
And here is my view code where i get Undefined variable: find_tags
foreach($find_tags as $all_tag)
{
echo $all_tag['Product']['name'];
echo '</br>';
}
Any help or suggestions would really be appreciated been struggling with this for a while now
If searchIDs is array of ids you just need to make the json of array and then send to your controller
$("#clickme").click(function(event){
event.preventDefault();
var searchIDs = $("#checkboxes input:checkbox:checked").map(function(){
return $(this).val();
}).get();
var contentType = "application/x-www-form-urlencoded";
var data = 'ids='+JSON.stringify(searchIDs);
$.post("controller url",data,function(data){
console.log(data);
});
});
On php side you are getting wrong variable
if ($this->request->is('post') ) {
$data = $this->request->data['ids'];
$find_tags = array();
$selected_tags = $data;
foreach($selected_tags as $tag)
{
array_push($find_tags,$this->Product->findByTag($tag));
}
$this->set('find_tags', _($find_tags));
}

jquery building array isn't working

I'm trying to build an array of data that will then be ajax using post to php - below is my code:
$('#mainBodySaveSubmitButtonProfilePhotoIMG').click(function() {
var profilePhotoArray = [];
$('.mainUnapprovedProfilePhotoWrapperDIV').each(function() {
var action = '';
alert( this.id );
if($('.mainUnapprovedProfilePhotoAttractiveIMG', this).is(':visible')) {
alert('attractive...');
action = 'attractive';
}
else if($('.mainUnapprovedProfilePhotoDeleteIMG', this).is(':visible')) {
alert('delete...');
action = 'delete';
}else{
alert('normal...');
action = 'normal';
}
profilePhotoArray[this.id+'_'+this.id] = action;
});
alert(profilePhotoArray.length);
for (i=0;i<profilePhotoArray.length;i++) {
console.log("Key is "+i+" and Value is "+array[i]);
}
$.post('scripts/ajax/ajax_approval_functions.php', {
'approvalProfilePhotos': '1',
'approvalProfilePhotosData': profilePhotoArray},
function(data) {
alert(data);
});
});
The if, else if, else section works fine as I can see the alerts.
When I try to alert the array length 'profilePhotoArray' it says 0 so I'm not populating the array correctly. Do I need to use .push()? I thought this format was ok?
Also do I need to do anything to the array before sending to php via ajax?
thankyou
** edit - I'm adding "profilePhotoArray[this.id+'_'+this.id] = action;" this.id twice just to prove this words as I will pass a second variable like this... am I better to use JSON for this?
Javascript arrays use numerical index, therefore your storage is failing. Use a javascript Object to store string based keys.
var lang=new Object();
lang["foo"]="Foo";
lang["bar"]="Bar";

Cannot populate form with ajax and populate jquery plugin

I'm trying to populate a form with jquery's populate plugin, but using $.ajax
The idea is to retrieve data from my database according to the id in the links (ex of link: get_result_edit.php?id=34), reformulate it to json, return it to my page and fill up the form up with the populate plugin. But somehow i cannot get it to work. Any ideas:
here's the code:
$('a').click(function(){
$('#updatediv').hide('slow');
$.ajax({
type: "GET",
url: "get_result_edit.php",
success: function(data)
{
var $response=$(data);
$('#form1').populate($response);
}
});
$('#updatediv').fadeIn('slow');
return false;
whilst the php file states as follow:
<?php
$conn = new mysqli('localhost', 'XXXX', 'XXXXX', 'XXXXX');
#$query = 'Select * FROM news WHERE id ="'.$_GET['id'].'"';
$stmt = $conn->query($query) or die ($mysql->error());
if ($stmt)
{
$results = $stmt->fetch_object(); // get database data
$json = json_encode($results); // convert to JSON format
echo $json;
}
?>
Now first thing is that the mysql returns a null in this way: is there something wrong with he declaration of the sql statement in the $_GET part? Second is that even if i put a specific record to bring up, populate doesn't populate.
Update:
I changed the populate library with the one called "PHP jQuery helper functions" and the difference is that finally it says something. finally i get an error saying NO SUCH ELEMENT AS
i wen into the library to have a look and up comes the following function
function populateFormElement(form, name, value)
{
// check that the named element exists in the form
var name = name; // handle non-php naming
var element = form[name];
if(element == undefined)
{
debug('No such element as ' + name);
return false;
}
// debug options
if(options.debug)
{
_populate.elements.push(element);
}
}
Now looking at it one can see that it should print out also the name, but its not printing it out. so i'm guessing that retrieving the name form the json is not working correctly.
Link is at http://www.ocdmonline.org/michael/edit_news.php with username: Testing and pass:test123
Any ideas?
First you must set the dataType option for the .ajax call to json:
$.ajax({dataType: 'json', ...
and then in your success function the "data" parameter will already be a object so you just use it, no need to do anything with it (I don't know why you are converting it into a jQuery object in your code).
edit:
$( 'a' ).click ( function () {
$( '#updatediv' ).hide ( 'slow' );
$.ajax ( {
type: "GET",
url: "get_result_edit.php",
success: function ( data ) {
$( '#form1' ).populate ( data );
},
dataType: 'json'
} );
$( '#updatediv' ).fadeIn ( 'slow' );
return false;
}
also consider using $.getJSON instead of $.ajax so you don't have to bother with the dataType
Try imPagePopulate (another jquery plugin). It may be easier to use:
http://grasshopperpebbles.com/ajax/jquery-plugin-impagepopulate/

Categories