I'm stuck in a problem here that I tried all google answers and nothing did this work out. Specially because I prefer to do a pure JavaScript solution if possible... I have a menu, with a cart. This menu shows something like: Your cart (0)
where 0 is the number of items inside the cart. The items number are query from a SQL table 'cart', where I save all users products added to cart. So they don't lose the items on cart when the session closes. But I want to update this menu span everytime they add something inside the cart, without the need to refresh the page. The items are being added this way:
In the table where products are displayed I have:
<td id="add'.htmlspecialchars($row['id'], ENT_QUOTES, 'UTF-8').'"> <label><b><img src="/img/cart.gif" /></b></label> </td>
so I call javascript:addtocart passing 'id' of the product as parameter. This function does:
function addtocart(id)
{
document.getElementById('add'+id).innerHTML='<b>On your cart!</b>';
load('/index.php?addtocart&id='+id);
}
Ok, function load does:
function load(url) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
eval( xmlhttp.responseText );
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
OK, so we have my index.php receiving the GET with id of the product to add to cart, and I do on index.php:
if (isset($_GET['addtocart']) && isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO cart VALUES('$id', '$userid')");
}
This is working very well, and if I refresh the page, in the menu I get "Your cart (1)"... But how to do this refresh automatically when the client clicks on the table? Possible with pure javascript function?
//EDIT for index.php content:
<?php
include("./includes/header.php");
include("./includes/db.php");
?>
<html>
<head>
<link rel="stylesheet" href="./css/style.css">
<title>MyShop</title>
<script type="text/javascript">
function load(url) {
var xmlhttp;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject('Microsoft.XMLHTTP');
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('cart').innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open('GET', url, true);
xmlhttp.send();
}
function addtocart(id)
{
document.getElementById('add'+id).innerHTML='<b>On your cart!</b>';
load('/index.php?addtocart&id='+id);
}
</script>
</head>
<body id="home">
<?php include 'menu.php'; ?>
<div id="container">
<?php
if (isset($_GET['news']))
{
include 'news.php';
}
else if (isset($_GET['orders']))
{
include 'orders.php';
}
else if (isset($_GET['addtocart']) && isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO cart VALUES('$id', '$userid')");
}
?>
</div>
</body>
</html>
From your index.php page, return the number of products inserted for the current user and then use the success handler of the ajax call to update the span.
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// here get the number of products inserted and display in span
document.getElementById('span_id').innerHTML = xmlhttp.responseText;
}
}
EDIT
Do not make the ajax call to the same page. Have the id sent to some other page, let's say abc.php. Then keep only the php related code inside your update_cart_ajax.php page.
So your addtocart() becomes:
function addtocart(id)
{
document.getElementById('add'+id).innerHTML='<b>On your cart!</b>';
load('/update_cart_ajax.php?addtocart&id='+id);
}
update_cart_ajax.php
<?php
include("./includes/db.php");
if (isset($_GET['addtocart']) && isset($_GET['id']))
{
$id = mysql_real_escape_string($_GET['id']);
mysql_query("INSERT INTO cart VALUES('$id', '$userid')");
}
else
{
echo 0;
exit;
}
// get the number of products added to the cart for the current user
$total_products_in_cart = <value returned from db>;
echo $total_products_in_cart;
exit;
Related
Problem is that i have dynamic changing script for mysql query
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
}
</script>
I need to get str from this code to php.
from the html point of view i get string from
<select name="users" onchange="showUser(this.value)">
adn in the other file getuser.php I have
$q = $_GET['q'];
$sql="SELECT * FROM articles WHERE type = '".$q."'";
The biggest problem is that i put onchange this parameters so i can get values to my page without refreshing it. But now i cant get value from combobox to php.
How can i do this ???
Thanks in advance
I have this JavaScript:
<script>
if (str == "") {
document.getElementById("txtHint1").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "/npsmart/umts/action_plano/?q=" + query1, true);
xmlhttp.send();
}
</script>
And this JavaScript call a page called getuser.php.
This is the code of getuser.php:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"></p>
<script>
document.getElementById("dumb").innerHTML = "WORK";
</script>
</body>
</html>
What I would like is only to change the paragraph content, called dumb, to WORK. But when I call the page and it loads, my paragraph content keep null.
It's like my Ajax Call Request don't execute the Script Tag.
EDIT:
I have already solved my problem with this simple but genious solution:
function showUser() {
if(query_num == 2){
if (str == "") {
document.getElementById("txtHint1").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint1").innerHTML = this.responseText;
eval(document.getElementById("runscript").innerHTML);
}
};
xmlhttp.open("GET","/npsmart/umts/action_plano/?q="+55555,true);
xmlhttp.send();
}
And in my getuser.php file:
<script type="text/javascript" id="runscript">
document.getElementById("dumb").innerHTML = "WORK";
</script>
I just putted the : eval(document.getElementById("runscript").innerHTML); in my function and then in the php file I called this script using this:
<script type="text/javascript" id="runscript">
So thanks everybody =)
Hope this post can help other people.
JS is not executed automatically from a script embedded in the response.
Since getuser.php is a PHP script there's no need to use JS and have the browser set the paragraph content. Use PHP itself:
<!DOCTYPE html>
<html>
<body>
<p id="dumb"><?php echo 'WORK'; /* or anything else */ ?></p>
</body>
</html>
Otherwise you'll have to use JS eval on the returned AJAX response to have the browser run the JS returned from your script. But I recommend against this.
Currently, I cannot load the second content using ajax. Actually, I have loaded the first content using ajax. In order to go to the second content, i need to call the ajax function but after i click to load the second content using ajax it does not work. I have checked my code, its working fine if i directly call the second ajax function, unless i call the first ajax function after that the ajax is not working again. Are there any ways to solve this problem.
This is the first ajax code:
function showMusic(str) {
if (str == "") {
document.getElementById("albums").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("albums").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","getAlbums.php?q="+str,true);
xmlhttp.send();
}
}
The above function works. The above function is at another php file
This is the second ajax code:
$(document).ready(function(){
function showArtistDetails(str) {
if (str == "") {
alert("hi");
document.getElementById("artist").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
alert("hi1");
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
alert("hi2");
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("artist").innerHTML = xmlhttp.responseText;
alert("hi3");
}
};
xmlhttp.open("GET","getArtist.php?title="+str,true);
alert("hi4");
xmlhttp.send();
alert("hi5");
}
}
$("#clickme").click(showArtistDetails);
});
This is the php code which is at another php file:
echo "<td id=\"clickme\">" . $row['CDTitle'] . "</td>";
I have been trying to solve this for the past 2 days but i am unable to solve it. Some are saying its a bug. But i really i dont know what causes this problem. Thanks in advance.
I am trying to use Ajax to insert data into database with POST method. But php can not recognize the post variables.
ajax:
function createUser() {
var _id=document.getElementById('new_id').value;
var _name=document.getElementById('new_name').value;
var params = "id="+_id+"&name="+_name;
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
//xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.onreadystatechange = function() {
console.log(xmlhttp);
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
if(xmlhttp.responseText=="")
alert("New User is created!");
else
document.body.innerHTML=xmlhttp.responseText;
}
};
xmlhttp.open("POST","resource/create_profile.php",true);
xmlhttp.send(params);
}
php:
<?php
$id = $_POST["id"];
$name = $_POST["name"];
$conn = oci_connect(....);
$query = "....";
$result = oci_parse($conn, $query);
oci_execute($result);
oci_close($conn);
?>
if i uncomment the request header content type then nothing happens, no error is shown. if i comment it then php shows error. i am giving a screenshot.
http://imgur.com/CdKO84V
what am i supposed to do? if i use get method then it is working good but i can not use it since i need to upload file.
At last I have found the solution! I had to add the setRequestHeader() method below the open method. So in the end the code looks like:
xmlhttp.open("POST","resource/create_profile.php",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
I have three divs saved in an array as simple_html_dom objects. I needed to change a CSS property of two of them on the click of a button. That's easy, but then I also need to make that change in the CSS property (in the simple_html_dom object stored in the aforementioned array) in the PHP script on the server side.
So I figured from my web search I needed AJAX for this. So I read up this tutorial, and I am following this example, and doing something like:
On the client side:
function xyz(var divIdOne, var divIdTwo) {
document.getElementById(params.divIdOne).style.display = "none";
document.getElementById(params.divIdTwo).style.display = "block";
document.getElementById(params.divIdTwo).style.border = "5px solid red";
var xmlhttp;
if (window.XMLHttpRequest) { xmlhttp=new XMLHttpRequest();}
else { xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); }
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
On server side:
foreach($_REQUEST as $requestkey => $requestvalue) {
echo $requestkey.': '.$requestvalue;
}
if (array_key_exists('pass_back', $_REQUEST)) {
foreach ($array_of_divs as $div) {
if ($div->id=$divIdOne) {
$div->style='display:none';
} else if ($div->id=$divIdTwo) {
$div->style='display:block';
}
}
} else {echo 'FALSE!';}
The first foreach loop prints other variables but does not print pass_back. The next if block does not execute at all. The else block executes. This means that $_REQUEST clearly does not contain pass_back. Can anyone pinpoint why, or what I did wrong?
I fail to see the error. How do you check that you're not sending the data properly? I suggest using this piece of code in order to check what your server is receiving from your request:
function xyz() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
console.log(xmlhttp.responseText);// Let's see what the server is echoing
}
}
xmlhttp.open("GET","myfile.php?pass_back="+"pass_back",true);
xmlhttp.send();
}
Please, let us know the output.
I would recommend that you use jquery and firebug, and first get rid of the following problem: why is passback variable not received.
Create the file: test.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<script src="https://code.jquery.com/jquery-2.1.1.js"></script>
<title>Html page</title>
</head>
<body>
<script>
(function($){
$.post("myfile.php", {
passback: "pooo"
}, function(d){
console.log(d);
});
})(jQuery);
// or if you cannot use jquery
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
// do something with the response, if you need it...
// document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "myfile.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("passback=pooo");
// src: http://www.w3schools.com/ajax/ajax_xmlhttprequest_create.asp
</script>
</body>
</html>
Then create the file: myfile.php
<?php
if(isset($_REQUEST['passback'])){
echo "ok";
}
else{
echo "oops";
}
Next, download firefox, and download the firebug extension (or you can use chrome's console alternatively). The goal here is to see what is being passed through the network.
Launch test.php in a browser, open the firebug console (or chrome's console),
and debug until you see the "ok" message.