JQuery UI Autocomplete Wordpress - javascript

I want to add autocompletion in a nickname search bar. I do not understand why it does not work. My code is correct ?
In my file liste.php
global $wpdb;
$name = $_POST['code_postal'];
$sql = $wpdb->get_results("SELECT * FROM membres WHERE pseudo LIKE '$name%' ");
$titles = array();
foreach($sql as $key=> $value){
echo $value->pseudo;
}
echo json_encode($titles); //encode into JSON format and output
In my global.js
$('#recherche').autocomplete({
source: function(name, response) {
$.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-content/themes/ARLIANE/liste.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
}
});
}
});
In my index.php
<form>
<input type="text" name="term" id="recherche"/>
</form>

You can try to log ajax errors to console for more informations about the problem , something like this :
$.ajax({
type: 'POST',
dataType: 'json',
url: 'wp-content/themes/ARLIANE/liste.php',
data: 'action=get_listing_names&name='+name,
success: function(data) {
response(data);
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});

Try to change the URL in your js code by adding a page and to associate the file liste.php as a custom page Type and Than add the page URL :
url: '<?php echo get_permalink(page_id); ?>',

If I do a include of liset.php this returns me well a table json.
But when I make my ajax call it returns a Error 500.
I think the problem comes from the jquery call with the autocomplete function.

Related

How to get return text from php file with ajax?

I am making a call with ajax to a php file. All I want to do is get a value back from the php file to test it with javascript. I have tried many many things, but can only get undefined (from the below code).
How can I get "hello" returned from the php file to my javascript?
jQuery.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = jQuery(data).html();
alert(the_returned_string)
}
});
The PHP file:
<?php
echo '<div id="id-query-result>"';
echo "hello";
echo "</div>";
You can change the code inside PHP like this
<?php
$queryResult = '<div id="id-query-result">hello</div>';
echo json_encode(['html' => $queryResult]);
Then, change your ajax call
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
dataType: 'json',
success: function(data) {
var the_returned_string = data.html;
alert(the_returned_string);
}
});
$.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
$('body').append(data);
var text = $('#id-query-result').text();
alert(text);
$('#id-query-result').remove()
}
});
Why not just append the HTML response of your php file then get the text accordingly. You can then remove it after.
There are two changes to be done:
Change the type to "GET" since you directly call the PHP File.
remove the wrapped jQuery method inside the success function and add .html as an attribute
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = data.html
alert(the_returned_string)
}
});

How to make a generic ajax function for php file

I hope you can understand my question. I am trying to make a generic ajax function that will send some data to a php file and get the server's response. There is a very similar question here jquery - creating a generic ajax function , however I am having some troubles sending the data in a json format. Let me provide you the JS code:
function CallMethod(url, parameters, successCallback) {
$.ajax({
type: 'POST',
url: url,
data: JSON.stringify(parameters),
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}
var pars = {
id:"1",
message:"hello world"
};
function onSuccess(data) {
console.log(data);
}
CallMethod('ajaxGeneric.php', pars, onSuccess);
And now here is my php file 'ajaxGeneric.php':
<?php
$id = $_POST["id"];
$msg = $_POST["message"];
echo $id;
echo $msg;
?>
When I run the page I have this error in the Chrome's console:
SyntaxError: Unexpected token < in JSON at position 0(…)
The php file seems also to have some problems trying to get the post values. What am I doing wrong? sending the data? getting the data back?
Any help will be greatly appreciated.
Try removing JSON.stringify and pass the parameters directly,So that your function will look like this
function CallMethod(url, parameters, successCallback) {
$.ajax({
type: 'POST',
url: url,
data: parameters,
contentType: 'application/json;',
dataType: 'json',
success: successCallback,
error: function(xhr, textStatus, errorThrown) {
console.log(errorThrown);
}
});
}

AJAX success function not working when the page is load

here is my code in ajax
function loadcountries()
{
var p = document.getElementById("selectCntry");
while(p.firstChild)
{
p.removeChild(p.firstChild);
}
var data = {
action: "loadccc"
};
jQuery.ajax
(
{
type: "POST",
url: "ajax-ows2.php",
dataType: 'json',
async:false,
data:data,
success: function(msg)
{
alert(msg.test);
}
}
);
}
here is my ajax-ows2.php
<?php
$action = $_POST["action"];
include "dbconnect.php";
if($action == "loadccc")
{
$var = $action;
$response_array['test'] = $var;
header('Content-type: application/json');
echo json_encode($response_array);
}
?>
and here is my function call:
<script>
window.onload = loadcountries;
</script>
my ajax way is different. I really have no idea why it is not alerting when the page is load. Im really sure that my ajax-ows2.php is good and im sure that my function call is correct. Can somebody help me with this. This is not a duplicate one. I tried to used asynch:false but still not working.
try this format:
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: data,
url: 'ajax-ows2.php',
success: function (data) {
console.log(data);
},
error: function (error){
console.log(error);
}
});
since you are doing POST method, your data parameter must be a stringify, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

how to send javascript array to controller in yii

I have a view having multiple checkboxes.
When I select some textbox, I need to do some operation on them, so they should be passed to the controller.
How can I do this?
My JS function :
function myfun() {
$.ajax({
type : "POST",
url : "http://localhost/newtemplate/index.php/product/dispatchdata/",
dataType : 'json',
data : {
idList : $("input[type=checkbox]:checked").serializeArray()
},
success : function(data) {
alert(data);
},
error : function (data){
alert('Error');
//alert(data);
}
});
}
replace your URL by this:
url: "<?php echo Yii::app()->createUrl('product/dispatchdata'); ?>",
then try to send your json as follow: data: {idList:JSON.stringify(idList)},
Use this :
$.ajax({
url: "<?php echo App::param('siteurl'); ?>products/ZipUpload",
type: "POST",
data: {
idList : $("input[type=checkbox]:checked").serializeArray()
},
success: function(data) {
alert(data)
}
});
As mohammad said: "Replace your url with"
url: "<?php echo Yii::app()->createUrl('product/dispatchdata'); ?>",
Further, if you fail in ajax call, the reason may be that the error is in your code in the controller. if you cant return successfully from controller, then you will get error in ajax... so try debugging step by step your controller action.

Unable to pass string parameter to php function via ajax

I am making the following jquery ajax call to a codeigniter php function:
$.ajax({
type:"POST",
url: "Ajax/getHtml",
data: { u : 'http://stackoverflow.com/' },
contentType: "application/json; charset=utf-8",
dataType: 'html',
success: function(data) {
console.log(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log('error');
console.log(jqXHR,textStatus, errorThrown);
}
});
The requested php function is :
public function getHtml() {
var_dump($_POST);
$url = $_POST['u'];
$result = file_get_contents($url);
echo ($result);
}
var_dump($_POST) yields:
array(0) { }
How can I fix this?
Php will not populate the $_POST array if the content type of the request is application/json; charset=utf-8, also you aren't sending json. Just remove the content type line and the proper(default) content type of application/x-www-form-urlencoded will be set.

Categories