I'm trying to fill two text boxes with a single ajax whisperer. I got the following code:
HTML:
<input type="text" name="ICZ" id="ICZ">
<input type="text" name="ODB" id="ODB">
respond.php:
<?php
require_once("../inc/dbconnect.php");
$return_arr = array();
$term=iconv('UTF-8' ,'WINDOWS-1250',$_GET["term"]);
$SQL="some sql";
$RS=sqlsrv_query($Conn,$SQL);
while($row=sqlsrv_fetch_array($RS)) {
$id_lekar=iconv('WINDOWS-1250', 'UTF-8',$row["ID_LEKAR"]);
$jmeno=iconv('WINDOWS-1250', 'UTF-8',$row["JMENO"]);
$odborn=iconv('WINDOWS-1250', 'UTF-8',$row["ODBORN"]);
$row_array['value'] = $id_lekar;
$row_array['value1'] = $odborn;
$row_array['label'] = $id_lekar." - ".$jmeno." - ".$odborn;
array_push($return_arr,$row_array);
}
sqlsrv_close($Conn);
echo json_encode($return_arr);
?>
and jQuery:
$(function() {$('#ICZ').autocomplete({
source: 'respond.php',
minLength:5
});
});
This works but only affect one input field. I would like to fill both so I extend SQL query and extend respond.php with $row_array['value1']. Then I try to redone jQuery:
$(function() {$('#ICZ').autocomplete({
minLength: 5,
source: function(request, response){
$.ajax({
url: "respond.php",
type: "GET",
dataType: "json",
data: {term: request.term},
success:function(response){
var len = response.lenght;
if (len > 0){
var icz = response[0]['value'];
var odb = response[0]['value1'];
document.getElementById('ICZ').value = icz;
document.getElementById('ODB').value = odb;
}
}
});
}
});
});
But this just doesn't do much, no errors in console, I can see the GET request going on when I fill the field with 5 and more characters, but no response. When I try access respond.php?term=XXXXX I'm getting same response in both ways.
use JSON.parse
$.ajax({
url: "respond.php",
type: "GET",
dataType: "json",
data: {term: request.term},
success:function(response){
var response=JSON.parse(response); // parse json to object
var len = response.length;
if (len > 0){
var icz = response[0].value;
var odb = response[0].value1; //access values like this
document.getElementById('ICZ').value = icz;
document.getElementById('ODB').value = odb;
}
}
});
Look if you need to parse json. Print response in console and check if you need to parse it.
Var result =JSON.parse(response);
Related
I'm trying to send a input value to php via ajax but I can't seem to get this right. I'm trying to create a datatable based on the user input.
This is my code:
<input class="form-control" id="id1" type="text" name="id1">
My javascript code:
<script type="text/javascript">
$(document).ready(function() {
var oTable = $('#jsontable').dataTable(); //Initialize the datatable
$('#load').on('click',function(){
var user = $(this).attr('id');
if(user != '')
{
$.ajax({
url: 'response.php?method=fetchdata',
data: {url: $('#id1').val()},
dataType: 'json',
success: function(s){
console.log(s);
oTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
oTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
} // End For
},
error: function(e){
console.log(e.responseText);
}
});
}
});
});
</script>
My php script:
<?php
$conn = pg_connect(...);
$id1 = $_POST["id1"];
$result = pg_query_params($conn, 'SELECT * FROM t WHERE id1 = $1 LIMIT 20', array($id1));
while($fetch = pg_fetch_row($result)) {
$output[] = array ($fetch[0],$fetch[1],$fetch[2],$fetch[3],$fetch[4],$fetch[5],$fetch[6],$fetch[7]);
}
echo json_encode($output);
?>
I don't know a lot of js but my php is correct i test it. So i guess the problem is in the javascript code.
The problem is, my datatable is not being created based on the user input.
Thank you!
change
data: {url: $('#id1').val()},
to:
type: 'POST',
data: {id1: $('#id1').val()},
However the problem might be bigger. You might not be getting the correct data from PHP. You can debug by adding the error option to your ajax() call, like this:
$.ajax({
url: 'response.php?method=fetchdata',
type: 'POST',
data: {id1: $('#id1').val()},
dataType: 'json',
success: function(s){
},
error: function (xhr, status, errorThrown) {
console.log(xhr.status);
console.log(xhr.responseText);
}
});
Then check your browser's Console for the output, this should give you some type of error message coming from PHP.
My assumption is that since you are using dataType: 'json', the ajax request expects JSON headers back, but PHP is sending HTML/Text. To fix, add the correct headers before echoing your JSON:
header('Content-Type: application/json');
echo json_encode($output);
I need some help. I am trying to send multiply array of width and length to php, straight forward. I don't want to save it to any HTML field, however it's not working. I am getting the width and length from html text are and convert it to a number and then add it to an array in javascript.
Here is the code for that
var widthL = [];
var lengthL = [];
var widths = document.wall.width.value;
var lengths = document.wall.length.value;
var wNumber = Number(widths);
var lNumber = Number(lengths);
widthL.push(JSON.stringify(wNumber));
lengthL.push(JSON.stringify(lNumber));
This is the Ajax code I am using to send it to PHP
$.ajax( {
type: "POST",
url: "./Summary.php",
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
In PHP I am using this code to receive it. But I am not getting things back.
<?php
$lengths = json_decode($_POST['lengths']);
$widths = json_decode($_POST['widths']);
echo 'This is the width: '.$widtsL;
echo 'This is the length: '.$lengths;
?>
I was hopping that someone could help me out here.
First you should specify the content type in the ajax POST:
$.ajax( {
type: "POST",
url: "./Summary.php",
contentType: "application/json; charset=UTF-8", // Add content type
data: {"widths": widthL, "lengths" : lengthL},
cache: false,
success: function (response) {
console.log("This is the width", widthL, " This is the length", lengthL);
}
});
then in PHP:
$request_body = file_get_contents('php://input'); //This reads the raw POST data
$json = json_decode($request_body); // Then parse it to JSON
$lengths = $json->lengths;
$widths = $json->widths;
please add a POST parameter name as dataType,type it value JSON,
the Ajax data param value use key=value&key=value format
then in php file enter debug code
I have some page with form, which loading some data to POST when i submit it. Then it links user to the next page. On this page I catch data from POST, and I have two dropdownlists, where the second one depends on the first. The first get's value from POST data:
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'"); </script>';
Where $GLOBALS["i"] = id from DB, which has kept in data from POST by previous page.
But it doesn't work for the second dropdownlist which depends on it:
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
I think it can be from the part of code, which realises depending of the second dropdown list:
<script>
jQuery(function(){
var id = jQuery(".mark").val();
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
jQuery(".mark").change(function(){
var id = jQuery(".mark").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
});
Where "mark" - first dropdownlist, "comm" - the second one.
This is the first part of my problem.
The second: I have some value on the page which depends on the value of the second dropdownlist. I tried to:
jQuery(".comm").change(function(){
var id = jQuery(".comm").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function(data){
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type:"POST",
url: "../wp-content/price.php",
data: {price1: price1,price2: price2,price3: price3,price4: price4,price5: price5,price6: price6,price7: price7,price8: price8, price9: data},
success: function(data){
jQuery(".summPrice").html(data);
}
});
}
});
But it works only one time, and i don't know why.
I'll be glad for any offers.
I don't have a full visibility of the rendered html and of the ajax responses, but I would give a try with:
Remove this lines
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'");
</script>';
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
And do something like this where you print the html
...
<select id="markid" data-val="<?php echo isset($GLOBALS["i"]) ? $GLOBALS["i"] : -1;?>"></select>
<select id="comm" data-val="<?php echo isset($GLOBALS["i1"]) ? $GLOBALS["i1"] : -1;?>"></select>
And in your javascript have something like
<script>
(function ($) {
//when everything is ready
$(fillUpCommOptions);
$(watchSelectsChanges);
function fillUpCommOptions() {
var id = $('#markid').data('val') ? $('#markid').data('val') : $('#markid').val();
$('#markid').removeAttr('data-val');//remove data-val, at next change event we want the select new val
$.ajax({
type: "POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function (data) {
//assuming data is something like
// '<option value="niceValue">nice value</option>
$("#comm").html(data);
if ($("#comm").data('val')) {
//apply values from post also for the second dropdown
// assuming that data contains and option with value == $("#comm").data('val')
$("#comm").val($("#comm").data('val'));
$('#comm').removeAttr('data-val');
$("#comm").change()//trigger change after setting the value
}
}
});
}
function watchSelectsChanges() {
$('#markid')
.off('change')//just in case, could not be needed
.on('change', fillUpCommOptions);
$('#comm')
.off('change')//just in case, could not be needed
.on('change', handleDependentValues);
}
function handleDependentValues() {
var id = $("#comm").val();
if (id) {
$.ajax({
type: "POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function (data) {
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type: "POST",
url: "../wp-content/price.php",
data: {
price1: price1,
price2: price2,
price3: price3,
price4: price4,
price5: price5,
price6: price6,
price7: price7,
price8: price8,
price9: data
},
success: function (data) {
jQuery(".summPrice").html(data);
}
});
}
})
}
}
})(jQuery);
I'm trying to call an AJAX query and have had lots of trouble recently.
Im trying to call a api that I have custom made myself, it displays this when the url api/reverse/test - tset (is just uses a php function to reverse the text given in the slug3.
That function works fine, just wanted to give some back on what gets requested.
reverse.php - HTML File
<textarea id="input"></textarea>
<div id="output">
</div>
index.js - All of my jQuery and AJAX
$(document).ready(function(){
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function(){
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; },
error: alert('fail')
}) // End of AJAX
$output.html = output;
});
});
api.php - PHP file being called
<?php
$area = $_GET['area'];
if ($area == 'reverse') {
if (isset($_GET['text']) ) $text = $_GET['text'];
else $text = 'Hello';
echo strrev($text);
}
It's then supposed to take the output variable and display that in a div but that's not the main thing that matters.
error removed - was trying to see if it fixed it
There are several issue I found:
Jquery:
var text = $('#input').val(); // if you are getting value from any inputbox - get value using .val() function
var url = 'http://localhost/test.php?data='+text; // pass data like this ?data='+text
// AJAX START
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
async: true,
success: function(data) { var output = data; alert(output)},
error: function(data) { alert('fail') }
});
In php you ca get data like this:
echo $_GET['data'];
exit;
Try this. Scope of variable output is within the success call and you are using it outside the ajax call.
$(document).ready(function()
{
var $input = $('#input');
var $output = $('#output');
$input.on('keyup', function()
{
var text = $input.val();
var url = 'http://coder.jekoder.com/api/?area=reverse&text='+text;
$.ajax({
type: 'GET',
url: url,
dataType: 'text',
success: function(data) { var output = data; $output.html = output;},
error: alert('fail')
}) // End of AJAX
});
});
I have this codes that will display words with checkbox. As you can see they are delimited by comma, and I used split() function to explode the string making it an array. I used for loop to iterate the words, but I'm getting an "undefined" for the words. It should automatically display the words with checkbox but the words display undefined. When I hit refresh, it displays the word properly and the there is a checkbox. I'm not sure where is the problem. Any idea on this?
$(document).on('click', '#wordlistsave', function()
{
var user = $("#getUser").val();
var title = $("#wordbanktitle").val();
var word = $("#wordbanklist").val();
var postID = $("#getPostID").val();
var words = word.split(", ");
for(var i = 0; i < words.length; i++)
{
var dataString = 'user='+user+'&title='+title+'&words='+words[i]+'&id='+postID;
<?php if (is_user_logged_in()): ?>
if(words[i])
{
$.ajax({
type: "POST",
url: "<?= plugins_url('wordlistsave.php', __FILE__) ?>",
data: dataString,
cache: true,
success: function(postID)
{
var testBoxDiv = $(document.createElement('div')).attr("id", words[i]);
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+words[i]+'" style="cursor:pointer">\
<img src="./wp-content/plugins/wordwork/admin/pdfpreview/delete_icon.png" title="Delete word"></span>\
  <input type="checkbox" name="words[]" value="'+ words[i]+ '">'+words[i] );
testBoxDiv.appendTo("#test_container");
}
});
}
<?php else: ?>
alert('Please login.');
<?php endif; ?>
}
});
words is visible from success function, but when it executes you can't be sure for i value because it doesn't execute syncronously.
So, you can pass an extra param, words, to ajax setup dictionary and access it from success function. Like this:
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: dataString,
cache: true,
word : words[i],
success: function(postID)
{
var testBoxDiv = $(document.createElement('div')).attr("id", this.word);
testBoxDiv.css({"margin-bottom":"5px"});
testBoxDiv.after().html('<span id="'+this.word+'" style="cursor:pointer"><img src="./wp-content/plugins/wordwork/admin/pdfpreview/delete_icon.png" title="Delete word"></span>  <input type="checkbox" name="words[]" value="'+ this.word+ '">'+this.word );
testBoxDiv.appendTo("#test_container");
}
});
Also, you do not need to construct the data string for $.ajax, you can simply pass the data like:
$.ajax({
type: "POST",
url: "<?=plugins_url('wordlistsave.php', __FILE__ )?>",
data: {
user: user,
title: title,
words: words[i],
id: postID
}