ajax jquery and drupal not work, please see why - javascript

drupal 6: here is the code:
http://pastebin.com/GGVFfAGS
//getcity.js:
$(document).ready(function() {
$("#edit-field-house-geo-area-value").bind('change', function(){
selected_loc=$("#edit-field-house-geo-area-value option:selected").val();
var myURL="http://whatever.com/getajax/citys/"+selected_loc+"/";
$.ajax({
type: "GET",
url: myURL,
dataType: "json",
success: function(data){
console.log(data);
}
});
});
});
drupal module:
function sf_menu()
{
cache_clear_all();
$items = array ();
$items ['getajax/citys/%'] = array ('title' => 'This is my custom page', 'page callback' => 'sf_get_cities_ajax', 'access arguments' => array ('access content' ), 'access callback' => 'user_access', // TRUE will give access to everyone
'page arguments' => array (2 ), 'type' => MENU_CALLBACK );
return $items;
}
function sf_get_cities_ajax($cityid)
{
$termsarray = array ();
$terms = array ();
$cityid_safe = (int)$cityid;
$cityid_safe = check_plain($cityid_safe);
if (is_number($cityid_safe)) {
$terms = taxonomy_get_children($cityid_safe, 143, 'tid');
if (count($terms)) {
foreach ($termsarray as $k => $v) {
$termsarray [check_plain($k)] = t($v [tid]);
}
$f= array('status' => 1, 'data' => $termsarray,'moo'=>'sadasdsd');
print drupal_json($f);
exit();
}
}
}
its not return me somthing even i print the 'moo' data
its my function its working fine i get array at the final but its dont pass it

That looks like it should work except one thing... PHP doesn't have a function 'is_number()' so unless you wrote your own you need to change your IF statement to use PHP built in 'is_numeric':
if (is_numeric($cityid_safe)) {
Its not a JS issue at all.

Related

How to change how my JSON looks

I have an AJAX call that makes my JSON look this in my JSON file:
{
"main_object": {
"id": "new",
"formData": "language=nl_NL&getExerciseTitle=test&question_takeAudio_exerciseWord%5B0%5D=test&Syllablescounter%5B0%5D=test&Syllablescounter%5B1%5D=test"
}
}
But I would like to have it like this (and this was before I changed my AJAX call with: id: getUrlParameter('id'):
{
"main_object": {
"language": "nl_NL",
"getExerciseTitle": "asd",
"question_takeAudio_exerciseWord": ["asd"],
"Syllablescounter": ["ASDasd", ""]
}
}
The only thing I want to add is the "id": "new", but when I do so (with id: getUrlParameter('id') it gets the id, but it messes up my code.
This is my AJAX call (my JSON starts looking like the first piece of code when I use this)
function saveExerciseAjaxCall() {
$("#my_form").on("submit", function(event) {
event.preventDefault();
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: {
id: getUrlParameter('id'),
formData: $('#my_form').serialize()
},
dataType: 'json',
}).done(function(response) {
});
});
}
How could this be achieved? I know it isn't my saveJson.php that's the problem. I know it's my AJAX call since it starts showing like the first JSON piece of code when I add the id: getUrlParameter('id').
edit: Since someone said it could be my php code.. here is my php code:
<?php
include_once('database_json.php');
$data = $_POST;
//Setup an empty array.
$errors = array();
if (isset($data)) {
$newExerciseData['main_object'] = $data;
$exerciseArray = $data['main_object'];
$databaseFile = 'json_files/database.json';
$textContent = file_get_contents($databaseFile);
$database = json_decode($textContent, true);
if ($data['id'] === 'new') {
if (count($database['data']) == 0) {
$ID = 0;
} // ending database['data'] count 0.
else {
$maxID = max($database['data']);
$ID = ++$maxID["id"];
} // ending the max ID else statement.
$newJsonFile = 'jsonData_' . $ID . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData = array(
'id' => $ID,
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][] = $newArrayData;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE, JSON_PRETTY_PRINT));
} // } op regel 34 lijkt verdwaald...?
else {
$index = array_search((int) $_POST['id'], array_column($database['data'], 'id'));
$correctJsonFile = 'json_files/jsonData_' . $_POST['id'] . '.json';
$newJsonFile = 'jsonData_' . $_POST['id'] . '.json';
$newJsonFilePath = 'json_files/' . $newJsonFile;
//Create new database exercise_txt
$newArrayData2 = array(
'id' => (int) $data['id'],
'exercisetitle' => $data['formData']['getExerciseTitle'],
'language' => $data['formData']['language'],
'file' => $newJsonFile
);
$database['data'][$index] = $newArrayData2;
file_put_contents($databaseFile, json_encode($database, JSON_UNESCAPED_UNICODE));
file_put_contents($newJsonFilePath, json_encode($newExerciseData, JSON_UNESCAPED_UNICODE));
} // closing off the else statement
echo json_encode($newExerciseData, JSON_UNESCAPED_UNICODE);
} //closing off the if isset.
?>
you can use parse_str($str, $output); it will help you achieve what you need.
Note that parse_str takes two parameters, the first one is the string (get Parameters), second one is the array to return the result on. you can use the below code
parse_str($str, $output);
echo json_encode($output);
The issue is how you process formData parameter. serialize() is building url encoded string, however you want key-value pairs. Try this:
$("#my_form").on("submit", function(event) {
event.preventDefault();
var myData = {id: getUrlParameter('id')};
for (var pair of formData.entries()) {
myData[pair[0]] = pair[1];
}
$.ajax({
url: 'saveJson.php',
type: 'POST',
data: myData,
dataType: 'json',
}).done(function(response) {
window.location = 'index.php';
});
});
}

JQuery Ajax goes in error

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 :)

Uncaught error:Cannot use 'in' operator to search for 'length' in

When I trying to return the inserted image as json I'm getting error like Cannot use in operator to search for length
Ajax code:
$("#imagesform").submit(function(){
$.ajaxSetup({
headers: { 'X-CSRF-TOKEN':
$('meta[name="_token"]').attr('content')
}
});
$.ajax({
url :"{{url('addImages/').'/'}}" + imagesProductId,
type: 'POST',
data:new FormData($("#imagesform").get(0)),
contentType:false,
processData:false,
success: function (data)
{
//alert(data);
//alert(json.parse(data));
$.each(data, function( index, value ) {
$("#insertedImages").append('<img src="'+value+'" width="75"
height="75" class="upload2"><br>');
alert(value);
});
},
});
return false;
});
Here the images get inserted into db.But while returning to the view and trying to display it with the div tag shows error..(specified above)
Controller:
public function addImages(Request $request,$imagesProductId)
{
$product = Product::create($request->all());
$filenames = array();
if (empty($request->images)) {
return Redirect::back()->withErrors(['msg', 'The Message']);
}
$rules = [
'images'=>'required'
];
$validator = Validator::make($request->all(), $rules);
$result = $validator->fails() ? 'QCFailed' : 'QCVerified';
// echo($result);
foreach ($request->images as $photo) {
$filename = $photo->store('public/uploadedImages');
$filename = substr($filename,22);
$filenames[] = asset('storage/uploadedImages/'.$filename);
ProductsPhoto::create([
'product_id' => $product->id,
'productId'=>$imagesProductId,
'nonliveStatus' => $result,
'filename' => $filename
]);
}
return response()->json($filename);
}
This is my controller function for inserting array of images and I'm returning the same to the view and trying to append it using div tag.

FullCalendar: receive error while trying to display events using json file

Following is my JSON file:
<?php
$driver_booking = q("select * from vehicle_driver_booking where vehicle_id = ".$_REQUEST['ch']);
$array = array();
foreach($driver_booking as $bookings) {
$driver = getRow("vehicle_driver", $bookings['driver_id']);
//return date_time from only....
$date_from = date("Y-m-d",$bookings['datetime_from']);
$time_from = date("H:i:s",$bookings['datetime_from']);
//return date_time to only.....
$date_to = date("Y-m-d",$bookings['datetime_to']);
$time_to = date("H:i:s",$bookings['datetime_to']);
if($bookings['days_option'] == 1) {
$start = $date_from."T".$time_from;
$array[] = array('id' => $bookings['id'], 'title' => $driver['name'], 'start' => $start, 'allDay' => false);
} else {
$start = $date_from."T".$time_from;
$end = $date_to."T".$time_to;
$array[] = array('id' => $bookings['id'], 'title' => $driver['name'], 'start' => $start, 'end' => $end, 'allDay' => false);
}
}
echo json_encode($array);
?>
Following is part of the calendar where I am trying to get json data from above file.
eventSources: [
// your event source
{
url: '/vehicle_json.php',
type: 'POST',
data: {
// custom_param1: 'something',
//custom_param2: 'somethingelse'
},
error: function() {
alert('there was an error while fetching events!');
},
color: 'yellow', // a non-ajax option
textColor: 'black' // a non-ajax option
}
// any other sources...
],
or I tried with this following way as well...but not worked and above give me alert message and following give me nothing at all.
events: 'vehicle_json.php',
& once if above issue will resolve then I also wanted to update my events through using following where when the record save it refresh the events to show the update ones.
$.ajax({
url: "save_booking_details.php",
type: "POST",
data: {booking_id: bookingid, date_single: datesingle, date_from: datefrom, date_to: dateto},
success: function(data){
//alert(data);
//location.reload();
//$('#calendar').fullCalendar('removeEventSource', curSource[0]);
//$('#calendar').fullCalendar('removeEventSource', curSource[0]);
$('#calendar').fullCalendar('refetchEvents');
//Calendar.init();
//setTimeout(function(){ Calendar.init(); }, 10000);
}, error: function() {
alert("something went wrong!");
}
});
So can someone please help as I am looking for solution since yesterday thank you guys in advanced.
You have to provide a parameter called ch. Not sure what it is
data: {
'ch': "something I don't know"
},

Wordpress ajax returning html

Am using WordPress ajax to load the sub-categories dynamically.
Here's my code
Php code
function techento_getsubcat() {
$category_name = $_POST['catname'];
$cat_id = $_POST['catid'];
return wp_dropdown_categories( 'show_option_none=Choose a Sub Category&tab_index=10&taxonomy=category&hide_empty=0&child_of=' . $cat_id . '' );
}
add_action('wp_ajax_techento_getsubcat', 'techento_getsubcat');
add_action('wp_ajax_nopriv_techento_getsubcat', 'techento_getsubcat');
Jquery
jQuery(document).ready(function(){
$('#cat').change(function(e){
alert("changed");
$.ajax({
type: 'POST',
dataType: 'json',
url: pcAjax.ajaxurl ,
data: {
'action': 'techento_getsubcat', //calls wp_ajax_nopriv_ajaxlogin
'catname': $('#cat option:selected').text(),
'catid': $('#cat option:selected').val() },
success : function(response){
alert(response);
console.log(response);
$("#subcats").html(response);
}
});
e.preventDefault();
});
});
The problem with the above code is that php returns the raw html irrespective of the thing asked to return
even if set it to
return true;
it then returns the raw html of subcategories generated plus '0'
You're missing the $ shortcode in
jQuery(document).ready(function($){
The Ajax callback is better handled by wp_send_json_success(), so we don't have to worry with return or echo, exit or die. For that, set echo to false in the dropdown arguments:
function techento_getsubcat() {
$cat_id = intval( $_POST['catid'] );
$args = array(
'hide_empty' => 0,
'echo' => 0,
'child_of' => $cat_id,
'taxonomy' => 'category'
);
$data = wp_dropdown_categories( $args );
wp_send_json_success( $data );
}
On Ajax success, use response.data:
success : function(response){
console.log(response.data);
}

Categories