I have my autocomplete working fine if there is hard coded data being fed into it. My PHP is returning a JSON result. I'm not sure where I am going wrong.
HTML
<div class="form-group bgcolor">
<label for="send_to">Direct to: </label><input type="text" name="send_to" id="send_to" class="form-control send_to typeahead" placeholder="Leave blank normally">
</div>
Jquery
$('.typeahead').typeahead({
source: {
groupName: {
ajax({
url: 'scripts/order_messaging.php',
method: 'POST',
data: JSON.stringify({action: 'autocomplete_to_user', query:query}),
contentType: 'application/json',
dataType: 'json',
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
},
},
debug: true
});
PHP
//autocomplete user name for user_to
if ( $_POST['action'] == 'autocomplete_to_user' ) {
$stmt = $pdo->prepare('select * from login where username like :query');
$stmt->bindValue('query', '%'.$_POST['query'].'%');
$stmt->execute();
$result = array();
while($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($result, $user_name->username);
}
echo json_encode($result);
}
I think it's this line in my jQuery: data: {action: 'autocomplete_to_user', query:query}, Maybe I have a syntax problem.
As per jQuery Ajax Documentation, dataType: 'json' evaluates the response as JSON and returns a JavaScript object.
You need to stringify your data by using JSON.stringify({action: 'autocomplete_to_user', query:query}) before you send it to PHP. Also, you need to add header Content-Type: 'application/json' that tells you PHP code that request data is JSON. You can do this by adding contentType: 'application/json' in your Ajax settings.
Your final jQuery code would look like this:
$('.typeahead').typeahead({
source: function(query, result)
{
$.ajax({
url: 'scripts/order_messaging.php',
method: 'POST',
data: JSON.stringify({action: 'autocomplete_to_user', query:query}),
contentType: 'application/json',
dataType: 'json',
success:function(data)
{
result($.map(data, function(item){
return item;
}));
}
})
}
});
Refer to jQuery Ajax Documentation for mode details.
Hope this helps!
EDIT:
You need to update your PHP code to read JSON. Please refer to this link.
Your PHP Code should look like this:
<?php
// Read the input stream
$body = file_get_contents("php://input");
// Decode the JSON object
$object = json_decode($body, true);
//autocomplete user name for user_to
if ( $object ['action'] == 'autocomplete_to_user' ) {
$stmt = $pdo->prepare('select * from login where username like :query');
$stmt->bindValue('query', '%'.$object['query'].'%');
$stmt->execute();
$result = array();
while($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($result, $user_name->username);
}
echo json_encode($result);
}
?>
In my humble opinion, the documentation has some errors. For instance, in the demos, specifically the example Country v2 states
A POST request will be sent with data myKey: myValue
when in actuality the request being sent in the example is GET, because it depends on the type key of the ajax object of the first source (country in this case), which is not set, thus defaulting to GET.
So, that being said, you really should stick to the proposed HTML structure (at least start with it, then take away stuff you don't want gradually as long as it'll let you).
HTML
<form id="form-country_v2" name="form-country_v2">
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input class="typeahead" name="country_v2[query]" placeholder="Search" autocomplete="off">
</div>
<div class="typeahead__button">
<button type="submit">
<i class="typeahead__search-icon"></i>
</button>
</div>
</div>
</div>
</form>
JS
$(document).ready(() => {
$('.typeahead').typeahead({
template: "{{display}} <small style='color:#999;'>{{group}}</small>",
source: {
users: { //might as well be 'willy wonka', it doesn't matter
ajax: {
type: "POST",
url: "scripts/order_messaging.php",
//this is not actually needed for the request to work (reach the server),
//this is used to access said request's returned data, it all
//depends on how you structure the response in the server,
//check out the php part
path: "data.users",
data: {
action: 'autocomplete_to_user',
query: 'username'
}
}
}
},
callback: {
//this is just to help you show the response in the html
onResult: function(node, query, result, resultCount) {
if (query === "") return;
var text = "";
if (result.length > 0 && result.length < resultCount) {
text = "Showing <strong>" + result.length + "</strong> of <strong>" + resultCount + '</strong> elements matching "' + query + '"';
} else if (result.length > 0) {
text = 'Showing <strong>' + result.length + '</strong> elements matching "' + query + '"';
} else {
text = 'No results matching "' + query + '"';
}
$('#result-container').html(text);
},
onInit: function(node) { //and this is just informational
console.log('Typeahead Initiated on ', node, node.selector);
}
}
});
});
order_messaging.php
if ($_POST['action'] == 'autocomplete_to_user') {
$stmt = $pdo->prepare('select * from login where username like :query');
$stmt->bindValue('query', '%' . $_POST['query'] . '%');
$stmt->execute();
$result = array();
while ($user_name = $stmt->fetch(PDO::FETCH_OBJ)) {
array_push($result, $user_name->username);
}
echo json_encode(array(
"status" => true,
"error" => null,
//here you use whatever structure you want to return the data in,
//as long as the payload is an array ($result).
//remember in the JS you are expecting 'data.users'?
//this is where it's coming from
"data" => array(
"users" => $result,
)
));
} else
echo json_encode(array(
"status" => true,
"error" => null,
"data" => array(
"users" => [],
)
));
HIH
Well, after much trial and error I got an autocomplete working using jQuery .autocomplete.
I don't know what I was doing wrong with the typeahead but the documentation was hard to understand (probably because of my limited experience with jQuery).
To all those in the future that need some help with this; here is a tutorial I found that was helpful: jquery ui autocomplete tutorial
Thank you to everyone
I've tested the library and you need to change two things in order to make it work.
1) You need to restructure the source parameter. You were giving it an AJAX callback which is not supported. According to the documentation, it accepts an array or an object with settings, so AJAX needs to be defined like this:
$('.typeahead').typeahead({
source: {
// source has an "ajax" property where you just need to place
// the object with AJAX params (the one you'd normally place inside
// an $.ajax() call)
ajax: {
url: 'scripts/order_messaging.php',
method: 'POST',
data: {
action: 'autocomplete_to_user',
query: query,
},
dataType: 'json',
path: '',
},
},
});
The path property of the ajax object is key here. It tells the typeahead function where to look for the data that was returned by the AJAX action. Since you're encoding a one-dimensional array of values, you need to set it to an empty string, meaning your data is in the root of the response.
If you were to return, for example, an array like echo json_encode(['users' => $result]); then you'd have to set the path to 'users' (because that is the index in the response that holds your data).
2) You have to follow a strict HTML structure in order to make it work:
<div class="typeahead__container">
<div class="typeahead__field">
<div class="typeahead__query">
<input class="js-typeahead" name="q" autocomplete="off">
</div>
</div>
</div>
If you leave out any of these elements, it doesn't trigger the functionality. This HTML structure is one of the first things they mention in the documentation.
Related
So I have this jquery code:
$(function(){
var url = 'template/traitComTest.php';
window.onload = function(e) {
// $(".formCom").ajaxForm({url: 'template/traitComTest.php', type: 'post'});
$.ajax({
type: "POST",
url: url,
data: $( ".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
}
});
}
});
with this php code:
if (isset($_REQUEST)) {
$adresse = $_POST['adresse'];
$com = $_POST['commentaire'];
$sql = $bdd->prepare('UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem ');
$sql->execute(array(
":com" => $com,
":exem" => $adresse
));
$myData1 = array('result' => $sql);
echo json_encode($myData1);
$sql->closeCursor();
$sqlSelect = $bdd->prepare("SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp");
$sqlSelect->execute(array(
":exemp" => $adresse
));
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
}
I get this response from ajax on chrome' console =>
{"result":{"queryString":"UPDATE tempSelector_template SET commentaire= :com WHERE exemple = :exem "}}{"result1":{"queryString":"SELECT commentaire FROM tempSelector_template WHERE exemple= :exemp"}}
and my issue is that I can't access to the data inside the json and need your help
Ok so you are basically returning 2 seperate sets of json encodes. It does not work that way. you can only accept a single set of json while reading through ajax. Not two. In your php script i see that you have included that following parts.
$myData1 = array('result' => $sql);
echo json_encode($myData1);
and
$myData = array('result1' => $sqlSelect);
echo json_encode($myData);
you should remove both parts and combine them into one single array using array_merge
$myData1 = array('result' => $sql);
$myData = array('result1' => $sqlSelect);
echo json_encode(array_merge(myData1, $myData));
also in your ajax request, set dataType to json
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(".formCom").serializeArray(),
success: function(reponse){
console.log(reponse);
});
You have 2 problems:
You are sending back invalid json: Instead of echoing out different json strings, you need to build a data-structure (an array or object) and only at the end encode and echo that once. Now you have concatenated json in your response and that makes it really hard to parse.
You are not parsing the json you get back in your javascript. When you return valid json (see 1.), you can add dataType: 'json' to your ajax call to have jQuery parse the response automatically:
$.ajax({
type: "POST",
dataType: 'json',
url: url,
// etc.
So you have a form and you want to submit and that ajax will return some data after submitting the form. And if you want to access the data of response. You need to add this things
1.) Add type = 'post' in your $.ajax object
2.) And use JSON.parse(response)
So I've followed all your advice about making an jQuery or Javascript AJAX request to a php file on a server.
The problem I'm running in to is that my response is this
Fatal error: Array callback has to contain indices 0 and 1 in
So here is my jQuery
$(document).ready(function(){
$(".ex .select").click(function(){
$("body").data("id", $(this).parent().next().text());
Those lines serve to capture a variable and save it as data on the body element, so I can use it later.
But I want to send that same variable to PHP file, to add to a complex API request - eventually to return the results, create $_SESSION variables and so forth
var pageId = {
id: $("body").data("id"),
};
But let's avoid that as a problem and just make my array simple like
var pageId = {
id: "12345",
};
$.ajax({
type: 'GET',
url: 'test.php',
data: pageId,
datatype: 'json',
cache: false,
success: function (data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
});
});
});
And for now at least I was hoping to keep my PHP file simple for testing my grasp of the concepts here
<?php
$id = $_GET('id');
echo json_encode($id);
?>
I'm expecting the response
Data: 12345
Status: Success
But I get the Error Message above.
You need to change $_GET('id') to $_GET['id']
and in order to send status, you need to add status to an array just like below and try to parse JSON on your response.
<?php
$id = $_GET['id'];
$result = array("id"=>$id, "Status"=>"Success");
echo json_encode($result);
?>
And access in jquery using . like if you use data variable in success then
success:function(data){
alert(data.Status);
}
change $id = $_GET('id'); to $id = $_GET['id'];
because $_GET, not a function it's an array type element.
I have a ajax function that would retrieve data from my database and display it in my textbox. I am using a JQuery Form Plugin to shorten the ajax process a little bit. Now what I want to do is to get the data back from the php script that I called from the ajax function.
The form markup is:
<form action="searchFunction.php" method="post" id="searchForm">
<input type="text" name="searchStudent" id="searchStudent" class="searchTextbox" />
<input type="submit" name="Search" id="Search" value="Search" class="searchButton" />
</form>
Server code in searchFunction.php
$cardid = $_POST['searchStudent'] ;
$cardid = mysql_real_escape_string($cardid);
$sql = mysql_query("SELECT * FROM `users` WHERE `card_id` = '$cardid'") or trigger_error(mysql_error().$sql);
$row = mysql_fetch_assoc($sql);
return $row;
The ajax script that processes the php is
$(document).ready(function() {
$('#searchForm').ajaxForm({
dataType: 'json',
success: processSearch
});
});
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
In PHP, if I want to call the data, I would just simply create a function for the database and just for example echo $row['username'] it. But how do I do this with ajax? I'm fairly new to this so, please explain the process.
$('#Search').click(function (e) {
e.preventDefault(); // <------------------ stop default behaviour of button
var element = this;
$.ajax({
url: "/<SolutionName>/<MethodName>",
type: "POST",
data: JSON.stringify({ 'Options': someData}),
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
error: function () {
alert('Unable to load feed, Incorrect path or invalid feed');
},
success: processSearch,
});
});
function processSearch(data) {
var username= ($(data).find('#username'));
}
Change the input type submit to button. Submit will trigger the action in the form so the form will get reloaded. if you are performing an ajax call change it into button.
Everything seems to be fine, except this bit -
function processSearch(data) {
alert(data['username']); //Am I doing it right here?
}
You need to change it to -
function processSearch(data) {
// data is a JSON object. Need to access it with dot notation
alert(data.username);
}
UPDATE
You also need to return a JSON response from your PHP file. Something like -
// Set the Content Type to JSON
header('Content-Type: application/json');
$data = [
"key" => "value"
];
return json_encode($data);
In your case you can directly encode the $row like so -
return json_encode($row);
I am trying to pass a JSON object that looks similar to this:
{"service": "AAS1", "sizeTypes":[{"id":"20HU", "value":"1.0"},{"id":"40FB","2.5"}]}
Just a note: In the sizeTypes, there are a total of about 58 items in the array.
When the user clicks the submit button, I need to be able to send the object to a PHP script to run an UPDATE query. Here is the javascript that should be sending the JSON to the PHP script:
$('#addNewSubmit').click(function()
{
var payload = {
name: $('#addservice').val();
sizeTypes: []
};
$('input.size_types[type=text]').each(function(){
payload.sizeTypes.push({
id: $(this).attr('id'),
value: $(this).val()
});
});
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {service: payload},
dataType: 'json',
success: function(msh){
console.log('success');
},
error: function(msg){
console.log('fail');
}
});
});
Using the above click function, I am trying to send the object over to php script below, which is in api/editService.php:
<?php
if(isset($_POST['service']))
{
$json = json_decode($_POST['service'], true);
echo $json["service"]["name"] . "<br />";
foreach ($json["service"]["sizeTypes"] as $key => $value){
echo $value["value"] . "<br />";
}
}
else
{
echo "Nooooooob";
}
?>
I do not have the UPDATE query in place yet because I am not even sure if I am passing the JSON correctly. In the javascript click function, you see the SUCCESS and ERROR functions. All I am producing is the ERROR function in Chrome's console.
I am not sure where the error lies, in the JavaScript or the PHP.
Why can I only produce the error function in the AJAX post?
Edit
I removed the dataType in the ajax call, and added JSON.stringify to data:
$.ajax({
type: 'POST',
url: 'api/editService.php',
data: {servce: JSON.stringify(payload)},
success: function(msg){
console.log('success');
},
error: function(msg){
console.log('fail'), msg);
}
});
In the PHP script, I tried this:
if(isset($_POST['service'))
{
$json = json_decode($_POST['service'], true);
foreach ($json["service"]["sizeTypes"] as $key => $value){
$insert = mysqli_query($dbc, "INSERT INTO table (COLUMN, COLUMN, COLUMN) VALUES (".$json["service"] . ", " . "$value["id"] . ", " . $value["value"]")");
}
}
else
{
echo "noooooob";
}
With this update, I am able to get the success message to fire, but that's pretty much it. I cannot get the query to run.
without seeing the error, I suspect the error is because ajax is expecting json (dataType: 'json',) but you are echoing html in your php
Try to change
error: function(msg){
console.log('fail');
}
to
error: function(msg){
console.log(msg);
}
There might be some php error or syntax issue and you should be able to see it there.
Also try to debug your php script step by step by adding something like
echo "still works";die;
on the beginning of php script and moving it down till it'll cause error, then you'll know where the error is.
Also if you're expecting JSON (and you are - dataType: 'json' in js , don't echo any HTML in your php.
As you are sending an object in your service key, you probably have a multi-dimensional array in $_POST['service'].
If you want to send a string, you should convert the object to json:
data: {service: JSON.stringify(payload)},
Now you can decode it like you are doing in php.
Also note that you can only send json back from php if you set the dataType to json. Anything other than valid json will have you end up in the error handler.
Example how to handle a JSON response from editService.php. Typically, the editService.php script will be the worker and will handle whatever it is you need done. It will (typically) send a simple response back to the success method (consider updating your $.ajax to use the latest methods, eg. $.done, etc). From there you handle the responses appropriately.
$.ajax({
method: 'POST',
url: '/api/editService.php',
data: { service: payload },
dataType: 'json'
})
.done(function(msh) {
if (msh.success) {
console.log('success');
}
else {
console.log('failed');
}
})
.fail(function(msg) {
console.log('fail');
});
Example /editService.php and how to work with JSON via $.ajax
<?php
$response = [];
if ( isset($_POST['service']) ) {
// do your stuff; DO NOT output (echo) anything here, this is simply logic
// ... do some more stuff
// if everything has satisfied, send response back
$response['success'] = true;
// else, if this logic fails, send that response back
$response['success'] = false;
}
else {
// initial condition failed
$response['success'] = false;
}
echo json_encode($response);
I'm trying to send a JavaScript variable to a php script using ajax. This is my first time using ajax and I don't know where I went wrong. Here's my code
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
dataType: "script",
data: { "selected_category" : v}
}).done(function() {
window.location.href = "http://mywebsite.com";
});
}
All help is appreciated
Here's the HTML
<ul class="cat">
<li class="opt" onclick="selectcat('option1')">option1</li>
<li class="opt" onclick="selectcat('option2')">Option 2</li>
</ul>
This is the ajax php file
<?php
session_start();
$ctgry = $_GET['selected_category'];
$_SESSION['select_cat'] = $ctgry;
?>
You need to remove dataType: "script" since you are just sending data. Do it like this:
function selectcat(v) {
$.ajax({
type: "GET",
url: "myurl.php",
data: {"selected_category": v}
}).done(function(result) {
console.log(result);
//window.location.href = "http://mywebsite.com";
});
}
Hi this is what I do to call an ajax request
You can post data or load a file using following code:
$("#button click or any other event").click(function(){
try
{
$.post("my php page address",
{
'Status':'6',
'var one':$("#myid or .class").val().trim(),
'var 2':'var 2'
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax request you
//can send any type of data whether json or or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
I hope this help!
AJAX is easier than it sounds. You just need to see a few good examples.
Try these:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
The above examples demonstrate a few things:
(1) There are four formats for an AJAX request - the full $.ajax() structure, and three shortcut structures ($.post(), $.get(), and $.load() )
Until you are pretty good at AJAX, I suggest using a correctly formatted $.ajax() code block, which is what the above examples demonstrate. Such a code block looks like this:
$('#divID').click({
$.ajax({
type: 'post',
url: 'contact.php',
dataType: 'json',
data: 'email=' + form.email.value
}).done(function(data) {
if ( typeof(data) == 'object' ) {
if ( data.status == 'valid') {
form.submit();
} else if(data.status !=='valid' {
alert('The e-mail address entered is wrong.');
return false;
} else {
alert('Failed to connect to the server.');
return false;
}
}
});
});
(2) In an $.ajax() code block, the data: line specifies the data that is sent to the PHP processor file.
(3) The dataType: line specifies the type of data that the ajax code block expects to receive back from the PHP processor file. The default dataType is html, unless otherwise specified.
(4) In the PHP processor file, data is returned to the AJAX code block via the echo command. Whether that data is returned as html, text, or json, it is echoed back to the AJAX routine, like this:
<?php
//perform MySQL search here. For eg, get array $result with: $result['firstname'] and $result['lastname']
$out = '<div id="myresponse">';
$out .= 'First Name: <input type="text" value="' .$result['firstname']. '" />';
$out .= 'Last Name: <input type="text" value="' .$result['lastname']. '" />';
$out .= '</div>';
echo $out;
Please try a couple of the above examples for yourself and you will see how it works.
It is not necessary to use json to send/return data. However, json is a useful format to send array data, but as you can see, you can construct a full html response on the PHP side and echo back the finished markup.
So, you just need to echo back some data. It is the job of the PHP file to:
(1) receive the data from the AJAX routine,
(2) Use that data in a look up of some kind (usually in a database),
(3) Construct a response, and
(4) echo (NOT return) the response back to the AJAX routine's success: or .done() functions.
Your example could be changed to look something like:
HTML:
<ul class="cat">
<li class="opt" value="TheFirstOption">option1</li>
<li class="opt" value="The Second Option">Option 2</li>
</ul>
javascript/jQuery:
$('.opt').click(function(){
var v = $(this).val();
$.ajax({
type: "POST",
url: "myurl.php",
dataType: "html",
data: { "selected_category" : v}
}).done(function(data) {
$('#div_to_insert_the_response').html(data);
});
});
PHP:
<?php
$val = $_POST['selected_category'];
echo 'You selected: ' . $val;
dataType: "script" has no sense here, I think you want json or leave it empty.
Your PHP script should work if you try to get the variable with $_GET['selected_category']
I suggest you this modification to help yourself for debugging
$.ajax({
type: "GET",
url: "myurl.php",
data: { "selected_category" : v},
success: function(data){
console.log(data);
// you can also do redirection here (or in complete below)
},
complete: function(data){
// when request is done, independent of success or error.
},
error: function(data){
// display things to the user
console.error(data);
}
})