Populating select list from AJAX JSON result data - php

Hello stackoverflow developer,
First of all, sorry if I couldn't find a solution, but I've been trying for a while now.
I'm not sure if my approach is the best one, so, if there's an alternative to AJAX and/JSON, please feel free to suggest it.
I'm creating a tourist guide website where registered users will include their resorts, restaurants and tourist attractions according to region and state. I'm using Joomla! and Seblod for this (with some custom PHP, MySQL, Javascript and AJAX). Since I don't want to manually create 27 dynamic selects, I've been trying selecting the list of registered beaches (to which resorts and tourist attractions must be related to) with PHP/AJAX/JSON/JQuery.
Everything works except populating the beach list, and I don't know what the problem is. I've tried multiple ways to append, create or add the options but nothing happens.
The PHP/JSON result is :
`
[{"id":"17","title":"Porto+de+Galinhas"},{"id":"18","title":"Serrambi"},{"id":"19","title":"Tamandar%E9"}]
`
It's the result of this PHP script:
`
if($_GET['q'] == 'beaches'){
$praiaSQL = sprintf("SELECT * FROM vp_content AS c LEFT JOIN vp_cck_store_item_content AS v ON c.id = v.id WHERE c.catid = 10 AND v.cck = 'praia' AND v.venue_state = '%s' ORDER BY c.title ASC;", $_GET['s']);
$query = mysqli_query($connection, $praiaSQL);
$praia = array();
while($results = mysqli_fetch_assoc($query)){
array_push($praia, array('id' => $results['id'], 'title' => urlencode($results['title'])));
}
echo json_encode($praia);
}
`
I also need a solution to handle accented characters. I'm trying urlencode here and decode in the JQuery, but may be the problem. When I left it as the original data, when there were accented characters the result item was empty.
This is the relevant JQuery that handles the result (where x = the select and u = the URL to get the AJAX JSON result - I've commented where the problem is in the code):
`
function setBeachList(x,u){
var theDiv = "#cck1r_" + x;
var theSelect = "#" + x;
$j(theSelect).children("option:not(:first)").remove();
$j.ajax({
url: u,
contentType: "application/json;charset=UTF-8",
success: function(data){
if(data.length){
/****
This is where I'm stuck, as I can't find a way to make sure the
data is actually being treated/handled.
I've tried alerts and all sorts of other options to populate the
select.
I know it's being called because the before: and after: functions
are working.
*****/
/*
$j.each(data, function(k, v){
var o = new Option();
var newTitle = urldecode(v.title);
$j(o).html(newTitle).val(v.id);
$j(theSelect).append(o);
});
*/
var htm = '';
for (var i = 0; i '+urldecode(data[i].title)+'';
}
$j(theSelect).html(htm);
}
},
beforeSend: function(){
$j(theDiv).hide();
},
complete: function(){
$j(theDiv).show();
},
dataType: 'json',
});
}
`
Thank you for the time and patience, I'm not an expert at any of this (not exactly a newbie, but close...).

urldecode is not a javascript function,
you can use decodeURIComponent instead of it.
it's working when you change it,
http://jsfiddle.net/MzMPK/1/
UPDATE:
I think your problem is about trying to encode accented chars, It should work without encoding them, if your all encodings are set as UTF-8.

This is a common JSON parsing silent error.
If the JSON is not well formatted, the ajax request will fail silently.
The second most common cause of this problem is the encoding. Make sure you are using UTF-8 in the page you're calling the AJAX and on the script that returns the data.
Your problem with accented data can be resolved by not encoding the data on the server side, thus not needing to unenconde on the client side.

To answer my own question:
Since I'm not and AJAX/JSON expert, I don't know if it's the expected behavior, but the responding page, which generates the AJAX result, cannot have different data than the one expected. Since I had left a regions' output, the requesting page had problems dealing with it somehow. Once I removed the unnecessary data, the select list got updated fine.
That was something I forgot to mention in my post, because I assumed that it was fine to have more than one result in the page. Using Firebug to check the code, the request was being brought fine.
Thank you all for your time, and sorry for the inconvenience...
I had to add htmlentities to the responding page, as accents returned null, although I explicitly have UTF-8 on every file...

Related

Send multiple AJAX data to PHP and update Mysql database

i am tying to build an application where user can reorder items (and save the order to database). The items user is reordering are navigation links, which are generated dynamically on the page from php loop:
$nav_links.='<li class="collection-item ui-state-default item" data-ord="'.$navorder.'" data-url="'.$pageurlname.'"><a>' .$pagename. '</a></li>';}
$navorder is order of the page in the navigation
$pageurlname is string which is used to call the page dynamically (index.php?page=$pageurlname) and is unique key in the table.
I am using jqueryUi sortable funcion to make the process drag & drop, it is working fine and each time i reorder the links, the new order is updated to "data-ord".. the sript:
$('#sortable').sortable({
stop: function(event, ui){
$(".sortable li").each(function(i, el){
$(el).attr('data-ord',$(el).index()+1);
});
}
});
Now to the problem, which is my ajax script:
$(document).on('click','.saveorder',function(){
var neworder = $('.collection-item').attr('data-ord');
var pgurl = $('.collection-item').attr('data-url');
$.ajax({
type:'POST',
dataType:'text',
url:'/rs/pages/nav_order.php',
data: { neworder:neworder, pgurl:pgurl },
success: function(data) {console.log(data); $('#response').html(data);},
error: function(data) {console.log('Error!', data); }
});
});
I am new to ajax, so it is mostly build on scripts i found in other quiestions here. (I was able to succesfully implement cript link this to my other functions) however it is not working in this case. The problem seems to be that i am trying to post multiple data for multiple rows (At this time i have 4 links i am trying to reorder, but the link count can be more or less). When i tried to get values of variables "neworder" and "pgurl" (using alert), it always show only the values for the first item.
I have tried lot of solutions found in similar quiestion but none of them worked, simply because user were posting form data and then serialized it, which is not my case because i am not sending data from the form.
Lastly here is the nav_order.php (i guess it is wrong here too, probably need to add foreach but at first i need to have the ajax working correctly):
<?php
include "/rs/include/db.php";
$neworder = $_POST['neworder'];
$pgurl = $_POST['pgurl'];
$query = mysqli_query($Connection, "UPDATE horus_pages SET nav_order='$neworder' WHERE url_name='$pgurl'") or die (mysqli_error($Connection));
echo 'Reordered';
?>
Also when i check the console, there is no data.
So please can you tell me how to correct the ajax script to send the data for each object and then handle it correctly in the php script? Hope i described my problem clearly. Thank you for any help.
Put data-id="your_database_id" in your links html. Selecting them in your database with href, will be slow and bug things if there are multiple records with the same href.
You have save button which sends the order and href of the first link it finds? And what happens when multiple items change their order? If you have many links, you will be throwing hundreds of mysql updates for each save?
You should be better off sending json to your php. Something like that:
[{id:123, order: 332}, {id:124, order:334}, ... ]
dataType:'text' becomes dataType:'json'
If you don't care about scalability, then this will work on the backend.
$data = file_get_contents("php://input");
$links = json_decode($data, true);
foreach($links as $link) {
$order = intval($link['order']);
$id = intval($link['id'])
// UPDATE table SET `order` = '$order' WHERE id = '$id'
}
Btw. Your php code allows SQL injection. Thats bad
Perhaps you can make the order 'float' and make an algorithm which finds empty spot. This will allow you to reduce these 100's of SQL requests to 1.

Searching a database based on a javascript variable

I am trying to execute a specific query where I search for the name that i get using javascript. I have this HTML:
<a onmouseover="showDef(textContent)" href="aLinkHere.com">myWord</a>
The function showDef gets the myWord and I'm trying to execute my query after that.
<script type="text/javascript>
function showDef(txt) {
var myWord = txt;
//Some code here to execute the query?
}
</script>
The query I want to have is as follows:
mysql_query("SELECT * FROM defs WHERE name='myWord'");
Now I have to replace the 'myWord' with the word stored in the javascript variable. Is there any way to this? I already tried the following, but that didn't work..
document.write('<?php $data = mysql_query("SELECT * FROM defs WHERE name=\''+ myWord + '\'"); ');
I am relatively new in javascript and php, so any help is very much appreciated!
Javascript is client side language and you need php (server side) lang to execute query.
Create ajax request with that variable and use that variable in your query.
return that response from your remote php file and catch response in javascript. And enjoy with response.
IF you are searching name only(exact) then use = else use LIKE or REGEXP for better performance
This is an example that uses the jQuery library.
var dataString = 'searchVar='+ myWord;
$.ajax({
type: "POST",
url: "ajax.php",
data: dataString,
cache: false,
success: function(data){
alert(data)
}
});
IN php code you jst get variable with $_POST['searchVar'] and execute your query
$qry = "SELECT * FROM defs WHERE name LIKE '%".'$myWord."%'";
and in while loop jst echo you response.
You're relatively new indeed, this is basic strings 101.
1) do NOT use document.write, it's not meant for you to be used, it's an API from a decade ago and doesn't do what you think it does. Find the element you want to set the content of (using document.getElementById or the like) and then use .innerHTML = ... to set its content.
2) To get your value in your query on the PHP side, just put it in there, it's one of the basic features of PHP:
$myword = sanitize_the_hell_out_of_this($_POST['myword'];
mysql_query("SELECT * FROM defs WHERE name='$myword'");
You can pick whatever method you like for sanitization, there are a few baked into PHP but do NOT, under ANY circumstance, pass the posted value straight to your database, unless you like people deleting your database because they can. Someone can just edit the html, change the single word to "'; drop table words; 'lo" and now your table will get dropped. fun times =)
In order for it to actually work, remember your page runs on the client's computer, and PHP is a server technology. So the javascript will have to ask the server for the data by literally asking the server: you'll need an AJAX get or post operation, and then work with the data that get back. You can't inject PHP code and then have it run on the user's computer.

jQuery (without $.ajax) $.POST+json retrieves "null" from PHP json_encode

My first time writing, but not the first here. I felt forced to ask here because none of those apparently alike questions here were able to give me a clear workaround or solution.
My projects involves a tic-tac-toe game, all jQuery, PHP and log file based. It's working fine, but for every information sent to the txt log, I have to star a new $.post to retrieve the information that will be displayed in different parts of the page, not all in a single list (specially O and X that are retrieved back to their original text element) ...
The game is real-time, multiplayer and is working fine, but is using two txt logs written by PHP which also manages the game: one log keeps the position (filled space) and the other what char was used (X or O). Nice, but I'm calling the two via $.post, storing their data in respective global variables and using them in a setInterval, to update on time for the other player. But as there are many other informations like name and remaining moves (from 9 to 1), I'd like to put everything in a single log, something easier to be retrieved all in a time and be displayed in their respective positions through the game page. My problem (now what I need to get working for now) here is retrieving them from PHP. During tests, I simulate three informations: position, char (O or X) and player's name, put them in an array and echo them with json_encode, as it follows (my jQuery post and then my PHP):
<script type="text/javascript" src="jquery.js"></script>
$.post ("json.php", {pos:"pos",weapon:"weapon",nome:"nome"}, function(data){
alert (data); //returns null...
//alert (data.pos); //nothing, script ignores execution
//alert (data[0].pos); //returns null...
//alert (data[1].pos); //returns null...
//alert (data[2].pos); //returns null...
//alert (data[3].pos); //returns null...
//tests above based on some suggestions I'fe found through the web, ineffective...
},"json");
And my PHP:
<?php
//Simulating values being received during the game:
$pos='s3'; //simulation player's move on slot 3
$weapon='O'; //player puts O on slot 3
$name= 'fulano';
//Putting general player info into the array to be used by jQuery:
$coord= array();
$coord['pos']= $pos; //Sets the position where the player put his char
$coord['weapon']= $weapon; //The "weapon" to be put in respective "pos"
$coord['nome']=$name; //Player's name to be displayed during the game
echo json_encode($coord); //encoded json is returning {"pos":"s3","weapon":"O","nome":"fulano"} nicely
?>
Both are post, both using json, jQuery returns something, but is null, PHP echoes alright... $.ajax simply didn't make it either...
What I need: that $.post retrieves every datum so that I can store one by one in their respective global variables, but if alert can't even show one of them coming, something's wrong. Changed every variable names to avoid any kind of conflict, not solved...
I made this test just to make sure PHP json would be clearly gotten by jQuery, what's not happening here. My HTML is using default charset, I'm testing it in localhost, I have the main project working perfectly here, this was a side test to test specifically json response. I simply had no success in using $.ajax ({}) (my jQuery is 1.7.1), no matter what, the script simply stops executing, PHP keeps responding alright here, but jQuery is not giving me what it should other than "null", I've tested it on FF15 and IE8, problem is just with my json routine on jQuery, PHP is working fine and my $.posts here and on the main project, too. What could be going wrong here? Why is it simply returning data as null regardless to what I may try? I thank everyone in advance, I'm just asking because there were no examples here and outside that really gave me the answer, and 99,9% depend on Ajax, but Ibelieve it can be simpler like this.
Add this to your code
$.post ("json.php", {pos:"pos",weapon:"weapon",nome:"nome"}, function(data){
$(data).each(function(){
alert(this.s3);
alert(this.0);
alert(this.fulano);
});
},"json");
Valid JSON is as follows: {"key":"value"} not {key:"value"}
Note: All quote encapsulated, not just the value. Hope that helps.

Jquery Autocomplete too slow

I have written this code what it does is if user types postcode or city name it fetches from database using like query now the problem is i have around 1260 records with two fields one is city and other is post code
SELECT code, area FROM post_codes WHERE code LIKE '$q%' or area LIKE '$q%' ORDER BY area LIMIT 4
i have read many questions posted by users and researched online as well but nothing works used query delay as well .i have even indexed both these fields in database as well .. its getting records too slow that is the first problem now my second problem is when user is in that text field for search and he presses tab he can bypass the search and write any invalid code he wants how to restrict that here is my code for reference.
$("#Postcode").autocomplete("get_codes2.php", {
width: 260,
queryDelay:0,
dataType: 'json',
parse: function(data) {
var array = new Array();
for(var i=0;i<data.length;i++)
{
array[array.length] = { data: data[i], value: data[i].areacode, result: data[i].areacode};
}
return array;
},
formatItem: function(row) {
return row.areacode;
}
}).result(function (){
I think Drupal's API search has a really nice approach to solving this problem. Their alternative to letting every incremental search hit the backend is to serve one big JSON file, which is used to autocomplete on client side.
In their implementation they're listening on the focus event for the search input, to fetch the JSON only when it's actually needed.

Sending PHP json_encode array to jQuery

ok, i guess I need help ! I searched with every keyword I could think off, but I still cant figure out, please help. Am more of a php guy, and I've just started with jQuery.
Basically, what I am trying to do is to send a jQuery post from a click function. And based on whatever is returned by my php function, show/hide 2 divs. My php function returns a "json_encode" array with 2 simple values, like such :
//==================PHP code ==================================
$message_for_user = "blah blah";
$calculatedValue = 1230;
$responseVar = array(
'message'=>$message_for_user,
'calculatedValue'=>$calculatedValue
);
echo (json_encode($responseVar));
//==================PHP code End ==================================
My javascript code is supposed to accept the values returned by php :
//==================Javascript code ==================================
$("div.calculator_result").click(function()
{
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}
}
//==================Javascript code End ==================================
Unfortunately, on the javascript side of my project, the divs are not updated with the values returned by my php functions .... where am I wrong? I hope I was clear in my question, if not, do let me know, and I shall provide any extra info required.
Another thing is that earlier, I was echo'ing only a single value, that is the calculated value (echo $calculatedValue), and everything worked fine, its only after I shifted to echo'in the json encode array that things dont work
var json = $.parseJSON(response); alert(json.message);
Try setting the dataType option:
$.post('myCalculator.php' ,{qid:itemID},function(response)
{
$("div.calculation_value").show(500).html(response['calculatedValue']);
$("div#message_for_user").show(500).html(response['message']);
}, 'json');
NB I have also added the closing brackets ) where you have missed them.
You must parse the JSON response. jQuery has this built-in functionality (thankfully, because otherwise IE6 and 7 don't natively support JSON). Set a variable equal to this:
$.parseJSON(response)
And then, if you're not familiar with JSON format, check the response headers (using Firebug or similar,) and that will help you pick which keys' values you want. If you're looping, I would look into for in statements once the response has been parsed.
EDIT: Using $.getJSON, the parsing is done automatically. Write less, do more. :)
All you gotta do, its tell the Ajax call that you're receiving data type "json". In other words...
$.ajax({
url: "external_file",
method:"post",
dataType: "json", // **************** Note dataType****************
success:function(response){
console.log(response)
// Response will be a javascript array, instead of a string.
},
error: function(){
alert('something went wrong.')
}
})

Categories