Insert PHP functions into Javascript - javascript

I got really confused when trying to get PHP functions into javascript.
In my scenario, I just extract some lines from XML file in PHP and convert it into a table, and the presentation of the whole table is in the function getNews(). Into the function are echo sentences like
function getNews(){
$xmlResponse = new SimpleXMLElement('xml.addr',0,TRUE);
foreach($xmlResponse -> children()as $contents){
echo "<table id ='news'>";
echo "<a href='".$links."'>".$contents -> item[$num] -> title."</a>";
HTML tags are involved to build a news table.
Then I was asked to implement a button, when clicking on the button, the button image changes and the table should be shown below. Obviously the onclick function should be written using javascript, when click on it, I need to call the anotherButton() function and show the news table
echo "<script>function anotherButton(){
document.getElementById('news').innerHTML='<div class='newStyle'
onclick='anotherButton1()'>click to hide stock news
<img src='http://image-addr'></div>';
}</script>";
All these things were done in PHP and I need to insert function getNews()
somewhere in the above echo, so how I can put the function in it ?
Thanks in advance.

What you need is the following:
Javascript sends the data to server using AJAX in the client's browser.
PHP decodes the request, processes it then responds with the information requested.
Javascript receives the response and displays it accordingly.
Using Asynchronous Javascript And XML (or AJAX for short); you can essentially fetch data from the server dynamically without the client performing a browser refresh.
Here is a video by Codecourse which will get you started in the right direction.

Related

Posting to Javascript from php without form action

I'm working on a child theme that uses ultimate member and redefines some of it's functions. Previously it redefined the follow button and sent the info to a payment form and then the form sent the info to a javascript file. The form is no longer used so we are trying to send the info directly to a javascript file and I haven't worked with php in awhile so I'm a little lost. The only options I find are form action and method post which aren't working,
The function is
<div class="um-followers-btn">
<?php
if (in_array("um_customer", $res->roles)) {
$nav_link = UM ()->permalinks()->get_current_url(get_option('permalink_structure'));
$nav_link = remove_query_arg('um_action', $nav_link);
$nav_link = remove_query_arg('subnav', $nav_link);
$nav_link = add_query_arg('profiletab', $id, $nav_link);
And previously the trigger was
echo '<a href="" id="cm_follow_button" data-toggle="modal" data- target="#payment_modal" class="um-button" >Follow</a>';
Obviously this doesn't work so any help would be appreciated.
Apologies, the echo puts forth a "follow" button, what the button appears but what I"m trying to accomplish is for the values, such as user1 and user2 to go to another php file which inserts them into the database and changes the button to request sent this is allhandled in the other php file by the previous team, I'm having trouble sending it there, the previous method was going to a javascript file from the last line above, this line produced the button which when pressed called forth a php form that took payment info, and then sent that to a js form which in turn took theinfo fand verified the payment format, changed the "follow" to "Follow request sent" and sent the rest to a php form that as I said, put the ifo in the mysql database and gave the 2nd user the option of accepting the follow request. Ultimate Member doesn't offer this option which is why it was modified in a child theme like this. We aren't processing payment like this we just want the button to send the info to the php form and I'm having that issue with doing it, via this button. I hope that helps

Remove values from array onclick without page refresh

I have a one form and onclick i want to remove image id from array without page refresh and after submit form i will update it in the DB.
I am using following code for this but no any success.
PHP Code:-
$total = count($oldimage);
//print_r($oldimage);
for($i=0;$i<$total;$i++)
{
$fimgsql="select * from cc_tbl_img_vid_upload where id='$oldimage[$i]'";
$gimgname=mysqli_query($db,$fimgsql) or die('Error');
$rw=mysqli_fetch_assoc($gimgname);
?><b id="rm<?=$i?>">Remove<?=$rw['upload_url']?></b><br/><br/>
<script>$( "#rm<?=$i?>" ).click(function() {
<?php unset($oldimage[$i]);?>
alert(<?php echo $oldimage[$i]; ?>);
$( "#rm<?=$i?>" ).hide();
});</script>
<?php
}
sort($oldimage);
$oldimage=implode(',',$oldimage);
Unfortunately you can't directly execute PHP (server-side) based on a JavaScript (client-side) event like you have in your code.
You need to handle your arrays in JavaScript. You can json_encode a PHP array and use the JSON array in your JavaScript, which is probably the closest you will get to doing what you're trying to do.
It's not possible the way you want to do it.PHP is serverside - which means you need to send a request to the server and get the response back(refreshing/changing page) while js is client side, and manipulates the UI, in order to achive that you must use AJAX (making a request from behind, and not seen by the user and getting the response, and based on it's output change the UI for the user)
Read this link - http://api.jquery.com/jquery.ajax/ ajax isn't that hard, but you must understand it, if you have php/mysql/html/css/js/jquery knowledge you will get it in no time.

populate textfield on selecting dropdown struts2

I have a text <s:select> in my jsp page .
Now what i have to do is when someone selects a value from this dropdown ,
i need to call my action class to get some value based on dropdown selection.
Now this value (which i got from my actionclass) should be shown in the <s:textfield> below this dropdown .
Please help !!
Well all you have to use the power of Ajax.You have multiple options to do this.
User simple Javascript.
User any javascript frameowrk like jquery,DOJO etc
Bind you code with on-click/change even of the Select tag and send a simple request to the S2 action.you can either use Stream result to send data back from the S2 action or better (in my opinion) send back JSON data from your action class and user Jquery build in functionality to parse the JSON data at JSP
user S2 JSON plugin to send and receive JSON data from Action and JSP to make life more easy.
Please follow this tutorial to know how to use JQuery with JSON and struts2
using-struts-2-json-and-jquery
Update
You need to do something like this in your JSP code for Ajax and JQuery
var selectedState = document.getElementById("selectboxid");
var statedata = selectedState.options[selectedState.selectedIndex].value;
var formInput='state='+statedata;
$.getJSON('search/dropDownRenderer',formInput,function(data) {
}

dropdown menu populated from a database in a client side page

I want to populate the data from a database using client side programming either HTML or javascript. I looked online and got lot of sites giving examples on server side i.e. JSP,ASP or PHP for creating the dropdown menu. I know the simple syntax for creating the HTML dropdown menu and in other languages. But I don't know how to populate that HTML dropdown menu values from the database. Any technique which either gets the data from the JSP page which fetches the data from the database and on selecting a single item triggers a query to JSP page which again fetches data from the database can work for me.
Problem: I want to access the database fields from a html page. The dropdown list of html page should be populate from the database and on selecting a specific value it should get data specific to that option.
Any ideas or links to the sources I should look at.
Just so you can get a general idea of the mechanism: How about an Ajax-call triggered by an event listener like this (could also use click event or whatever):
After the html-document is loaded, add an event listener to the watched element (here onchange) and call a function when the event is triggered:
$(document).ready(function() {
$('#watchedElement').change(callAjaxFunction());
});
Function for Ajax-call:
In the data variable you can send information to the server to decide there which options to send back. Easiest way (though quick and dirty) would be to return (like "echo" in php) the option values in plain text/html and replace the old option-elements with this. I prefer the JSON-ways described in the link from your question's comment, since you have a lot more control on the data but for a first impression you could try if the mechanism works for you in general:
function callAjaxFunction() {
$.ajax({
type: "POST",
url: url,
data: { "selectedValue": $('#watchedElement').val() }
success: function(data) {
$("#idOfSelectElement").html(data);
}
dataType: "HTML"
});
}
Just for testing purposes without any evaluation of the value sent to the server you could send back two dummy options like this (example is php file for simplicity and you even could use an html-file that only contains the text itself):
<?php
echo "<option value='test1'>Test1</option>" .
"<option value="test2">Test2</option>";
?>
Still it's probably better to go the JSON way and add element by element, which makes dbugging and stuff way easier later on.

Need sample JavaScript to query MySQL and display result upon combo box update

I have a combo box that will be loaded with a list of choices. When the user selects a choice, I need a JavaScript to simply run a query of MySql (obviously based on the user choice in the combo box) which will return a simple, discrete value that then needs to be displayed on the page next to the combo box.
The query is nothing more than SELECT foo FROM tblexample WHERE id = blah (where blah is the combo box value). The value will be a simple number. If the user chooses a new value, then it should just re-query and display the result.
I'm open to reading the whole table in upon page load into an array or something too. I work in PHP but I don't know Javascript; I was only hoping for a sample code bit; I can read and extrapolate most of the time.
I just didn't want to put a submit button in a form and force the user to do that each time they look at a new combo box choice. I wanted a more seamless, quick display for them.
JavaScript is a client-side language. It will not run MySQL queries (safely, at least). Use PHP to dynamically create the HTML and JavaScript for the combo box.
PHP has an entire section of their documentation reserved for MySQL.
I think you are actually looking for a reference in Ajax programming using PHP on the backend and javascript on the front end.
My recommendation would be to look at using one of the excellent Javascript development frameworks. Great candidates would be JQuery or Prototype. They both give you solid libraries to simplify programming in javascript.
Rather than working with sample code, you'll probably get a lot further by developing javascript expertise. Ajax is complicated, and you'll need to at least get basic skills together before you can start to integrate javascript and PHP.
Here's a good query to get started- I'd recommend beginning with JQuery if you have to pick one.
http://www.google.com/search?sourceid=chrome&ie=UTF-8&q=ajax+php+jquery+tutorial
Once you get started on jQuery as Tim mentioned you could do this,
The select box,
<form name="formName" action="" method="">
<select name="selName">
<option value={uniqueId}>Option 1</option>
</select>
</form>
<p class="displayMsg">No message to display.... yet</p>
The javascript and jQuery in a script tag of the head tag,
$(document).ready(function() {
$('select[name=selName]').change(function() {
function processData(data, success) {
...do something with the query results echoed into var data...such as
$('p.displayMsg').txt(data); // which will update the text node of the p tag class displayMsg
} // end function processData
var formData = $('form[name=formName]').serialize(); // this will encode the variables from the form to pass into post headers. You can access in your ajax called script with $_POST['selName']
$.post('phpAjaxProcessScript.php',formData,processDataClose); // sends data to script and when it's done it calls function processData
}); // end select change event function call
}); // end document ready event function call

Categories

Resources