Remove values from array onclick without page refresh - javascript

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.

Related

Insert PHP functions into 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.

Changing PHP Session variables on click event

Please help me on this problem. It is small but causing me lot of trouble.I have set the session variable in my index.php and when clicked on anchor tag , it is not changing the session variable.
Relevant PHP part:
session_start();
$_SESSION["amount"] = "99";
Now the html part (in same PHP file).
<a onclick="change('<?php echo $_SESSION['amount']='399'; ?>')" href="#"><h4>Order 399</h4></a>
<a onclick="change('<?php echo $_SESSION['amount']='200'; ?>')" href="#"><h4>Order 200</h4></a>
I am checking the value of Session variable in another div in same file.
<td>Amount: <?php echo $_SESSION["amount"] ?> </td>
the value shown is 200 though clicked on "Order 399".
How do I change session variable?Am I mixing Client side and server side?
Please help me and do suggest the shortest possible way to do it.
Actually you are mixing it up!
It could be done like this:
You need a js-function, which calls a PHP-File, which then will change the value of the Session Variable.
And don't forget: Locate all the values on the currently loaded page via JS, because they won't change instantly. For sure they will change on Page-Reload, but if you want to avoid a page reload, then change the values, which are currently on the page.
jQuery ajax and append will be a huge help here.
If you have tried this and have still problems, then just ask again, but please try it to do first by yourself!
The last value of your session parameter is 200, you need to send an ajax request and then retrieve the latest changed value of your parameter.
you shouldn't change in in 'view' port.

Load a page, give a variable on alert of JavaScript

I have a intranet-website here that checks if an employee has used the form correctly and (via php) calls then a JavaScript part:
<script type="text/javascript">alert("Error!"); history.back(-1);</script>
Now, there is a php-variable with a huge amount of text. how can I call the site and give the variable with it, instead of using a simple history.back, where every variables are deleted instantly? Someone an idea how to make this without jQuery?
I think this is what you need:
<script type="text/javascript">alert("Error!"); location.href="page.php?yourvar=<?php echo $var; ?>";</script>
This will show the alert box and then redirect user to "page.php", where you can get your variable value using $_GET['yourvar'].
Hmm, not entirely sure what you mean but you could try something like this?:
if ($error) {
echo '<script type="text/javascript">alert('.$error.');</script>';
header('Location: page.php?var='.$myVar);
}
They should still get alerted with the error and then get sent back to the previous page, if this is what you were asking.

Server side validation results appear in the same browser window

Simple HTML form:
<form action="test.php" method="post" name="my_form" id="my_form" >
<input name="c_name" type="text" id="c_name" maxlength="90"/>
</form>
test.php with the following code:
<?php
$name=$_POST['c_name'];
if ((!isset($name)) || ($name==''))
{
echo 'Fill in the name';
}
else
{
echo $name;
}
?>
Now, I want the following upon form submission:
1) Not to leave the current browser window as PHP to display the corresponding message.I want the form window to stay there.
2)I do not want just a simple response message. For example, I want instead of "Fill in the name" a more graphical way to interact like making a hidden div to appear; in other words I want to write Jquery inside PHP and make it execute. Is it possible and how?
I know I have to use AJAX, however I do not know what to do exactly! Could you give me some code as to realise the above two things?
I believe that if you're new to all of this, as you seem to are, you are best of using jQuery indeed. An ajax example can be found here: http://api.jquery.com/jquery.ajax/
Code in this case is q bit extensive. Cause you would not only want to check if it is in fact empty, but you also want to preg_match it. Which means you want to make sure that what your users send you actually want (and not break or hack or inject your server, which is important).
So seeing this I would recommend to read a tutorial, something like this (fast google search): http://code.tutsplus.com/tutorials/5-ways-to-make-ajax-calls-with-jquery--net-6289
And familiarize yourself with some basics before getting into the next steps.
To get the effect you are wanting. I like to use the jQuery Form Plugin, it makes it easy to create an AJAX form out of any existing form. Then simply echo your results in the .php file you submit to (Hint: you can echo div's with styling too.) The below example, assuming you have the jQuery Form Plugin included on your page, will submit the form using AJAX and return the echoed results to a div with id=status.
$(document).ready(function(){
var status = $('#status');
$('#my_form').ajaxForm({
beforeSend: function() {
status.empty();
},
complete: function(xhr) {
status.html(xhr.responseText);
}
});
});

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.

Categories

Resources