Pass json array from php - javascript

I wast some hours searching solutions for my issue and I couldn't find an answer.
I'm making a search on same page and for that, I'm using Jquery, AJAX and PHP.
The array from php still return undefined.
PHP code:
$i=0;
while($eee = mysqli_fetch_array($result)) {
$array[$i][1] = $eee['ex'];
$array[$i][2] = $eee['ex'];
$array[$i][3] = $eee['ex'];
$array[$i][4] = $eee['ex'];
$array[$i][5] = $eee['ex'];
$array[$i][6] = $eee['ex'];
$array[$i][7] = $eee['ex'];
$i = $i + 1;
}
json_encode($array)
AJAX and JQUERY
jQuery(document).ready(function(){
$(document).on('submit', '#FormData', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
console.log(data[1]);
}
});
e.preventDefault();
});
});
Thanks for any help here ;)

in your php file use echo json_encode($array);
in your jquery
type: 'json',
method:'post'
,

Related

Send js varible to php file with ajax

I would like to send my variable "var targetId" to my php file.
I try to make ajax request but nothing happens.
My js file :
$( ".project_item" ).click(function(e){
var targ = e.target;
var targetId = targ.dataset.id;
console.log(targetId);
$('.popUp').fadeIn("200");
$('header, main, footer').addClass('blur');
$.ajax({
url: 'function.php',
type: "POST",
data: {idVoulu: targetId},
success: function(data){
alert(data);
console.log(data);
}
});
});`
And my php file to get the data
$idProject = (isset($_POST['idVoulu'])) ? $_POST['idVoulu'] : 0;
if($idProject==0) { echo ' ID not found';}
Can you tell me what's going wrong?
Well I can't Find a problem on your code but you can try this may be this will help you
var mydata = "idVoulu='+targetId+'"; // make a string
$.ajax({
url: 'function.php',
type: "POST",
data: mydata,
success: function(data){
alert(data);
console.log(data);
}
});
So, i made this and it works:
My js:
$( ".project_item" ).click(function(e) {
var targ = e.target;
var targetId = targ.dataset.id;
$('.popUp').fadeIn("200");
$('header, main, footer').addClass('blur');
$.post('../function.php', { id: targetId }, function(response) {
console.log("reponse : ", response)
});
My php :
if (isset($_POST['id'])) {
$newID = $_POST['id'];
$response = 'Format a response here' . $newID;
return print_r($response);
}

Send variable to php via ajax

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

Retrieving each variable posted by AJAX

I am storing my checkbox selections in an array then splitting each array and posting them using AJAX so my PHP function can use the posted id/ids to query my MySQL database.
First part of my JavaScript
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
alert(tbl);
This first part works as intended, where every time I click a checkbox the value is alerted.
AJAX post
$.ajax({
type: "POST",
url: "index.php",
data: "tbl=" + tbl
});
});
Finally my PHP
function describeTables() {
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}}
I don't get any vlaues of tbl even if I choose just one option. Why is this????
EDIT
My Checkbox
function showTables() {
if (isset ( $_GET ['db'] )) {
$db = $_GET ['db'];
$link = mysqli_connect ( 'localhost', 'root', '', $db );
$qry = "SHOW tables";
$tbl_list = mysqli_query ( $link, $qry );
echo '<ul>';
while ( $row = mysqli_fetch_array ( $tbl_list ) ) {
echo '<input type="checkbox" name="tbl[]" class="tbl_list" value="' . $row [0] . '" class="tablebox" />';
echo $row [0];
echo '<br>';
}
}
}
showTables ();
SECOND EDIT
After suggestions I have amended my code but now have a new problem where the page doesn't load #dbdisplay Below is my full JS code
if (!location.search.match(/db=[^&#]+/i)) {
$("#dbdisplay").show();
} else {
$("#qryDisplay").show();
}
$(document).on("change", ".checkbox", function () {
var db = $(this).val();
window.sessionStorage.setItem("db", db);
window.location.assign("index.php?db=" + db);
$("#dbdisplay").hide();
});
$('#tbl_list').click(function (event) {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
//alert(tbl);
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl': tbl }
});
});
The old function
/*
$(document).on("change", ".tablebox", function () {
var tbls = new Array();
$("input:checkbox[name='tbl[]']:checked").each(function () {
tbls.push($(this).val());
});
var tbl = tbls.join('|');
var yourDB = window.sessionStorage.getItem("db");
window.location.assign("index.php?db=" + yourDB + '&tbl=' + tbl);
});
*/
How do I fix this??
In ajax call, data has to be object data: {'tbl': tbl}
This should to the job
$.ajax({
type: "POST",
url: "someurl",
data: {"tbl=" + tbl}
});
http://api.jquery.com/jquery.getjson/
See here for documentation
First thing in your ajax call, data has to be object
data: {'tbl': tbl}
Secondly Ajax can't call php function directly
so your index.php file should be something like this without function
if (isset ( $_POST ['tbl'] )) {
$tbl = $_POST ['tbl'];
echo $tbl;
}
You should use "{ }" with data
$.ajax({
type: "POST",
url: "index.php",
data: {'tbl' : tbl}
});
or
$.ajax({
type: "POST",
url: "index.php&tbl="+tbl
});

Display array words in a span when success 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>\
&nbsp&nbsp<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>&nbsp&nbsp<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
}

What is the proper or best way to get data from ajax?

I have this javascript code with ajax.
$('#btnCart').click(function() {
var pName = document.getElementById('prodName').value;
$.ajax({
url: 'index.php',
data: 'prdName='+pName,
success: function(data) {
$('#prod').html(data);
}
});
});
I want to get the value of pName to be returned on my php. Here's my code on my index.php side:
<?php
$prodName = $_GET['prdName'];
echo $prodName;
?>
But it returns Unidentified index: prdName.
How can I get the value from ajax to my php? Please help...
if(isset($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo $prodName;
}
You should send the data as:
data: {prdName: pName},
add this to your PHP code:
if(!empty($_GET['prdName'])){
$prodName = $_GET['prdName'];
echo cartTable($prodName);
}
also some corrections in js:
$('#btnCart').click(function() {
var pName = $('#prodName').val();
$.ajax({
url: 'index.php',
data: {prdName:pName},
success: function(data) {
$('#prod').html(data);
}
});
});
In index.php Get the prdName value from $_POST[] global array.
to send data to index.php file add type type:'POST' in ajax code
$.ajax({
type:'POST',
url: 'index.php',
data: {'prdName': pName},
success: function(data) {
$('#prod').html(data);
}
});
or you can use $.post() method in jQuery
$.post(
'index.php',
{'prdName='+pName},
function(data) {
$('#prod').html(data);
}
});
in index.php
if(isset($_POST['prdName']){
$prodName = $_POST['prdName'];
echo $prodName;
}

Categories