Advanced Contact Fields not updating repeater field in separate PHP file - javascript

I'm trying to dynamically add a new ACF repeater field value (course_slug) to the current user in Wordpress. The value to be added is a URL generated from a separate function.
If I use the following code on the original page using a static URL value for course_slug then the new value is added fine.
<?php $field_key = "field_61e9bb8b66765";
$value = get_field($field_key, "user_{$current_user_id}");
echo $value;
$value[] = array("course_slug" => "http://www.exampleurl.com");
update_field( $field_key, $value, "user_{$current_user_id}");
?>
However if I run the code in a separate PHP file using two data values sent from the original page (as per below), then I receive a 500 error.
url: 'http://localhost:8888/wordpress/wp-content/themes/cookable/write-course-to-user.php',data:{"userIDdata":finaluserid, "courseURLdata":tidycourseurlupdate},
success: function(data) {
$('#result3').html(data);
}
});
write-course-to-user.php
<?php
$userIDfinal = isset($_REQUEST['userIDdata'])?$_REQUEST['userIDdata']:"";
$courseURLfinal = isset($_REQUEST['courseURLdata'])?$_REQUEST['courseURLdata']:"";
echo $userIDfinal;
echo $courseURLfinal;
echo "user_{$userIDfinal}";
$field_key = "field_61e9bb8b66765";
$value = get_field($field_key, "user_{$userIDfinal}");
echo $value;
$value[] = array("course_slug" => $courseURLfinal);
update_field( $field_key, $value, "user_{$userIDfinal}");
?>
The three test echos in there display data as expected:
echo $userIDfinal; - displays 1
echo $courseURLfinal; - displays https://calendly.com/tjmdigital/cookable-1-week-1
echo "user_{$userIDfinal}"; displays user_1
Am I missing something daft here as to why the code will run fine in the original file but not in a linked one? Any advice hugely appreciated, thanks.

Related

Update MYSQL Table On Div Click using Ajax - No Page Refresh?

I have a MYSQL Table called users.
I also have a column called online_status.
On my page I want a user to be able to toggle their status as 'Online' or 'Offline' and have this updated in the database when they click on the div using Ajax, without refreshing the page.
Here's my PHP/HTML code:
<?php if ($profile['online_status'] == "Online") {
$status = "Offline";
}else{
$status = "Online";
} ?>
<div id="one"><li class="far fa-circle" onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"/></li><? echo 'Show as ' .$status; ?></div>
My Ajax:
<script type="text/javascript" src="/js/jquery.js"></script>
<script>
function UpdateRecord(id)
{
jQuery.ajax({
type: "POST",
url: "update_status.php",
data: 'id='+id,
cache: false,
success: function(response)
{
alert("Record successfully updated");
}
});
}
</script>
update_status.php
<?php
$var = #$_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = 1";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
//added for testing
echo 'var = '.$var;
?>
I am currently getting no alert, nothing is being updated in my database either. Please can someone help me improve/fix the code to get it to work? Also, if there's a way of eradicating the need for the update_status.php file and have the ajax self post then this would be preferred.
Thank you in advance.
From what i see, the reason why no alert pops up nor nothing gets updated is because of the onclick() on button you have. Add quotes around the parameter to the update function. As you have it, javascript sees the parameter as a javascript variable as $profile['online_status']; is a string.
If you had debugged your code, you should see an error pointing towards the onclick() line
Change this
onClick="UpdateRecord(<? echo $profile['online_status']; ?>);"
To
onClick="UpdateRecord('<? echo $profile['online_status']; ?>');"
Also you are hardcoding the where clause in your update statement. You should be using the $_POST['id'] variable via prepared statements
pass data to PHP file
data: { id: id },
add a database connection to your PHP file
<?php
$var = $_POST['id'] ;
$sql = "UPDATE users SET online_status = 'Offline' WHERE user_id = '$var'";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
?>
If you still see any errors then press F12 and go to network tab, then click on that div, network tab will record your ajax file returns, you can check there on by selecting your php file's response, hope it helps

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list

How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
index.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<div id="container">
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
</div>
<button id="loadMore">Загрузить ещё...</button>
<script src="/jquery-1.11.3.min.js"></script>
<script src="/script.js"></script>
item.php
<?php
class Item
{
public $id;
public $text;
function __construct($id = null, $text = null)
{
$this->id = $id;
$this->text = $text;
}
public function show()
{
return $this->text;
}
}
loadmore.php
<?php
$offset = 0;
$limit = 10;
$statement = $pdo->prepare('SELECT * FROM credit LIMIT ?, ?');
$statement->bindValue(1, $offset, PDO::PARAM_INT);
$statement->bindValue(2, $limit, PDO::PARAM_INT);
$statement->execute();
$data = $statement->fetchAll();
$items = [];
foreach ($data as $item)
{
$items[] = new Item($item['id'], $item['tel']);
}
pdo.php
<?php
$host = '127.0.0.1';
$db = 'test';
$user = 'root';
$pass = '';
$charset = 'utf8';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);
script.js
function getMoreItems() {
var url = "/loadMore.php";
var data = {
//
};
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
//
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
}
How to change files so that when you click on the "load more" button the browser dynamically adds the following entries from the database in the list
I think 2 hours and I can not understand.
Help.(
I understand your confusion, I believe you're wondering why your php code in index.php doesn't work properly after you call loadMore.php using ajax.
There's one distinction you need to understand to be capable of developing for the web. The difference between server-side and client-side code.
PHP is a server-side programming language, which means that it only executes on the server. Your server returns html, or json, or text, or anything to the browser and once the response arrives at the browser, you can forget about php code.
Javascript on the other hand is a client side programming language (at least in your case) It executes on the browser.
You basically have two options:
To send back some json and loop over it using jQuery, which is the preferable choice, but I fear it requires more work.
Send back html and append it to your page, first create a file called async.php
<?php
include('pdo.php');
include('item.php');
include('loadMore.php');
?>
<?php foreach ($items as $item): ?>
<div class="single-item" data-id="<?= $item->id ?>">
<?= $item->show() ?>
</div>
<?php endforeach; ?>
in your js add to your success callback
$.ajax({
url: url,
data: data,
type: 'get',
success: function (res) {
$('#container').append(res);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
//
}
});
don't forget var url = "async.php";
First you need to attach the buttons onclick="" attribute with the ajax-method.
<button ... onclick="getMoreItems">...</button>
Second, your loadmore.php need to require_once the files it depends on:
require_once('pdo.php');
require_once('item.php');
Third, separate your logic for querying the database to a function in the pdo.php file you can call with the limits as parameters, i.e.
function getData($offset = 0, $limit = 10){
//logic
}
You should also always try to use require_once or include_once to be sure files aren't loaded several times.
Now you can call the function getData(...) from index.php before the container div to load up the initial data, remove the include to loadmore.php from index.php, and in loadmore.php write the logic to use the parameters sent from the webpage to get the next chunk of data.
The data:... in your ajax needs to pass along the "page" it wants to get, perhaps simply a counter as to how many times you have loaded more. In the loadmore.php script you then just multiply the page by the limit to get the offset.
Return the data as JSON to the ajax, parse the JSON so you can build a new div for each item, then add each div to the container-div using javascript.
Im not going in detail on all topics here, but you at least will know what tutorials to search for on google :)

AJAX - Undefined PHP variable

I have the following problem, the following script sends a keyword a PHP file hosted in another domain (I already added the CROS headers), this PHP returns me some "echos of different variables" (title, thumbnail, url, etc.) And it works but randomly returns me "Undefined variables".
The first thing was to add an if (isset ()) to my variables in PHP and the error does not appear anymore but the results returned by my searches are much smaller (Before adding it averaged 10 to 20 results, Now I get 5 results).
Can this be a problem with my script?
My form.php
<form method="POST" action="" id="form-busqueda">
<input type="text" name="keyword">
<button id="search" name="search">Search</search>
<div id="results"></div>
<script>
jQuery(function($){
var pluginUrl = '<?php echo plugin_dir_url( __FILE__ ); ?>' ;
$('[id^="form-busqueda"]').on('submit', function(e) {
e.preventDefault();
$.ajax({
type : 'POST',
url : 'http://localhost/ladoserver/script.php',
data : $(this).serialize(),
beforeSend: function(){
$('#results').html('<img src="'+pluginUrl+'../../assets/img/loading.gif" />');
}
}).done(function(data) {
$('#results').html(data);
});
});
});
</script>
</form>
My script.php (dlPage is a function that create cURL connection):
<?php
if (isset($_POST['keyword'])) {
$search = $_POST['keyword'];
$html = dlPage("http://example.com/" . $search);
//where I search and get with simple_html_dom example:
$video = $videos->find('div.example2>a', 0);
$title = $video->innertext;
$url = $video->attr['href'];
$id = $video->attr['id'];
$thumbnail = $video->find('div.thumb', 0)->innertext;
echo $title;
echo $url;
echo $id;
echo $thumbnail[0];
}
?>
I've updated my code, I didn't put all the code because I thought that it isn't relevant, my script.php works fine with pure PHP. The problem appear when I use AJAX.
I'm getting the following error:
Notice: Undefined variable: title in C:\xampp\htdocs\webs\ladoserver\script.php on line 13
Notice: Undefined variable: title in C:\xampp\htdocs\webs\ladoserver\script.php on line 13
Notice: Undefined variable: url in C:\xampp\htdocs\webs\ladoserver\script.php on line 14
The undefined variable is coming from your PHP file (/ladoserver/script.php).
What generates the variables being returned? The most common "cause" of this, is by only setting the variables within a block of code that might not be executed (eg within an if block, or in a loop that iterates 0 times)
You could get around the error (assuming you're okay with blank values) by defining each of the variables at the top of your script.
<?php
$title = "";
$thumbnail = "";
$url = "";
$id = "";
?>
Edit: #snip1377 reminded me that you can also just use isset at the end of your script before the output as well.
Here's some sample code for your $thumbnail variable, which you could apply to all your variables being returned
<?php
if (isset($thumbnail))
{
echo $thumbnail;
}
else
{
echo "";
}
?>
Alternativaely, you can use a ternary operator:
<?php
echo (isset($thumbnail)) ? $thumbnail : '';
?>
Edit again: just to illustrate what I mean about how the variables might not get defined within a script, here is an example that could cause that undefined error:
<?php
if ($_POST['value'] == 1)
{
// This will never be reached unless $_POST['value'] is exactly 1
$return_val = 1;
}
echo $return_val;
?>
This will give the undefined warning, if $_POST['value'] is anything other than 1.
Similarly, if $_POST['value'] were 0 in the following code, it would have that undefined warning as well:
<?php
for ($i=0; $i<$_POST['value']; $i++)
{
// This will never be reached if $_POST['value'] is less than 1
$return_val = $i;
}
echo $return_val;
?>
In the examples above, you can simply define $return_val at the top of the script, and you won't get the error anymore.
You send this data as a post method.you shuld echo them with $_post['name'] but you just echo $name
Use this in script.php :
<?php
echo $_POST['title'];
echo $_POST['thumbnail'];
echo $_POST['url'];
?>

PHP: why two codes that echo the same string return different results?

I'm new at PHP and I don't understand why this happens.I try using echo to show "$imglinksis" and the result is exactly http://catpic.s3.amazonaws.com/product.jpg
I do not understand why the 2nd Code fails. Please help!
Code #1: This code completely works in returning the fields I want
<?php function CallCatpicAPI($photoUrl){do something...}
$imglinksis = "http://catpic.s3.amazonaws.com/product.jpg";
$jsonReturnCatpic = CallCatpicAPI($imglinksis);?>
Code #2: Fail to return: API says invalid URL image link
<?php function CallCatpicAPI($photoUrl){do something...}?>
<script>var img_link = "http://catpic.s3.amazonaws.com/product.jpg";</script>
<?php
$imglinksis = "<script>document.write(img_link).toString()</script>";
$jsonReturnCatpic = CallCatpicAPI($imglinksis);?>
You are mixing the two codes. Your php is executed on the server but the javascript is executed on the client side after php executed. You can fix your second code by this:
<?php
$imglinksis = 'http://catpic.s3.amazonaws.com/product.jpg';
function CallCatpicAPI($photoUrl){do something...}
?>
<script>var img_link = '<?php echo $imglinksis; ?>';</script>
<?php
$jsonReturnCatpic = CallCatpicAPI($imglinksis);
?>

Inserting MySQL results from PHP into JavaScript Array

I'm trying to make a very simple autocomplete function on a private website using a trie in JavaScript. Problem is the examples I have seen and trying are just using a predefined list in a JavaScript array.
e.g. var arrayObjects = ["Dog","Cat","House","Mouse"];
What I want to do is retrieve MySQL results using PHP and put them into a JavaScript array.
This is what I have so far for the PHP (the JavaScript is fine just need to populate the array):
<?php
$mysqli = new mysqli('SERVER', 'U/NAME', 'P/WORD', 'DB');
if (!$mysqli)
{
die('Could not connect: ' . mysqli_error($mysqli));
}
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
while($stmt->fetch())
{
printf("%s, ", $name);
}
?>
Then I want to insert essentially each value using something like mysql_fetch_array ($name); (I know this is incorrect but just to show you guys what's going on in my head)
<script> -- this is the javascript part
(function() {
<?php while $stmt=mysql_fetch_array($name))
{
?>
var arrayObjects = [<?php stmt($name) ?>];
<?php }
?>
I can retrieve the results echoing out fine, I can manipulate the trie fine without MYSQL results, I just can't put them together.
In this case, what you're doing is looping through your result array, and each time you're printing out the line var arrayObjects = [<?php stmt($name) ?>];. However this doesn't convert between the PHP array you're getting as a result, and a javascript array.
Since you started doing it this way, you can do:
<?php
//bind to $name
if ($stmt = $mysqli->prepare("SELECT category.name FROM category")) {
$stmt->bind_result($name);
$OK = $stmt->execute();
}
//put all of the resulting names into a PHP array
$result_array = Array();
while($stmt->fetch()) {
$result_array[] = $name;
}
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($result_array);
?>
<script>
//now put it into the javascript
var arrayObjects = <?php echo $json_array; ?>
</script>
Use json_encode to turn your PHP array into a valid javascript object. For example, if you've got the results from your database in a php array called $array:
var obj = "<?php echo json_encode($array); ?>";
You can now use obj in your javascript code
For the auto-completion you can use the <datalist> tag. This is a relatively new feature in HTML5 (see support table) but the polyfill exists.
Fill the <option> tags in php when building the page and you a are done.

Categories