JQuery Ajax goes in error - javascript

My ajax function goes in error after I set the dataType to Json.
That's the code:
Ajax script:
$('#da').on("change",function() {
$.ajax({
url: "callAjaxIndex.php",
type: "POST",
dataType: "json",
data: {
method: 1,
id: $('#da').val(),
},
success: function() {
alert('test');
},
error: function() {
alert('error');
}
});
});
callAjaxIndex.php
<?PHP
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as 'nome_arrivo', tratte.id as 'id_arrivo' FROM tariffe, tratte WHERE id_arrivo = tratte.id AND id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}
?>
What's wrong?
Thank you

You can try this
$(document).on('change', '#da', function(){
$.post("callAjaxIndex.php", {'method': 1, 'id': $(this).val()}, function(data){
var d = $.parseJSON(data); //here is the data parsed as JSON
//data is that returned from callAjaxIndex.php file
});
});
<?php
require('includes/core.php');
if ( isset($_POST['method']) ) {
$sql = "SELECT tratte.nome as nome_arrivo, tratte.id as id_arrivo FROM tariffe INNER JOIN tratte ON id_arrivo = tratte.id WHERE id_partenza = '".$_POST['id']."'";
$query = $conn->query($sql);
while ( $tariffe = $query->fetch_array() ) {
$result[] = array(
'id' => $tariffe['id_arrivo'],
'nome' => $tariffe['nome_arrivo']
);
}
echo json_encode($result);
}

You can find out the error by changing your function to this:
//other code
error: function(data)
{
console.log(data.responseText)
}
//other code
This will tell you why it fails, might be something generic but better than 'error'
Also note:
this was done from a phone so excuse any mistakes
I'd rather this be treated as a comment until I can get to a machine to help more :)

Related

Second Wordpress Ajax not firing

Hi there I am trying use some wordpress ajax my first ajax request works fine but the second one does not. Can some one please tell me why this is happening
Works fine:
PHP
//Add Students Details to DB
add_action( 'wp_ajax_my_action', 'my_action_callback' );
function my_action_callback() {
$fName = $_POST['fName'];
$lName = $_POST['lName'];
$dob = $_POST['dob'];
$gender = $_POST['gender'];
$diet = $_POST['diet'];
$current_id = get_current_user_id();
global $wpdb;
$result = $wpdb->insert(
'wp_students',
array(
'ID' => NULL,
'first_name' => $fName,
'last_name' => $lName,
'birthdate' => $dob,
'gender' => $gender,
'dietary_requirements' => $diet,
'user_id' => $current_id
)
);
echo json_encode($result);
wp_die();
}
JS
var data_value = {
action: 'my_action',
fName: $(acc[i]).find('input.fName').val(),
lName: $(acc[i]).find('input.lName').val(),
dob: $(acc[i]).find('input.dob').val(),
gender: $(acc[i]).find('select.gender').val(),
diet: $(acc[i]).find('textarea.diet_req').val()
};
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: data_value,
success: function(msg) {
if (msg == false) {
$('#insert_status').html('<strong><span style="color: red;">Error: </span></strong>Details Have Not Been Updated');
return false;
}
},
error: function(xhr, status, error) {
var i = JSON.parse(xhr.responseText)
alert(i.Message);
}
});
Does not work:
PHP
//Delete Students Details
add_action( 'wp_ajax_my_delete', 'my_action_callback_delete' );
function my_action_callback_delete() {
echo 'here';
global $wpdb;
$result = $wpdb->delete( 'wp_students', array( 'usesr_id' => get_current_user_id()) );
echo json_encode($result);
wp_die();
}
JS
var value = {
action: 'my_delete'
};
$.ajax({
type: "post",
dataType: "json",
url: my_ajax_object.ajax_url,
data: value,
success: function(msg) {
if (msg == false) {
$('#insert_status').html('<strong><span style="color: red;">Error: </span></strong>Details Have Not Been Updated');
return false;
}
},
error: function(xhr, status, error) {
var i = JSON.parse(xhr.responseText)
alert(i.Message);
}
});
If you could help me would be great. Wordpress Ajax is not a straight forward as normal ajax.
Could it be that you just have a typo in your delete function?
'usesr_id' => get_current_user_id()
should probably be
'user_id' => get_current_user_id()
//Delete Students Details
add_action( 'wp_ajax_my_delete', 'my_action_callback_delete' );
function my_action_callback_delete() {
echo 'here';
global $wpdb;
$result = $wpdb->delete( 'wp_students', array( 'usesr_id' => get_current_user_id()) );
echo json_encode($result);
wp_die();
}

jQuery autocomplete retrieve data from database

I have implemented jQuery autocomplete function for my web, which is working fine. But I want the result of the autocomplete to retrieve only the data of a particular person and not the complete database result.
Below is the jQuery for the autocomplete
jQuery(document).ready(function($){
$('.product_desc').autocomplete({source:'functions/products.php?', minLength:2});
products.php
//Path for the databsae
<?php
include '../include/configuration.php';
if ( !isset($_REQUEST['term']) )
exit;
$rs = mysql_query('select id,item_name,fk_vendor_id from item where item_name like "%'. mysql_real_escape_string($_REQUEST['term']).'%" order by item_name asc ', $con);
$data = array();
if ( $rs && mysql_num_rows($rs) )
{
while( $row = mysql_fetch_array($rs, MYSQL_ASSOC) )
{
$data[] = array(
'label' => $row['item_name'],
'value' => $row['item_name']
);
}
}
else
{
$data[] = array(
'label' => 'not found',
'value' =>''
);
}
// jQuery wants JSON data
echo json_encode($data);
flush();
?>
Any solution will be appreciated.
Try this:
$(".product_desc").autocomplete({
source: "functions/products.php",
minLength: 2,
select: function(event,ui){
//do something
}
});
Try this code, Any text field having class .search the auto complete suggestion will works on server side in ajax.php file you need to return array as below:
$response = ['Computer', 'Mouse', 'Keyboard', 'Monitor'];
echo json_encode($response);
Here is sample code for auto suggest.
$(document).on('keyups','.search',function() {
$(this).autocomplete({
source: function( request, response ) {
if (request.term != "") {
$.ajax({
url: "ajax.php",
dataType: "json",
method: "post",
data: {
name: request.term
},
success: function (data) {
if (data != "") {
response($.map(data, function (item) {
var name = item.name;
return {
label: name,
value: name,
data: item
}
}));
}
}
});
}
},
autoFocus: true,
minLength: 2,
select: function( event, ui ) {
var name = ui.item.data;
$(this).val(name);
}
});
});

no out while calling php function to read database

I am calling a php function from javascript by passing three arguments, on the other side php function inside the php file gets two values from database and prints all the value. for that I have written this code but this is not working, means this code prints nothing in the output so kindly help.
javascript code
jQuery.ajax(
{
type: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:["className", "student_id", "isPresent"]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});
php code
<?php
header('Content-Type: application/json');
if( $_POST['functionname'] == 'saveUser' ) {
include_once("dbConnection.inc");
$db = db_connect();
$newSql = "SELECT class_id, date FROM class_session WHERE class_id = (select max(class_id) from class_session)";
$result = mysql_query($newSql, $db);
$row = mysql_fetch_array($result);
$class_id = $row["calass_id"];
$date = $row["date"];
echo json_encode(Array(
'result' => $_POST['arguments'][0] .' '. $_POST['arguments'][1] .' '. $_POST['arguments'][2] .' '. $class_id .' '. $date
));
}
?>
The right property is method not type, see jQuery.ajax()
jQuery.ajax({
method: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:["className", "student_id", "isPresent"]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});

Hide value in Bootstrap Typeahead

I'm using Bootstrap Typeahead with PHP to display a list from a database using source.php:
<?php
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = $row['title'] . ',' . $row['id'];
}
// Return the json array
echo json_encode($array);
}
?>
You can see that I add both 'title' and 'id' to the array. All I want it to display in the typeahead is the title but I need the id for the links. Here is the JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + item.replace(/ /g, '-').replace(/\,/g,'/').toLowerCase() + "/";
return item;
}
});
In the line beginning document.location I replace the comma between the two values with a forward slash and it works e.g. /england/123/. But it's the typeahead display that shows it as England,123 rather than just England.
Any help would be greatly appreciated.
OK managed to get a result with the following:
PHP:
if (isset($_POST['query'])) {
require( "config.php" );
$conn = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
$query = $_POST['query'];
$sql = "SELECT * FROM articles WHERE title LIKE '%{$query}%'";
$array = array();
foreach ($conn->query($sql) as $row) {
$array[] = array('label' => $row['title'], 'id' =>$row['id']);
}
// Return the json array
echo json_encode($array);
}
JS:
$('#typeahead').typeahead({
source: function (query, process) {
$.ajax({
url: "http://www.stubowker.com/amex/cms/source.php",
type: "POST",
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
objects = [];
map = {};
$.each(data, function(i, object) {
map[object.label] = object;
objects.push(object.label);
});
process(objects);
}
})
},
sorter: function (items) {
items.unshift(this.query); // Includes a new row with exact search query
return items.sort();
},
updater: function (item) {
document.location = "/companies/" + map[item].label.replace(/ /g, '-').toLowerCase() + "/" + map[item].id +
"/";
return item;
}
});

Ajax with map, getting data

I'm trying to use the $.map in ajax and I don't success with getting the data from json array. I'll show you the json file, the ajax code and the json output i get. Hope you can help me, thank you very much :) and sorry for my english! Here is the ajax:
$.ajax({
url: 'searchapi.php',
dataType: "jsonp",
data: {
featureClass: "P",
style: "full",
maxRows: 12,
name_startsWith: request.term
},
success: function( data ) {
response( $.map(data.table, function( item ) { //dont get this line!
return {
label: item.trid,
value: item.trid
}
}));
}
});
And here is the json file:
<?php
$host = "localhost";
$user = "root";
$pass = "";
$databaseName = "mydb";
$con = mysql_connect($host,$user,$pass);
$dbs = mysql_select_db($databaseName, $con);
$data = ("select * from table;");
$json = array();
$result = mysql_query($data);
while($row = mysql_fetch_array ($result))
{
$array = array(
'trid' => $row['name'],
);
array_push($json, $array);
}
$jsonstring = json_encode($json);
echo $jsonstring;
die();
?>
Here is the json output:
[{"name":"Emma"},{"name":"Eric"},{"name":"Peter"},{"name":"Sam"},{"name":"Roger"},{"name":"Sven"},{"name":"Julia"}]
You are referring to the wrong key, try it like this
$.map(data, function( item ) { //dont get this line!
return {
label: item.name,
value: item.name
}
})

Categories