Ajax.request not working - ajax

I am sorting a list using scriptaculous, i can't get the ajax request part to work.
This is my code:
<script type="text/javascript">
Sortable.create("images_list", {
onUpdate: function() {
var list = Sortable.serialize("images_list");
alert(list);
new Ajax.Request('processor.php', {
method: 'post',
parameters: { data: list }
});
}
});
I Have alerted out the serialize string, this part is working fine:
images_list[]=18&images_list[]=19&images_list[]=21&images_list[]=22&images_list[]=20
So the sorting is working fine, however the data string doesn't seem to be available in the processor.php
<?php
//Connect to DB
require_once('connect.php');
parse_str($_POST['data']);
for ($i = 0; $i < count($images_list); $i++) {
$id = $images_list[$i];
mysql_query("UPDATE images SET ranking = '$i' WHERE id = '$id'");
}
?>
Any ideas why the data is not getting posted? I have tested to see if the processor.php page is actualy being invoked, and it is.
Thank you

When method = 'post', you need to use "postBody" instead of "parameters" for having parameters posted to your server side script

Related

How can I get the results of two SQL-Queries in PHP in one JS function with AJAX?

I am a complete beginner and I hope that you can help me.
In my php file I make two different database queries and I need their results for calculations in a js function, which in turn should be displayed in the browser.
If I try to display the results from both queries, only "undefined" is returned. However, they are displayed to me in the console, where I also have the numbers output via consol.log (data). I am trying this with the help of ajax. If I remove the part from the second DB query in my function, it works. Unfortunately not all together. What am I doing wrong? Is what I plan to do even possible or do I have to take a detour? If yes, which one?
Here is my previous code:
Javascript:
function clickPHPtoJS(){
$.ajax({
url: "index.php",
type: "POST",
success: function(data) {
console.log(data);
clickPHPtoJSResponse(data);
},
error: function (data) {
console.log("Daten nicht erhalten");
}
});
}
function clickPHPtoJSResponse(data) {
// Antwort des Server ggf. verarbeiten
var response = JSON.parse(data);
var einer = response.einer;
var zwoelfer = response.zwoelfer;
var anzahl = response.nr;
document.getElementById("lab1er").innerHTML = einer + " " + zwoelfer + " " + anzahl;
}
PHP:
<?php
require 'inc/db.php';
$erg = $db->query("SELECT id, sender FROM packaging_log WHERE sender='test' AND packaging='1er'")
or die($db->error);
$gesteigereiner = $db->query("SELECT * FROM geliefert WHERE 1")
or die($db->error);
while ($zeile = $gesteigereiner->fetch_object()) {
$einer = $zeile->test1er;
$dreier = $zeile->test3er;
$sechser = $zeile->test6er;
$zwoelfer = $zeile->test12er;
}
$geliefert = array ( "nr" => $erg->num_rows,
"einer" => $einer,
"zwoelfer" => $zwoelfer);
print_r (json_encode($geliefert));
?>
Unfortunately, that's not how it works. But if I completely remove the result from the first DB query in the JS.
Many thanks in advance. I am grateful for any information, clarification and tips.
The problem was the following: "nr" => $erg->num_rows
To get what I wanted I had to save $erg->num_rows as a variable and to put the variable into the array.
So first step: $nr= $erg->num_rows;
Second step: "nr" => $nr

Ajax multiple response

I need to fetch the names using mysql query for which I'm trying to send some values via ajax to php.
Js file:
var dataselect = 'catg='+ $('#catg_list').val() + '&brand='+ $('#brand_list').val(); // get data in the form manual
$.ajax({
type="POST",
url:"check.php"
data: dataselect,
success: function(data) {
alert (data);
}
});
check.php file
<?php
include(database connection);
$catg_list= $_POST['catg'];
$brand_list= $_POST['brand'];
if ($catg_list!="") {
$catg_query = mysql_query("SELECT name FROM categories WHERE id='$catg_list'");
if ($catg_query) {
while ($row_catg=mysql_fetch_assoc($catg_query)) {
echo $row_catg['name'];
}
}
}
if ($brand_list!="") {
$brand_list = mysql_query("SELECT name FROM brand WHERE id='$brand_list'");
if ($brand_list) {
while ($row_brand=mysql_fetch_assoc($brand_list)) {
echo $row_brand['name'];
}
}
}
?>
Problem is I need to display both the above names separately in . Is it possible? I am very much new to ajax. Any help would be great.
Thanks
You should be sending your data back in JSON format. You can send back a JSON object, which is like an associative array in PHP. You could use this php code:
<?php
include(database connection);
$catg_list= $_POST['catg'];
$brand_list= $_POST['brand'];
$results = array('categories' => array(), 'brands' => array());
if ($catg_list!="") {
$catg_query = mysql_query("SELECT name FROM categories WHERE id='$catg_list'");
if ($catg_query) {
while ($row_catg=mysql_fetch_assoc($catg_query)) {
$results['categories'][] = $row_catg['name'];
}
}
}
if ($brand_list!="") {
$brand_list = mysql_query("SELECT name FROM brand WHERE id='$brand_list'");
if ($brand_list) {
while ($row_brand=mysql_fetch_assoc($brand_list)) {
$results['brands'][] = $row_brand['name'];
}
}
}
echo json_encode($results);
?>
Then, in your javascript success function, your data variable will be an object with two fields, each containing an array.
{
categories: [],
brands: []
}
You can access them by iterating over data.categories and data.brands.
Lastly, do not use SQL statements with data straight from your $_POST array. You have to sanitize that.
js
var dataselect = 'catg='+ $('#catg_list').val() + '&brand='+ $('#brand_list').val(); // get data in the form manual
var x, y;
$.ajax({
type="POST",
url:"check.php"
data: dataselect,
success: function(data) {
var x = data.categories[0];
var y = data.brand[0];
}
});

Bootstrap Typeahead with AJAX source (not working)

I'm trying to implement a search bar dropdown using bootstrap v3.0.0 with typeahead.js.
My search bar will take a student's firstname and lastname. I'm using a MYSQL database which consists of a table called practice with afirstname, alastname, aid as columns. The search bar should not only contain the firstname and lastname in the dropdown, but also the id associated with it in a second row. I've read all the examples on the typeahead.js page and I'm unable to do it with ajax call.
Below is the code of my index.php
JS
<script type="text/javascript">
$(document).ready(function() {
$('.cr.typeahead').typeahead({
source: header: '<h3>Select</h3>',
name: 'accounts',
source: function (query, process) {
return $.getJSON(
'localhost/resultly/source.php',
{ query: query },
function (data) {
return process(data);
});
});
});
</script>
HTML:
<body>
<div class="container">
<br/><br/>
<input type="text" name="query" class="form-control cr typeahead" id="firstname" />
<br/><br/>
</div>
</body>
Code for source.php : This should return the firstname and lastname from my database in the form of a json string or object?
<?php
$query = $_POST['query'];
try {
$conn = new PDO('mysql:host=localhost;dbname=practice','root','');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
$stmt->execute();
}
catch (PDOException $e) {
echo 'ERROR:' . $e->getMessage();
}
foreach ($stmt as $row) {
$afirstname[] = $row['afirstname'];
$alastname[] = $row['alastname'];
}
echo json_encode($afirstname);
echo json_encode($alastname);
?>
result:
http://oi41.tinypic.com/50moi1.jpg
Nothing shows up. I've tried adding a prefetch:
prefetch: {
url: 'localhost/resultly/source.php',
filter: function(data) {
r1 = [];
for (var i = 0; i < data.length; i++) {
r1.push({
value: data[i].afirstname,
tokens: [data[i].afirstname, data[i]alastname],
afirstname: data[i].afirstname,
alastname: data[i].alastname,
template: '<p>{{afirstname}} - {{alastname}}</p>',
});
}
return r1;
}
}
Please do provide a solution or an example which I could refer.
Update:
The source.php should return a list of json encoded data. I debugged by looking at the output that the source.pho created. What I did wrong was whenever I was supposed to put a url I did localhost/source.php instead of just source.php.
Solution provided by Bass Jobsen works and now I have run into another problem.
I'm using
if(isset($_POST['query']))
{ $q_uery = $_POST['query'];
$query = ucfirst(strtolower($q_uery))};
to take the user's data and use it for searching logic
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
The updated source.php is http://pastebin.com/T9Q4m10g
I get an error on this line saying Notice: Undefined variable: stmt I guess the $query is not being initialized. How do I get this to work. Thanks.
Update 3
I used prefetch: instead of 'remote:' that did all the matching.
Your return is not correct:
echo json_encode($afirstname);
echo json_encode($alastname);
See for example Twitter TypeAhead.js not updating input
Try echo json_encode((object)$stmt);, see: typeahead.js search from beginng
Update
I tried echo json_encode((object)$stmt);still doesn't work.
Do you use any kind of debugging? What does? source.php return? Try to follow the steps from
typeahead.js search from beginng without the filter.
html:
<div class="demo">
<input class="typeahead" value="" type="text" spellcheck="off" autocomplete="off" placeholder="countries">
</div>
javascript:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10
});
php (source.php):
<?php
$people = array();
$people[] = array("lastname"=>"Inaw",
"firstname"=>"Dsajhjkdsa");
$people[] = array("lastname"=>"Dsahjk",
"firstname"=>"YYYsgbm");
$people[] = array("lastname"=>"Dasjhdsjka",
"firstname"=>"JHJKGJ");
$datums = array();
foreach($people as $human)
{
$datums[]=(object)array('value'=>$human['firstname'],'tokens'=>array($human['firstname'],$human['lastname']));
}
echo json_encode((object)$datums);
This should work
update2
Thanks, it worked. How do I display 2 or more 'value'?
add some values to your datums in source.php:
foreach($people as $human)
{
$datums[]=(object)array
(
'value'=>$human['firstname'],
'tokens'=>array($human['firstname'],$human['lastname']),
'firstname'=>$human['firstname'],
'lastname'=>$human['lastname']
);
}
firstname and lastname now are field you csn use in your templates
Add a template and template engine to your javascript declaration:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10,
template: [
'<p>{{firstname}} - {{lastname}}</p>'
].join(''),
engine: Hogan
});
The above make use of https://github.com/twitter/hogan.js. You will have to include the template engine by javascript, for example:
<script src="http://twitter.github.io/typeahead.js/js/hogan-2.0.0.js"></script>
It is working for me. please follow below step.
Please add below Js and give proper reference.
bootstrap3-typeahead
--- Ajax Call ----
$("#cityId").keyup(function () {
var al = $(this).val();
$('#cityId').typeahead({
source: function (valuequery, process) {
var states = [];
return $.ajax({
url: http://localhost:4000/GetcityList,
type: 'POST',
data: { valueType: "", valueFilter: valuequery },
dataType: 'JSON',
success: function (result) {
var resultList = result.map(function (item) {
states.push({
"name": item.Value,
"value": item.Key
});
});
return process(states);
}
});
},
});
});
---- Cs Code ---
public JsonResult SearchKeyValuesByValue(string valueType, string valueFilter)
{
List<KeyValueType> returnValue = SearchKeyValuesByValue(valueType, valueFilter);
return Json(returnValue);
}
Auto suggest of Bootstrap typehead will get accept only "name" and "value" so create reponse accordinly

Basic implementation of ajax in magento

I am a newbie in magento and trying to implement ajax,but can't find a proper tutorial to follow. Could anyone provide me some reference or guide me to where i would be able to find it?
Don't know a tutotial but I can explain you bit what I implemented in a project a month back.
I created a controller on which we can fire an AJAX request on a specific action. In this case the getoptionsAction in the IndexController of our custom Offerte module.
The getoptionsAction in my controller takes a product_id and loads the options for the product. It builds the HTML and echo's this on function end.
In phtml file I have following code to invoke the AJAX request and update html-object in frontend:
function get_options(prod_id){
var product_options = $('product_options');
var prod_id = $('product').getValue();
new Ajax.Updater('product_options',
'<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); ?>offerte/index/getoptions',
{ method: 'get',parameters: {prod_id: prod_id, type: 'get_regular_options' } ,
onCreate: function(){
$('loading-img-options').show();
},
onComplete: function (t) {
$('loading-img-options').hide();
$('product_options').show();
}
});
}
the above function uses Ajax.Updater. You can also use Ajax.Request to get the result to juggle with.
function stripslashes(str) {
return str.replace(/\\'/g,'\'').replace(/\"/g,'"').replace(/\\\\/g,'\\').replace(/\\0/g,'\0');
}
function get_products(){
product = $('product');
cat_id = $('category').value;
new Ajax.Request('<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB); ?>offerte/index/getproducts',
{method: 'get', parameters: {cat_id: cat_id, mode: 'offerte'},
onCreate: function(){
$('product-loading').show();
$('product_options').hide();
},
onSuccess: function(t) {
resp = jQuery.parseJSON(t.responseText);
$('prod-container').innerHTML = resp.options ? stripslashes(resp.options) : '<?php echo $this->__('No options found') ?>';
$('product-loading').hide();
}
});
}
(please note I use JQuery to parseJSON. You can also use String.evalJSON, but I was lazy here :-)
Using Ajax.Request you need to return the result from the controller as JSON. I used the code below in my controller to return JSON to our phtml to use in the onSuccess Callback function above:
$this->getResponse()->setBody(Zend_Json::encode($result));
Hope this is of any help

AJAX call each() and find() application

The message alert does not appear after the post call under ajax.
Given the following ajax call:
var val= 1;
$.post("ajax.php", { information: val }, function(result)
{
$(result).find("div").each(function()
{
if($(this).text()=="OK")
{
alert("OK");
}
});
});
and the ajax.php file:
<?php
if($_POST['information']==1)
{
?><div>You must fill all the fields</div><?php
?><div>The title must be between 10 and 30 characters</div><?php
?><div>Please insert your email in the field</div><?php
?><div id="answer">OK</div><?php
}
?>
Thanks for your help!
EDIT: corrected errors found by Benny. corrected post syntax and $(result) syntax
In your example you have faulty $.post syntax.
$.post("ajax.php"), { information: $val }, function(result){
// Callback code
});
The correct syntax would be.
$.post("ajax.php", { information: $val }, function(result){
// Callback code
});
Also using $ as part of the $val variable name is confusing. It can trick developers into thinking that it has something to do with the jQuery variable, even though it's just part a local variable name. I would recommend doing just...
var val = 1;

Resources