I'm building a autocomplete with Twitter typeahead using an ajax JSON call to my PHP file to get some data but it keeps displaying the following in the dropdown result list:
undefined
undefined
undefined
but when i do:
alert(data);
I get the right data displayed but somehow the autocomplete list keeps displaying undefined, I've read and tried multiple things by some articles here on StackOverflow, but I can't seem to get it to work.
I have to following jquery code:
$('.item-name .typeahead').typeahead(null,{
source: function (query, process) {
$.ajax({
url: 'ajaxItems.php',
type: 'POST',
dataType: 'JSON',
data: 'query=' + query,
success: function(data) {
// alert(data);
process(data);
}
});
}
});
And my ajaxItems.php has the following code for testing purpose:
<?PHP
$results = array();
$results[] = 'jeans';
$results[] = 'sweater';
$json = json_encode($results);
print_r($json);
?>
The JSON output is as follows:
["jeans","sweater"]
I hope someone can shine some light on what I'm doing wrong or point me in the right direction.
edit
I am using the following typeahead file:
http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js
I had the exact same problem. To fix it I had to return an array containing key/value pairs with the key 'value' like this:
[{'value': 'first', 'value': 'second', 'value': 'third'}]
I don't think the typeahead docs make it clear enough but I believe it is the displayKey option which is set to 'value' by default.
The closest answer is ian's though it does not really work (only returns last value). Working answer is :
[{'value': 'first'}, {'value': 'second'}, {'value': 'third'}]
I had similar problems using source: and I ended up using remote:.
In your case, it would be something like this:
$('.item-name .typeahead').typeahead({
remote: 'ajaxItems.php?query=%QUERY'
});
Note that I deleted null on typeahead(null,{ since I think it's not necessary but I might be wrong. Obviously, you'll have to use $_GET instead of $_POST but I think it's much easier this way.
The problem is the typeahead is expecting a array with suggestions. Not the JSON !
use $.makeArray() like this:
success: function(data){
process($.makeArray(data));
}
if it doesn't , may be JSON.parse() should help ?
Mark it as answer if helpful :)
Related
I have ajax that calls a php file called "fetch_quarter_limit.php" from template file.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
var quarter_limit = data['myVar'];
alert(quarter_limit);
}
});
In my .php file i have tried to return the session data as an array.
Fetched the required data, stored in session and formed an array.
$_SESSION['quarter_limit_mend'] = $quarterLimit;
$returnVal = array('myVar' => $_SESSION['quarter_limit_mend']);
echo $returnVal;
As shown in above ajax code part, i tried to fetch it, but all i am getting is "undefined" when i output the variable using alert.
Please help.
Ajax code updated, p2 :
Adding dataType is making code not to work.
$.ajax({
type: 'POST',
url: 'fetch_quarter_limit.php',
dataType: 'json',
data: {
leavefrom: from,
leaveto: to,
empid: emp
},
success: function(data) {
alert(data);
}
});
As #Tim mentioned i have added custom json encode function to my .php file.
It returns as expected {"myVar": 2}
echo array_to_json($returnVal);
This is returned from php file.
But not able to access in ajax code.
You're using echo on an array, which is not possible. As described in the PHP manual
echo outputs one or more strings.
Usually you'd use json_encode() on your array and then output it to the screen. But as you've commented you are using php < 5. First of all, if possible, you should consider to upgrade to PHP > 7, as this not only improves performance, it also improves security.
If you can't upgrade to a PHP version above PHP 5, then you can use workarounds. On this question there is already an answer for the workaround, and the workaround can be found on the PHP manual itself.
You should be able to use the returned JSON data.
Reply for after your edit
So you have your data as JSON now, but JS will still see it as a string. In your success function you still have to parse it.
success: function(data) {
jsonData = JSON.parse(data);
alert(jsonData.myVar);
}
I do have to add too that it is very insecure to continue using php < 7.3 (as of today, 24-02-2021)
Im trying to transfer an array from jQuery to PHP but for some reason after hours of searching nothing will work. Below is what I have and what others seem to be using online but for some reason I only get the error alert. Anyone know what it is I'm doing wrong? It seems to be something to do with my jQuery code but I can put in anything there and get the same results so it is useless for telling me what I am supposed to fix. Also Im not sure if it is important but the array Im using is 2d.
FINAL WORKING CODE:
jQuery:
$.ajax({
type: "POST",
url: "phpfile.php",
data: {"myData" : myArray},
success: function(data){
alert("Success");
//appends code to end of my webpage, just for testing purposes
$('#button').after(data);
},
error: function(e){
alert("Error")
}
});
PHP:
$data = $_POST['myData'];
//creates xml file
var_dump($data);
The following is copied from the comment so this question can be marked as answered:
It seems like it should be working so I would try a simple, very basic ajax test and make sure at least that is working correctly. I would try to:
1) Get rid of the dataType json line.
2) Take the "/" out of the url.
3) Change the data to {"myData" : "testing"} or even get rid of the data line altogether.
4) Change the PHP to only be: echo "test".
Then see if you alert Success. This will hopefully tell you that your ajax is working. If so, you can start putting your code back in and see where it fails.
The mistake might be:
data: {"myData" : myjsonString}
Try this, assumming that jsonString is a string
data: "myData="+ jsonString
i am new to php and mysql.
How can i extract a VALUE from a JAVASCRIPT VARIABLE(i set) then send it to a PHP page that can read it and process it , the PHP will then insert the value into a table in MySQL database.
var A = "somevalue"
I have been researching but none of it give me a simple and direct answer . I saw some people uses JSON(which i am unfamiliar with) to do this.
Hopes someone can give me an example of the javascript/jquery , php code to this. Thanks!
You've asked for... a lot. But, this tutorial looks like it could help you.
(FYI -- I swapped out the original tutorial for one on ibm.com. It's better but far more wordy. The original tutorial can be found here)
I'm not pretty sure if it works but just try this. Your jQuery script shoul be like this:
$(function(){
var hello = "HELLO";
$.post(
"posthere.php",
{varhello: hello},
function(response){ alert(response); }
)
});
and "posthere.php" is like this:
$varhello = $_POST['varhello'];
echo $varhello . ' is posted!';
you should then get an alert box saying "HELLO is posted!"
What you need is Ajax. This is an example jQuery to use:
function sendData(data) {
$.ajax({
type: 'POST',
data: data,
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
This will send post data to that url, in which you can use PHP to handle post data. Just like in forms.
If you have a form:
<form id="theformid">
<input type="text">
</form>
Then you can use jQuery to send the form submit data to that sendData function which then forwards it to the other page to handle. The return false stops the real form from submitting:
$("#theformid").submit(function(){
sendData($(this).serializeArray());
return false;
});
If you though want to send just a variable, you need to do it like this:
function sendData(data) {
$.ajax({
type: 'POST',
data: {somekey: data},
url: "/some/url/which/gets/posts",
success: function(data) {
}
});
}
Then when you are reading $_POST variable in PHP, you can read that data from $_POST['somekey'].
Inside the success callback function you can do something with the data that the page returns. The whole data that the page returns is in the data variable for you to use. You can use this for example to check whether the ajax call was valid or not or if you need to something specific with that return data then you can do that aswell.
///////UPDATE - I already have jquery library included to my code so if its easier with jquery than javascript let me know please.
OK. There are loads of questions on here that are sending a JavaScript array to php but only 1 which is the same as mine. Unfortunately I didn't understand the answer.
So, at the moment I have an associative array in php. I then used this code,
echo json_encode($this->_inputErrors);
I don't actualy know why i'm using it, just was mentioned a lot in other examples like this. So that then sends the data to javascript (via ajax) and if i do this code,
alert(requestText);
I get a long line of text. As I imagine i should.
So how do i then in javascript get the text back to an array?
Or Is there a better way to do this?
Many Thanks For Your Time,
Chris
var o = JSON.parse( requestText );
Include this ( https://github.com/douglascrockford/JSON-js/blob/master/json2.js ) to support old browsers.
requestText is a JSON string. You need to parse the string into an object.
You can use JSON.parse to convert the string to JSON.
var obj = JSON.parse(requestText);
If your browser doesn't have JSON, include this:
https://github.com/douglascrockford/JSON-js/blob/master/json2.js
You need to set the return type as JSON
or if using jQuery, you can use jQuery's method getJSON() to get the JSON object from the url
Somedays before, I faced the same problem. Check my solution :)
array.html
$(document).ready(function(e){
//This array is where I'll receive the PHParray
var js_array=new Array();
$("#btn").click(function(e){
$.ajax({
type: 'POST',
url: 'vector.php',
cache: false,
success: function(data){
js_array=data;
//I use this "for" to print each array item into a div called "data".
for(var i=0;i<js_array.length;i++){
$("#data").append("<p>"+js_array[i]+"</p>");
}
},
dataType: 'json'
});
});
});
vector.php
<?php
$array = array(1,2,3,4,5,6);
/*As you, I use "json_encode" to serialize the array
echo json_encode($array);
?>
I hope it can help (:
The simplest way to transform that long line of text in Javascript is using eval:
alert(eval('(' + requestText + ')'));
My html file:
<script>
$(document).ready(function() {
$.ajax({
type: "POST",
url: "search.php",
data: "id=1",
datatype: "json",
success: function(msg){
$('.result1').html(msg["name"]);
}
});
})
</script>
<span class="result1"></span>
My php file:
<?
$a["name"] = 'john';
echo json_encode($a);
?>
Why the name John doesn't appear in class result1? Why? Please help me, I am going insane.
edit: Is it possible to make bounty right now?
The dataType parameter has a capital T. It works if you correct this.
Currently it is (by default) trying to guess the response format based on the mime-type, so probably defaulting to html - debugging in firebug you can see that the msg argument of the success callback is a string containing the JSON.
Not to distract you from solving this problem. But you may want to look into the .getJSON() function http://api.jquery.com/jQuery.getJSON/. It's a little cleaner if you're just getting some data.
Also, take a look at the JSON format, I think data: "id=1" should be data: "{id:1}"
And on the response side, keep in mind it's expecting multiple records so try: msg[0].name;, check out the each() function to process multiple records.
I think you should use:
$('.result1').html(msg.name);