Refreshing webpage via JavaScript that is triggered by HTML select with AJAX - php

I have a strange problem where I cannot get a php webpage to refresh that is triggered by a pulldown. Here is the main file (SelectForceRefresh.php):
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="chrome=1" /><!-- Optimistically rendering in Chrome Frame in IE. -->
<title>My form</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<script>
function ConfigFileSelection(id)
{
$.ajax({
type: "GET",
url: "RefreshConfig.php",
data: "confFile = " + id,
success: function GotHere()
{
alert("Got here!");
}
});
}
</script>
<select name="userconfigoption" onchange="ConfigFileSelection(this.value);" >
<option value="1">One</option>
<option value="2">Two</option>
<option value="3">Three</option>
</select>
</body>
</html>
And here is the 'link' file (RefreshConfig.php):
<?php
if(isset($_GET['confFile'])){
CopyUserConfig($_GET['confFile']);
}
function CopyUserConfig($id)
{
header("Location: SelectForceRefresh.php");
exit;
}
?>
The problem is that the javascript function is fired when I make a selection from the pulldown because I see the alert "Got here!", but the other php file is never triggered for the refresh. I have been on this for three days not knowing what I'm missing. I have reviewed the other solutions here on Stack Overflow like this one:
on Change of dropdown list showld call the php function
Where I tried to learn this technique from, but they simply do not work.
What am I missing here? Both files are in the same directory. Thanks in advance.

You can not let the PHP file that you target with your AJAX function refresh your webpage.
The best way is do if in the success function of AJAX (so with JavaScript).
Something like:
$.ajax({
type: "GET",
url: "RefreshConfig.php",
data: "confFile = " + id,
success: function GotHere() {
window.location.reload();
}
});

Related

multi select is not being displayed through ajax call

I'm implementing multi select through bootstrap. When i wrote it directly on page it works fine. I call ajax on select of drop down that is already existed in my page.
here is the tutorial for multi select which i'm following.
here is my code
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/css/bootstrap-select.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.4/js/bootstrap-select.min.js"></script>
<script type="text/javascript">
$(function(){
$('#c_company').change(function() {
c_company = $('#c_company').val();
$.ajax({
type: "POST",
url: 'get_company_data.php',
data: {
'c_company' : $('#c_company').val()
},
success: function(result)
{
//alert(result);
$(".col-lg-8").html(result);
}
});
});
});
</script>
</head>
<body>
<select id='c_company' name='company'>
<option value='Bunnny'>Bunny</option>
<option value='Nestle'>Nestle</option>
<option value='Coke cola'>Coke cola</option>
<select>
<div class='col-lg-8'>
</div>
</body>
</html>
here is get_company_data.php file code.
<?php
echo "<select class='selectpicker' multiple >
<option>Mustard</option>
<option>Ketchup</option>
<option>Relish</option>
</select>";
?>
ajax call is working fine and it returns right data because i'd shown it by putting response on alert function. I don't know where i'm doing wrong because if html is directly visible on page then it must get visible by ajax call too. Any help would be much appreciated. Thank you :)

ajax "post" request failed

I am using ajax for the first time and passing data to another file using ajax request. The request goes through if I pass it using get which is by default but the moment I change it to post it does not work.
$.ajax({
type:'POST',
url:'pageAjax2.php',
data:'name='+name,
success: function(data){
$('#content').html(data);
}
})
If I remove the type:'POST'; everything works but if have it in the code nothing works . Can someone please help me with this.
All good here. What version of jQuery are you using ?
I'll post my code :
File jq.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
$(function(){
var name = 'Telmo Dias';
$.ajax({
type:'POST',
url:'pageAjax2.php',
data:'name='+name,
success: function(data){
$('#content').html(data);
}
});
});
</script>
</head>
<body>
<div id="content"></div>
</body>
</html>
File pageAjax2.php :
<?php echo "Hello ".$_POST['name'];?>
Result:
thank you guys i just checked and pageAjax2.php had been set to get instead of using post so i just changed it to post and everything works now
thank you

Very simple ajax add to cart

Ok I am trying to wrap my head around how to add something to a cart and have it show in the page without reloading the page.
So I have tried to write something very simple so I can wrap my head around how exactly the logic works and is properly written. In my example I have a div in the page for the session['cart'] and a drop down.
One option with value of 'red' and the other option with value 'blue'. When I select the option with value of 'red', I want 'red' to show in the div located right after body tag insession['cart']. When I select the option with value of 'blue', I want 'blue' to show in session['cart'].
I am attempting to do this through an ajax post to a page called 'cart_update.php'. I have been struggling with a more advanced model of this for a week and I thought it would be a good idea just to write something simple so i could really understand and learn what is really going on. Any help is really appreciated!
Here is my code and I know its way off. I am just trying to learn.
index.php
<?php session_start(); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<style type="text/css">
body {
margin-top: 200px;
}
</style>
</head>
<body>
<div align="left" style="display:block;width:200px;height:200px;background:#ccc;border:solid 1px #009966;">Color Chosen<br /><?php echo $_SESSION['cart']; ?></div>
<div align="center"><form method="post" action="">
<select id="color-selection">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
</div>
<script type="text/javascript">
$(document).ready(function(){
$("#color-selection").on("change", function(event){
var color = $("#color-selection").val();
var add = "add";
var dataString = {color: color, type: add}; //JSON-formatted string
$.ajax({
type: "POST",
url: "cart_update.php",
data: dataString
});
});
});
</script>
</body>
</html>
and here is my cart_update.php
<?php
session_start();
$type = json_decode($_POST['type']);
if(isset($_POST["type"]) && $_POST["type"]== $type)
{
$color = json_decode($_POST['color']);
$_SESSION['cart'] = $color;
}
?>
It's hard to tell what's not working when you don't tell us what error/warning you get. You should look into your js-console (with firebug or another debugging tool)
Looking at your code though, I see some things..
$(document).ready(function(){
$(".add_to_cart").onClick(function(){
var dataString = "color=" + color;
$.ajax({
type: "POST",
url: "cart_update.php",
data: dataString
});
});
});
onClick won't work in this context. Use on() instead. http://api.jquery.com/on/
The second thing is that you should use JSON-formatted strings when sending data.
$(document).ready(function(){
$(".add_to_cart").on("click", function(event){
var dataString = {color: color}; //JSON-formatted string
$.ajax({
type: "POST",
url: "cart_update.php",
data: dataString
});
});
});
In your html you have hidden fields with several forms with defined colors. Instead of that approach I would make a select-list within one form so it would be kind of easy to grab the value of the color, and you wouldn't have to create a new form for each color.
Something like this:
<select id="color-selection">
<option value="red">Red</option>
<option value="blue">Blue</option>
</select>
Then in your js, you can get the selection of color by doing something like this:
color = $("#color-selection").val();
To get a response-value when ajax-call is done, then use the done()-callback. It's also a good practice to assign a return-type.
$(document).ready(function(){
$(".add_to_cart").on("click", function(event){
color = $("#color-selection").val();
var dataString = {color: color}; //JSON-formatted string
$.ajax({
type: "POST",
url: "cart_update.php",
data: dataString,
dataType: "json" //This indicates the expected return-type
}).done(function(data) {
$("#thecoloris").html(data.color); //response from php. Set the color in the div id="thecolorid"
});
});
});
In your php-code you will have to decode the json-data:
<?php
session_start();
if(isset($_POST["type"]) && $_POST["type"]=='add')
{
$color = json_decode($_POST['color']);
$_SESSION['cart'] = $color;
}
echo $_POST['color']; //Output color (that is sent to this php through ajax) - This acts as the return value data in the ajax-function done()
?>
Usually the outputted value should be encoded in json-format with json_encode($variable) but in this case $_POST['color'] is already in json-format because it was sent to the php from js in json-format.

Show data in real time with AJAX/Jquery/PHP

I am fairly new to PHP but was looking at this tutorial. http://www.devirtuoso.com/2009/07/beginners-guide-to-using-ajax-with-jquery/
I want to test a similar concept to display data from my database on a page when someone submits data via a form.
eg there is a page where you choose what color shoes you want and a page with a leaderboard to see how many times each color has been chosen.
I have no problem submitting the form but don't no where to start to look to get the contents to display on the leaderboard using ajax. Can anyone point me in the right direction here please?
you should start with this
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html>
<head>
<meta http-equiv="Content-type" content="text/html; charset=utf-8" />
<title>Ajax With Jquery</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript" charset="utf-8">
$(document).ready(function(){
$('#txtValue').keyup(function(){
$.ajax({
url: '/ajax.php',
type: "POST",
data: "value="+$(this).val,
cache: true,
dataType: "JSON",
success: function(response){
$("#leader-board").append("you choose "+ $(this).val + "color : " +response.count + " times");
}
});
});
});
</script>
</head>
<body>
<label for="txtValue">Enter a value : </label>
<input type="text" name="txtValue" value="" id="txtValue">
<div id="leader-board"></div>
</body>
</html>
and you ajax.php file look like this
<?php
//if your data return result like this so you have to do this process
$data = array("count"=>5);
echo json_encode($data);
?>
You can send you form data and get your response in your div which have an id 'yourDivId' like below. You should to make a one more column 'countcolor' in your table . Increment it when a user request a particular color.
$.ajax({
url: base_path + "/folder/test.php",
data: "id="+id,
type: 'GET',
success: function (resp) { document.getElementById('yourDivId').innerHTML=resp;},
error: function(e){ alert('Error: '+e); }
});
After you submit the form, you need to get the pertinent data, echo it back (if you're using ajax, you want to echo is back using json_encode();), and then put it in the "leaderboard" div. e.g.
Action page for submitting to database
<?php
header('Content type: application/json');
// after you've submitted the data to the database, get the data for the leaderboard
$leaderboard_data = array();
$leaderboard_data = your_function_to_grab_data();
echo json_encode($leaderboard_data);
?>
On the page where you submit the form
$.ajax({
url: 'insert/path/to/action/here',
success: function(data) {
$("div#leaderboard-div").html(data)
}
});

How to use different pages for form input and results using AJAX

So, I have a search form in a php page (top.php) which is an include for the site I'm working on, one php page where all the mySQL stuff happens and the results are stored in a variable and echoed (dosearch.php) and lastly a php page where the results are displayed in a div through jQuery (search.php). This is the javascript code:
$(document).ready(function(){
$('#search_button').click(function(e) {
e.preventDefault();
var searchVal = $('#search_term').attr('value');
var categoryVal = $('#category').attr('value');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: "search_term=" + searchVal + "&category=" + categoryVal,
beforeSend: function() {
$('#results_cont').html('');
$('#loader').html('<img src="layout/ajax-loader.gif" alt="Searching..." />');
if(!searchVal[0]) {
$('#loader').html('');
$('#results_cont').html('No input...');
return false;
}
},
success: function(response) {
$('#loader').html('');
$('#results_cont').html(response);
}
});
});
});
The #search_term and #category fields are in top.php, the other divs (#loader and #results_cont) are in search.php. How would I go by in order to make the form submit and display the results in search.php from the top.php without problems? It works perfectly if the form and javascript are in search.php but I can't seem to separate those and make it work. What am I doing wrong?
PS. Sorry if I'm not clear enough, am at work, really tired. :(
SPLITTING:
<? include('functions-or-classes.php'); ?>
<!DOCTYPE html>
<html>
<head>
<title></title>
<? include('js-script.php'); ?>
</head>
<body>
<? include('results-div.php'); ?>
<? include('search-form.php'); ?>
</body>
</html>
You should just respect this order then you can split the code in different pieces and include it into your main php file;
PS: peraphs your code should look like this:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script>
$(function() {
$('#search-form').submit(function(e) {
e.preventDefault();
var searchVal = $('#search_term').val();
var query = $(this).serialize(); // search_term=lorem&category=foo
if (!searchVal) {
$('#results_cont').html('No input...');
} else {
$('#results_cont').html('<div id="loader">'+
'<img src="layout/ajax-loader.gif" alt="" /><div>');
$.ajax({
type: 'POST',
url: 'dosearch.php',
data: query,
success: function(response) {
$('#results_cont').html(response);
}
});
}
});
});
</script>
</head>
<body>
<form id="search-form">
<input type="text" id="search_term" name="search_term" />
<select id="category" name="category">
<option value="foo">foo</option>
<option value="bar">bar</option>
</select>
<input type="submit" name="search_button" />
</form>
<div id="results_cont"></div>
</body>
</html>
you can make your search_button redirect to your search.php an do the work when the pages is loaded instead of doing it on the click event.
and use $_GET['Search'] on the search page
and your url should look like this
/search.php?Search=1337

Categories