I'm using an autosuggest plugin that allows me to select multiple items from a dropdown menu (demo here). I want a query to be sent to a php file (I will be preoccupied with the query itself later) and get a result back without leaving the page.
The php file is pretty much empty right now:
<?php print_r($_REQUEST); ?>
But I know I made a mistake with my jquery somewhere since the search box is not displaying properly anymore.
Here's the code I built up, I'm not sure what to put in the "data" field.
<script type="text/javascript">
$(document).ready(function(){
$("#select3").fcbkcomplete({
json_url: "data.txt",
addontab: true,
maxitems: 10,
input_min_size: 0,
height: 10,
cache: true,
newel: false,
filter_selected: true,
maxitimes: 5,
// I did this
onselect:"get_venue",
});
// I also did this
function get_venue() {
$("#select3 option:selected").each(function() {
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: {
WHAT DATA GOES HERE?
},
success : function(data){
$('#phpmessage').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#phpmessage').removeClass().addClass('error')
.text('There was an error.').show(500);
}
});
});
}
});
</script>
Sorry for such a long post everybody :)!! Thanks :))
Error I'm getting:
Is not a function: return func.call(func, _object);
function funCall(func, item) {
var _object = {};
for (i = 0; i < item.get(0).attributes.length; i++) {
if (item.get(0).attributes[i].nodeValue != null) {
_object["_" + item.get(0).attributes[i].nodeName] = item.get(0).attributes[i].nodeValue;
}
}
return func.call(func, _object);
}
function checkFocusOn() {
if (focuson == null || focuson.length == 0) {
return false;
}
return true;
}
You want to loop over each of the items in the search box, these have a class of .bit-box. Create an array of these search terms then send them in as data into the ajax request.
function get_venue() {
var data = [];
$('.bit-box').each(function() {
data.push( $(this).text );
});
$.ajax({
type: 'POST',
url: 'post.php',
dataType: 'json',
data: {
'choices[]': data
},
success : function(data){
$('#phpmessage')
.removeClass()
.addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true){
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#phpmessage').removeClass().addClass('error')
.text('There was an error.').show(500);
}
});
}
Related
I have done almost everything and I have successfully implemented autocomplete searching with ajax. Now problem is that when no data is found in autocomplete searching by default it shows No Result found. When I click on "NO Results Found" it is appearing on textbox. I want when No Results Found and user tries to click on that it should be no clickable
Here is My jquery Code:
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
});
And My laravel 5.2 function
public function autoComplete(Request $request) {
$query = $request->get('term','');
$states=DB::table('states')->where('state','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($states as $state) {
$data[]=array('value'=>$state->state,'id'=>$state->id);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
This is the answer you are looking for
You can use the response function to check if you do have results. If not, just push "No results found" to your list and then use _renderItem to disable this option.
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
response: function(event, ui) {
if( ui.content.length === 0 ) {
ui.content.push({
'label': 'No results found',
'value': ''
});
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
if( item.value == '' ) {
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
} else {
return $("<li>").append("<a>" + item.label + "</a>").appendTo(ul);
}
};
I made this fiddle so you can see it working.
I am having issues validating a response from API.
I am using php-crud-api and I am passing the values from my login form to the url filter[], the server responds with a 200 OK and returns the json data from the table. However I don't need the json data just a "success" or "error" response. Any help would be amazing. Thank you in advance for any feedback.
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
crossDomain: true,
data: "filter[]=email,eq,email=" + log_email + "&filter[]=password,eq,password=" + log_password,
dataType: 'json',
success: function(data) {
if (data == "null") {
console.log("Email and Password DIDN'T match");
$( "#invalid-login" ).popup( "open" );
}
else if (data == "true") {
console.log("it's a !!MATCH!!");
window.location = "content.html";
}
}
});
return false;
});
});
I've read the documentation of https://github.com/mevdschee/php-crud-api and its written that it will return the output in json format only "Condensed JSON ouput: first row contains field names", so you need to change your code accordingly or you can use some other option.
Luckily the API developer got back to me and he offered the following solution:
in the ajax call add the following line to limit the output:
+"&columns=email"
Replase:
if (data == "null") {
With:
if (data.users.records.length==0) {
In the else clause, just replace:
else if (data == "true") {
with:
else {
RESULT:
$(document).ready(function() {
$("#login-button").click(function() {
log_email = $("#login_email").val();
log_password = $("#login_password").val();
$.ajax({
type: "GET",
url: "http://www.website.com/api.php/users?",
data: "filter[]=email,eq,"+log_email+"&filter[]=password,eq,"+log_password+"&columns=email",
crossDomain: true,
dataType: 'json',
cache: false,
success: function(data) {
if (data.itouchyou.records.length == 0) {
//FAIL
$( "#invalid-login" ).popup( "open" );
console.log("Email and Password DIDN'T match");
}
else {
// SUCCESS
window.location = "content.html";
console.log("it's a !!MATCH!!");
}
}
});
return false;
});
});
I would like to retry an ajax request when response data is an empty json object.
My ajax code is following.
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
$(this).ajax();//retry ajax request here, if data is empty
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
PHP
echo json_encode(array(
'type'=>$paymentType,
'btn'=>$this->PaymentBtn,
'usd' => round($this->finalUSDAmount,2),)
);
You can put your ajax request in a function and then call that function If the respons is empty.
Like this:
function yourCall(){
$.ajax({
type: "POST",
url: "index.php?r=funding/getPaymentButton",
data: {email:benfEmail,data:JSON.stringify(data),paymentType:method},
async: true,//false
success: function (data)
{
if(data.length === 0)
{
yourCall();
console.log('err');
}
else
{
obj = jQuery.parseJSON(data);
// prcessing ajax request
}
}
});
}
this setup will however keep trying the ajax call untill it gets a valid respons. This meaning that it will keep firing if the respons length == 0
Just Simply Do Following:
$.ajax({
url : 'index.php?r=funding/getPaymentButton',
type : 'POST',
data : {email:benfEmail,data:JSON.stringify(data),paymentType:method},
tryCount : 0,
retryLimit : 3,
success : function(json) {
//do something
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
//handle error
} else {
//handle error
}
}
});
Im trying to have a form do a post using ajax method it is getting blocked by jquery line:7845
xhr.send( options.hasContent && options.data || null );
how can i fix this, keeps omiting ' send.php 404 not found '
send.php is in inside js folder here is my code for php file
$('#contact').submit(function(e){
e.preventDefault()
if(!$('#contact').valid())
return false;
$('#submit').fadeOut(200,function(){
$('.sending').fadeIn(200);
});
$.ajax({
url: 'js/send.php',
type: 'post',
data: {name:$("input[name='name']").val(),
email:$("input[name='email']").val(),
comments:$("textarea[name='comments']").val(),
},
success: function(data) {
if(data==1)
{
$('.sending').html('Sent Successfully Thank You!');
$('#contact').fadeOut(500);
$("#contact input:not(#submit)").val('');
$('#contact textarea').val('');
txt_name = null;
}
else alert("error sending");
},
error:function(err)
{
alert("error sending");
}
}); });
I'm having a problem with my ajax code. Its supposed to check a returned value from php, but it's always returning undefined or some other irrelevant value. As i'm quite new to ajax methodologies i can't seem to find a headway around this. I've searched numerous link on stackoverflow and other relevant forums regarding the solution but none helped. The problem remains the same
Here is the ajax code::
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
dataType: 'json',
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
});
return false;
})
});
The problem lies with outputting the value of data. The php code returns 1 if the value is successfully entered in the database and 0 otherwise. And the ajax snippet is supposed to check the return value and print the appropriate message. But its not doing such.
Here is the php code::
<?php
require './fileAdd.php';
$dir_path = $_POST['path'];
$insVal = new fileAdd($dir_path);
$ret = $insVal->parseDir();
if ($ret ==1 ) {
echo '1';
} else {
echo '0';
}
?>
I can't find a way to solve it. Please help;
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path },
type: 'POST',
//dataType: 'json', Just comment it out and you will see your data
OR
dataType: 'text',
Because closing } brackets not matching try this
$(document).ready(function() {
$('#submit-button').click(function() {
var path = $('#path').val();
$.ajax({
url: 'frontEnd.php',
data: {path: path},
type: 'POST',
dataType: 'text', //<-- the server is returning text, not json
success: function(data) {
if (data == 1) {
alert("Value entered successfully" + data);
} else if (data == 0) {
alert("Sorry an error has occured" + data);
}
} //<-- you forgot to close the 'success' function
});
return false;
});
});