I have a data which i use PHP to access them. So i created a simple button, when i click on it, my programm needs to create a table with the data. Below you can see the jQuery Code to read the data, and also create a table. But the problem is, i can not access the each element in the DATA.
I want to make clear because of that i also add the code, which i make the selection in data. Its called "household.php"
<html lang="en">
<head>
<script
src="https://code.jquery.com/jquery-3.6.2.js"
integrity="sha256-pkn2CUZmheSeyssYw3vMp1+xyub4m+e+QK4sQskvuo4="
crossorigin="anonymous"></script>
<link rel="stylesheet" href="style.css">
<script>
function suchen() {
jQuery(document).ready(function($) {
$.ajax({
type: "get",
url: "household.php",
dataType: "json",
success: function(response) {
var data = JSON.parse(response)
var html_table = "";
data.forEach(function(item) {
var row = $("<tr>");
row.append($("<td>").text(item.contact_id_a));
row.append($("<td>").text(item.contact_id_b));
// add more cells for additional columns
html_table += row[0].outerHTML;
});
$("#tabelle").html(html_table);
}
});
});
}
</script>
</head>
<body>
<form id="form" onsubmit="suchen()" method="get">
<label>Enter your age: </label>
<br />
<input type="number" name="min" min="0">
<br />
<input type="number" name="max" min="0">
<br />
<input type="submit">
</form>
<div id="tabelle"></div>
</body>
</html>
Here's the code for household.php file. It works without problem. But i can not connect between my main php file.
<?php
require_once '/var/www/html/wordpress/wp-content/plugins/civicrm/civicrm/civicrm.config.php';
require_once 'CRM/Core/Config.php';
$config = CRM_Core_Config::singleton();
$relationships = \Civi\Api4\Relationship::get()
->addSelect('contact_id_a', 'contact_id_b', 'contact_id_a.display_name', 'contact_id_b.household_name', 'relationship_type_id')
->addClause('OR', ['relationship_type_id', '=', 7], ['relationship_type_id', '=', 8])
->setLimit(25)
->execute();
foreach ($relationships as $relationship) {
// do something
}
var_dump(json_encode($relationships));
?>
i can not access the data with php file. I also can not connect my main php file, with searching php.
I think you already used echo json_encode($relationships) in household.php file. You don't need the parse the response (you used ) because you already write dataType to json. it would automatically be converted. Hope this answer to help you. According to jQuery Manual, "any malformed JSON is rejected and a parse error is thrown. As of jQuery 1.9, an empty response is also rejected". So you can use dataType: 'json' only, if you're sure, that server will return poperly formatted JSON. If it only returns "a string, that looks like JSON", you should use dataType: "text json" to force jQuery conversion.
[NOTE] If above answer doesn't help you, I suggest that you use this function for parsing response. var data = jQuery.parseJSON(response); or var data = $.parseJSON(response)
Related
I am building a budget application with HTML, Javascript, and PHP. My goal is to have the user be able to add data into a database from a form provided. I already have a ton of php at the top of my 'dashboard.php' (which contains the form) so I didn't want to run dashboard.php on submit, so instead I created a button that preforms an AJAX call to a different php file 'addIncome.php'.
I have two different files...
dashboard.php &
addincome.php
dashboard.php contains my form, as well as my javascript to run an AJAX call.
addincome.php is using $_POST to grab the values from the form in dashboard.php and make a mysqli_query. However, at first nothing was happening so I decided to echo the value of one of the return values from my $_POST. And ended up getting this error...
undefined index iName in addIncome.php
undefined index iAmount in addIncome.php
So from there I though that maybe I didn't have access to the dashboard.php by default so I included...
include('dashboard.php');
Still no difference...
I'm really at a stand still here. Any thoughts?
Thanks
The form...
<form>
<input type="text" name="iName" placeholder="income name">
<input type="number" step="0.01" min="0" name="iAmount" placeholder="amount">
<input type="date" name="iDate">
</form>
The javascript...
<script>
$('.in-btn').click(function() {
$.ajax({
url: "addIncome.php",
type: "POST",
data: 'show=content',
success: function(data) {
$('.in-btn').html(data);
}
});
setTimeout(() => {
// location.reload();
}, 2000);
});
</script>
The php...
<?php
echo "adding...";
require_once('connection.php');
include('dashboard.php');
$iUser = $_SESSION["username"];
$iName = $_POST["iName"];
$iAmount = $_POST["iAmount"];
echo $iName;
$sql = "INSERT INTO income (user, name, amount, date) VALUE ('pmanke', '$iName', '$iAmount','1/16/19')";
mysqli_query($dbCon, $sql);
?>
You are not sending any post data with your AJAX call except for:
show=content. You want to send your form data. You can retrieve your form data with:
$("#id-of-form").serialize()
That way your PHP code is able to retrieve the correct values from your POST data.
An even more general way to do this is to just create a normal form with a submit button and an action and use javascript to catch the submit event and make an AJAX call instead:
HTML:
<form id="idForm" action="addIncome.php">
<input type="text" name="iName" placeholder="income name">
<input type="number" step="0.01" min="0" name="iAmount" placeholder="amount">
<input type="date" name="iDate">
<input type="submit" />
</form>
Javascript:
$("#idForm").submit(function(e) {
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "POST",
url: url,
data: form.serialize(), // serializes the form's elements.
success: function(data) {
alert(data); // show response from the php script.
}
});
e.preventDefault(); // avoid to execute the actual submit of the form.
});
I would like to build a newsletter subscription function to my website. and I want to get all the input save into a txt file in the host folder. However, I don't want to switch page after people submit it. Just show a popup message saying "Thank You for Subscribing" will be perfect. I know how to do it with PHP to show a message in a separate page, but not sure how to do it in a popup box. Here is my html and PHP code. Please help, thanks a lot.
<html>
<head>
<title></title>
</head>
<body>
<form>
<form action="myprocessingscript.php" method="post">
<input name="field1" type="text" />
<input name="field2" type="text" />
<input type="submit" name="submit" value="Save Data">
</form>
<a href='data.txt'>Text file</a>
</body>
PHP function is
<?php
if(isset($_POST['field1']) && isset($_POST['field2'])) {
$data = $_POST['field1'] . '-' . $_POST['field2'] . "\n";
$ret = file_put_contents('/tmp/mydata.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
}
else {
echo "$ret bytes written to file";
}
}
else {
die('no post data to process');
}
Once you have included jQuery to your page, something like following should work:
// process the form
$('form').submit(function(event) {
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'field1' : $('input[name=field1]').val(),
'field2' : $('input[name=field2]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'myprocessingscript.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// data is the output from your php, check it and display alert appropriately
// here we will handle errors and validation messages
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
Take a look at source article
Im trying to pass and return an array to and from a php script, I've tested the json_ecode portion and its working but I can't get the json_decode on the php side.
Javascript
scid_list = [];
$('.filter_on').each(function(){scid_list.push($(this).data("scid"));});
$.ajax({
type: "POST",
dataType: "json",
data: {scid_list:scid_list},
url: "/scripts/products_filter.php",
success: function(data){
alert(data.join('\n'));
}
});
PHP
<?php
$scid_list=(json_decode($_POST['scid_list'], true));
echo json_encode($scid_list);
exit();
?>
Ive also tried leaving out the true on decode
$scid_list=(json_decode($_POST['scid_list']);
and not decoding it at all
$scid_list=$_POST['scid_list'];
I'm not sure what I'm missing. I've tried playing around with serializing the data too but read I didn't have to if you specify the dataType as json, I tried using stripslashes
Any help is appreciated!
Cheers
I think the problem is that the data you're sending isn't json even though you're specifying it on the Ajax call. As it's only a 2-dimensional array you're getting, why don't you just use Array.join in your JS before doing the post:
var scids = scid_list.join(',');
That would turn it in to a comma separated string. e.g.
"id1,id2..."
You can simplify the Ajax call a bit too:
$.post('/scripts/products_filter.php', {scids: scids}, function(data) {
// process data response here
});
Then in your PHP file you can use explode() to turn it back in to an array:
$ids = explode(",",$_POST["scids"]);
foreach ($ids as $id) {
// Do something with the array of ids.
};
Hope that all makes sense.
Your dataType parameter specifies that you expect JSON data in response, but it does not mean you are sending data as JSON. In your case you are sending an array, therefor in PHP instead of:
$scid_list=(json_decode($_POST['scid_list'], true)); /* WRONG */
you should simply use:
$scid_list=$_POST['scid_list'];
dataType (default: Intelligent Guess (xml, json, script, or html))
Type: String The type of data that you're expecting back from the
server.
Alltogether, for given HTML:
<form action="work.php" method="post">
<p><input class="filter_on" data-scid="22" type="checkbox" /> Filter 22</p>
<p><input class="filter_on" data-scid="28" type="checkbox" /> Filter 28</p>
<p><input class="filter_on" data-scid="31" type="checkbox" /> Filter 31</p>
<p><input type="submit" value="Send" /></p>
</form>
and SCRIPT:
$(document).on('ready', function() {
$('form').on('submit', function(e) {
e.preventDefault();
scid_list = [];
$('.filter_on:checked').each(function(i){
scid_list.push( $(this).data("scid") );
});
$.ajax({
type: "POST",
dataType: "json",
data: {scid_list:scid_list},
url: "work.php",
success: function(data){
alert(data.join('\n'));
}
});
});
});
PHP part is:
$scid_list=$_POST['scid_list'];
echo json_encode($scid_list);
exit();
I want to have an HTML form that posts the following in an Http-request body.
{ “info” : {
“id” : “123”
“text1” : <comes from html text-box>
}
So, what I want is to formulate the above as a JavaScript Object, and then post this JavaScript object on submit. The value of “text1” will be coming from user input, that will be an html-form textarea input box. The first value “id” will be hard-coded, or could also come from a hidden text-box.
So my question is: how can I write a piece of JavaScript to achieve this, together with the corresponding html form, etc.
It is easiest to do this using jQuery.
First, initialize a JavaScript object with your data. Then, use jQuery to extract the text from the text box and assign it to the desired property in your object.
var data = {
"info": {
"id":"123",
"text1":""
}
};
data.info.text1 = $("#yourTextBox").val();
Then you can use jQuery.ajax to make the request:
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
See the jQuery documentation for posts:
http://api.jquery.com/jQuery.post/
EDIT:
Using inline javascript, your HTML would look something like this (not using jQuery to grab the form data):
<html>
<head>
<script>
var data = {
"info": {
"id":"123",
"text1":""
}
};
function makeRequest()
{
data.info.text1 = document.forms["frm1"]["fname"].value;
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
}
</script>
</head>
<body>
<form name="frm1" id="yourTextBox" onsubmit="makeRequest()">
<input type="text" name="fname">
<input type="submit" value="Submit">
</form>
</body>
</html>
<html>
<head>
<script>
function sendJson()
{
var x=document.forms["alfa"]["text1"].value;
str1="{ 'info' : { 'id' : '123' 'text1' : ";
str2=str1.concat(x);
body=str2.concat(" }");
document.forms["alfa"]["text1"].value=body;
}
</script>
</head>
<body>
<form id="alfa" onsubmit="return sendJson()">
Text1: <input id="text1" type=text size=50>
<input type="submit" value="Submit">
</form>
</body>
</html>
The best way is to use JSON.parse()
What I am trying to do is retrieve JSON data from an online web service that searches and finds a certain string in a MySQL database and display it using Javascript on an HTML page.
What I am struggling with is actually displaying the resulting data.
The relevant areas of my HTML page looks like this:
<form onSubmit="results()">
<fieldset>
<label for="area">First digits of postal code:</label>
<input name="area" type="text" maxlength="4" placeholder="AB12" required />
<input type="submit" value="Search" name="search" />
</fieldset>
</form>
<script type="text/javascript" src="jquery/jquery.min.js"></script>
<script type="text/javascript" src="cordova-2.3.0.js"></script>
<script type="text/javascript" src="js/index.js"></script>
<script type="text/javascript">
function results(){
$.ajax({
url: 'http://www.foobar.com/cp/index.php?area=AB12',
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data, status){
$.each(data, function(i,item){
var place = '<h1>'+item.location+'</h1>'
+ '<p>'+item.id+'</br>';
output.append(place);
});
},
error: function(){
output.text('There was an error loading the data.');
}
});
};
</script>
<div id="place">
<h3>Places near your location</h3>
</div>
The page for the GET data is http://www.foobar.com/cp/index.php with the search variable 'area'. Test sample is ?area=AB12.
It seems that this service is not correctly wrapping the JSON object in parentheses so it doesn't work as JSONP.
See: http://www.entertainmentcocktail.com/cp/index.php?area=AB12&jsoncallback=TEST
It returns:
TEST[{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]
while it should return:
TEST([{"id":"5","name":"The Red Lion", ... ,"confirmed":"0"}]);
You won't be able to use it because it is not valid JSONP.
UPDATE:
Answering more info from the comment - if you control the server-side script then try changing:
while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . json_encode($records);
to:
while($row = mysql_fetch_assoc($result)) { $records[] = $row; }
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
and see if that works.
UPDATE 2:
Answering another comment. Do you actually initialize the output variable? For example with something like this at the beginning:
var output = $('#place').append('<div/>');
Do you actually call your results function? It must be called with:
results();
or registered somewhere as an event handler, using the jQuery way:
$('form').submit(results);
but then add:
return false;
to the end of the results function to prevent the page from being reloaded.
See this demo: http://jsbin.com/uziyek/1/edit - it seems to work.
Another problem:
There seems to be another problem with your code, that the area=AB12 parameter is hardcoded into your URL. What you should do instead is get the value from the form and send that.
You implemented JSONP incorrectly. You need to generate a function call, i.e. the response should be foo(<json here>); not foo<json here>.
It is trivial to fix:
echo $_GET['jsoncallback'] . '(' . json_encode($records) . ');';
Another problem is that you are not preventing the form submission, i.e. when you submit the form, the page refreshes. You have to prevent that. Better bind the event handler with jQuery and don't use inline event handlers:
<form id="myForm">
and
$(function() {
$('#myForm').submit(function(event) {
event.preventDefault(); // <-- prevent form submission
// Ajax call here
});
});
DEMO