Im trying to send a value of a dropdown on change to a php script. But with my way of solving the problem, the form and also the status String are posted twice. Once with GET parameter set, and the other without. I dont know how to solve,but maybe you are smarter than me.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.easing.1.3.js"></script>
<script type="text/javascript" src="js/jquery.ennui.contentslider.js"></script>
<script type="text/javascript">
function showUser()
{
var users = document.getElementById('users').value;
if (users=="" )
{
document.getElementById("pictab").innerHTML="";
return;
}
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("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","slider.php?users="+users,true);
xmlhttp.send();
xmlhttp.reload();
}
<?php
//.............
//..............
//.............
//..............
$soso = mysql_num_rows($connn3);
for($i=0;$i<$soso;$i++)
{
echo "
$(function() {
$('#one$i').ContentSlider({
width : '280px',
height : '180px',
speed : 400,
easing : 'easeOutQuad'
});
});";
}
?>
</script>
<!-- Site JavaScript -->
<form>
<select id="users" name="users" onChange="showUser()" >
<option value="bikes">Bikes</option>
<option value="zub">Stuff/option>
<option value="sonst">Other</option>
</select>
</form>
<br>
<div id="txtHint"></div>
<?php
if(isset($_GET['users'])){
echo "<h2>Q posted</h2>";
$q = $_GET['users'];
echo $q;
//DB QUERY WITH Q
}elseif(!isset($q)){
echo "KEIN Q GEPOSTET";
// DB QUERY WITHOUT Q
}
?>
You've included Jquery into your project so use its features. Mostly Jquery Ajax to handle Ajax requests.
$(function (){ //document is loaded so we can bind events
$("#users").change(function (){ //change event for select
$.ajax({ //ajax call
type: "POST", //method == POST
url: "slider.php", //url to be called
data: { users: $("#users option:selected").val()} //data to be send
}).done(function( msg ) { //called when request is successful msg
//do something with msg which is response
$("#txtHint").html(msg); //this line will put the response to item with id `#txtHint`.
});
});
});
The php part of code should be in slider.php. Moreover, in example I use POST but if you want GET simply change type: "GET". In script.php to get value of it use:
$_POST['users']; or if you change the type to GET then $_GET['users'] you can also use $_REQUEST['users'] which handles POST, GET, COOKIE.
I think this is because your are actually making 2 calls. One in Javascript to the PHP file and the other your echoing no matter what is set. I would comment but haven't got enough juice yet.
Try and echo out $_GET and see what your are actually setting before the call and after the call. From there you may be able to see what's actually going on. I hope this helps guide you in the right direction.
var name=document.forms["myform"]["user"].value;
$.ajax({
type: "POST",
url: "yourpagenmae.php",
data: { name: user }
,
success: function(msg) {
// alert(msg);
}
});
hope it will help you
//view file
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
//use jquery get method
$('#users').change(function() {
//get the user value
var user = $('#users').val();
$.getJSON( "http://localhost/test.php?users="+user, function( data1 ) {
console.log(data1);
//status
if (data1.status) {
alert(data1.q);
//whatever response variable key
$('#txtHint').html(data1.q)
} else {
alert('error'+data1.q);
}
});
});
});
</script>
<!-- Site JavaScript -->
<form>
<select id="users" name="users" >
<option value="bikes">Bikes</option>
<option value="zub">Stuff</option>
<option value="sonst">Other</option>
</select>
</form>
<br>
<div id="txtHint"></div>
//test.php file
<?php
$data = array();
if(isset($_GET['users'])){
//echo "<h2>Q posted</h2>";
$q = $_GET['users'];
$data['status'] = true;
$data['q'] = $q;
}elseif(!isset($q)){
$data['status'] = false;
$data['q'] = 'KEIN Q GEPOSTET';
}
header('Content-type:application/json');
//json response
echo json_encode($data);
?>
Related
I have a simple form that that when changed includes a php file in a div. For some reason jquery will not load when placed in that included file? Can someone tell me why this doesnt work.
<select name='make' onChange='show(this.value)'>
<option value='some-file.php'>the file</option>
</select>
<div id="make">Where the file is loaded and where jquery wont work</div>
<script type="text/javascript">
function show(str)
{
if (str=="")
{
document.getElementById("make").innerHTML="";
return;
}
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("make").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","include/some-file.php?q="+str,true);
xmlhttp.send();
}
</script>
Then some-file.php
$models = mysql_query("SELECT model, id FROM model where make like '%".$q."%' order by model asc") or die(mysql_error());
//Puts it into an array
$count = 1;
$max = 3;
while($model = mysql_fetch_array( $models ))
{
if($count%20==1)
echo '</ul><ul style="float:left; padding:0; margin-right:10px;" class="makesModels">';
echo "<li style='padding-right:5px; display:block;'><font color='#fe9000'>".$count.".</font> ".$model['model']." <a class='delete-model".$model['id']."'>x</a></li>";
<script type='text/javascript' src='http://code.jquery.com/jquery-1.8.1.min.js'></script>
<script type='text/javascript'>
$(docuument).ready(function() {
$(".delete-model<? echo $model['id'];?>").click(function() {
alert("delete");
});
});
</script>
$count++;
}
?>
i've had the same exact problem ...
to solve this all you need to do is edit the ajax from using normal JavaScript to $.ajax so use jQuery to handle it .. and it will work ..
$.ajax({
url: "include/some-file.php?q="+str,
type: "GET",
datatype: 'html',
success: function(e){
$('#make').html(e);
}
});
I'm not sure about it, because the code is not complete, my guess would be that on someotherphpfile that you are importing you use document.ready function which is not calling because you load the file using ajax.
scripts loaded with ajax or in general a script string injected in the DOM will not execute for security reasons
you can use eval to get it working although i must warn you that you could be opening a can of worms..
after document.getElementById("make").innerHTML=xmlhttp.responseText; add this..
var parent = document.getElementById('make');
var myScript = parent.getElementsByTagName('script');
for(var i=0,len=myScript.length; i<len; i++){
executeScrpt(myScript[i]);
}
then the execute function...
function executeScrpt(scrpt){
if(scrpt.innerHTML != ""){
eval("("+script.innerHTML+")");
} else {
if(scrpt.src != ""){
var myScrpt = document.createElement("script");
myScrpt.src = scrpt.src;
document.head.appendChild(myScrpt);
}
}
}
The below code is to create a campaign. Before creation, I have to validate the form. I have to validate the campaign name which is already existed in database or not. I don't know whether I can use PHP code inside javascript (like below).Anyway it's not working. How can I change my code? How can I validate values with database values?
$this->campaign is an array which contain all campaign details from database.
<script type="text/JavaScript">
function validate()
{
var name = document.getElementById('name').value;
var shape = document.getElementById('shape').value;
<?
foreach($this->campaign as $c)
{
$old_cname=$c['name'];
?>
if(name==<?=$old_cname;?>)
{
alert("same name exists in database. Try again!");
}
<?
}
?>
if(!name)
{
alert("Please enter a name!");
return false;
}
if(!shape)
{
alert("Please select shape!");
return false;
}
return true;
}
</script>
<form action="create.php" method="post" onsubmit="return(validate());">
Name:
<input type="text" name="name" id="name"/>
Shape:
<select name="shape" id="shape">
<option value="long">Long</option>
<option value="tall">Tall</option>
</select>
<input type="submit" value="Create" name="submit"/>
</form>
Thanks!
You can't mix php and javascript like that.. php is a server-side language, while javascript is client-side; php renders the page before the user sees it, while javascript modifies the page without refreshing. Any php values in your js will get rendered and output before the js even executes.
In order to do what you need, you need to use ajax, which is asynchronous javascript and xml, a method of client-server communication that allows for what you want to happen.
To do this, I would suggest jQuery, a javascript library which makes such requests very simple. As an example of how you would make such a request in jquery....
The jQuery.ajax() method:
$.ajax({
url: "validate.php",
type: "POST",
data: "username=" + username,
sucesss: function(data) {
if (data == 1)
$("#ajax_div").html("Username is taken, choose another!");
}
else {
$("#ajax_div").html("Username is free :)");
}
}
});
That would be how to do it in ajax, while your php file would either return a 1 or a 0 depending on the result of an sql query comparing usernames in the database.
To do this without jquery, it would be something like this:
function checkUsername() {
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) {
if (xmlhttp.responseText == 1) {
document.getElementById('ajax_div').innerHTML = "Username is taken, please choose another!";
}
else {
document.getElementById('ajax_div').innerHTML = "Username is free :)";
}
}
}
xmlhttp.open("POST","validate.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("username=" + username);
}
}
You should use jquery to validate using a php script. The best way to do this is to disable the submit button until all fields are verified. This requires that you to listen to keystrokes then make a jquery call to validate the input field. A simple example below
script.js
var typingTimer; //timer identifier
var doneTypingInterval = 5000; //time in ms, 5 second for example
//on keyup, start the countdown
$('#myInput').keyup(function(){
typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//on keydown, clear the countdown
$('#myInput').keydown(function(){
clearTimeout(typingTimer);
});
//user is "finished typing," do something
function doneTyping () {
$.ajax({
type: "POST",
url: 'ajax/validate.php',
data: 'cname='+$('#name').val(),
success: function(data) {
if(data == "original"))
//enable the submit button
else
//Update your div that contains the results
}
});
}
ajax/validate.php
<?PHP
//Run your validations here
?>
This is a Google suggestion-like script.
I rewrote the AJAX Call code by splitting it up into multiple functions and seems this is a better cross-browser/usability approach. Now I need to pass the input variable that I read from the input #search_text to a php file where I actually fetch the data from database.
For moment all I need is to pass search_text and display it with echo $_GET['search_text'];
Can someone help me?
Here is the script
<script type="text/javascript">
/*note xmlHttp needs to be a global variable. Because it is not it requires that function handleStateChange to pass the xmlHttp
handleStateChange is written in such a way that is expects xmlHttp to be a global variable.*/
function startRequest(getURL){
var xmlHttp = false;
xmlHttp = createXMLHttpRequest();
//xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.onreadystatechange=function(){handleStateChange(xmlHttp);}
xmlHttp.open("GET", getURL ,true);
xmlHttp.send();
}
function createXMLHttpRequest() {
var _msxml_progid = [
'Microsoft.XMLHTTP',
'MSXML2.XMLHTTP.3.0',
'MSXML3.XMLHTTP',
'MSXML2.XMLHTTP.6.0'
];
//req is assiqning to xmlhttp through a self invoking function
var xmlHttp = (function() {
var req;
try {
req = new XMLHttpRequest();
} catch( e ) {
var len = _msxml_progid.length;
while( len-- ) {
try {
req = new ActiveXObject(_msxml_progid[len]);
break;
} catch(e2) { }
}
} finally {
return req;
}
}());
return xmlHttp;
}
//handleStateChange is written in such a way that is expects xmlHttp to be a global variable.
function handleStateChange(xmlHttp){
if(xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
//alert(xmlHttp.status);
//alert(xmlHttp.responseText);
document.getElementById("results").innerHTML = xmlHttp.responseText;
}
}
}
function suggest() {
startRequest("ajax-submit.php");
}
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" onkeydown="suggest();" />
</form>
<div id="results" style="background:yellow"></div>
</body>
and the php file is:
<?php
echo 'Something';//'while typing it displays Something in result div
//echo $_GET['search_text'];
?>
Thanks
The issue is that you're not actually passing in any data to the PHP script. In this case, you need to stick the 'search_text' parameter on the end of the URL, since you're expecting it to be a GET request.
startRequest("ajax-submit.php");
should be
startRequest("ajax-submit.php?search_text="+document.search.search_text.value);
this jQuery Solution is way easier and Cross-Browser compatible:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready( function(){
$('#search_text').keydown(function(){ // Bind event to KeyDown
var search_text = $(this).val(); // get value of input field
$.ajax({ // fire Ajax Request
url: "ajax-submit.php?search_text=" + search_text,
success: function(result){
$("#results").html(result); // on success show result.
}
});
});
});
</script>
<body>
<form action="" name="search" id="search">
<input type="text" name="search_text" id="search_text" />
</form>
<div id="results" style="background:yellow"></div>
</body>
I'd like to do a sql query with ajax so I don't need to reload the page / load a new page.
So basicly I need to call a php page with ajax. And it would be great if there could be a way to reload a count of amount of rows in a table too.
Edit: to make it more clear, it should be able to do something along the lines of when you click the Like button on Facebook.
Thanks
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
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("your_div").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax_file.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">here are your contents</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
You don't want to query using ajax, you want to get new data using ajax, which is a fundamental difference.
You should just, using ajax, request a php page with perhaps some parameters, which in turn executes the query and returns the data in a format you can handle (most likely: json).
If you allow queries to be executed using ajax, how are you going to prevent a malicious user from sending drop table users, instead of select * from news where id = 123?
You won't do a sql query with ajax, what you need to do is call an external php page (one where your query is) in the background using ajax. Here is a link that explains how to do it with jquery: http://api.jquery.com/jQuery.ajax/
"Facebook Like" button in Agile Toolkit (PHP UI Library):
$likes = get_like_count();
$view = $this->add('View');
$button = $view->add('Button')->setLabel('Like');
$view->add('Text')->set($likes);
if($button->isClicked()){
increate_like_count();
$view->js()->reload()->execute();
}
p.s. no additional JS or HTML code needed.
function onClick(){
$.post(
"path/to/file", //Ajax file ajax_file.php
{ value : value ,insiId : insiId }, // parameters if you want send
//function that is called when server returns a value.
function(data){
if(data){
$("#row_"+data.id).show(); //display div rows
}
},"json"
);
}
<div id="myDiv">here are your contents</div>
<button type="button" onclick="onClick()">Change Content</button>
Here the ajax code that you can call to the server side php file and get the out put and do what you want
You are wrong, who says that he is submitting the whole query who is telling that he is not filtering? U can do all this easy with the jquery load function, you load a php file like that $('#BOX').load('urfile.php?param=...');.
Have fun,
i hope that was a little helpful for you, sry bcs of my bad english.
Possible solution: Ajax calls PHP scripts which make the query and return the new number
$.ajax({
async:true,
type:GET,
url:'<PHP_FILE>',
cache:false,
data:'<GET_PARAMETERS_SENT_TO_PHP_FILE>',
dataType:'json',
success: function(data){
$('<#HTML_TARGET>').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('<#HTML_TARGET>').html('<div class="ajax_error">'+errorThrown+'</div>');
}
});
Where
<PHP_FILE> is your php script which output must be encoded according to dataType. The available types (and the result passed as the first argument to your success callback) are: "xml", "html", "script", "json", "jsonp", "text".
<GET_PARAMETER_SENT_TO_PHP> is a comma separate list of value sent via GET (es. 'mode=ajax&mykey=myval')
<#HTML_TARGET> is the jquery selector
See jquery.ajax for more details.
For example:
<p>Votes:<span id="count_votes"></span></p>
<script type="text/javascript">
$.ajax({
async:true,
type:GET,
url:'votes.php',
cache:false,
dataType:'text',
data:'id=4'
success: function(data){
$('#count_votes').html(data);
},
error: function(jqXHR, textStatus, errorThrown){
$('#count_votes').html(errorThrown);
}
});
</script>
If your looking for something like the facebook like btn. Then your PHP code should look something like this -
<?php
$topic_no = $_POST['topic'];
$topic_likes = update_Like_count($topic_no);
echo $topic_likes;
function update_Like_count($topic)
{
//update database by incrementing the likes by one and get new value
return $count;
}
?>
and the javascript/jquery ajax should be something like so -
<script>
$('#like-btn').click( function () {
$.post(
"like.php",
{ topic : value },
function(data)
{
if(data)
{
$("#like-btn span").append(data); //or append it to wherever you'd like to show it
}
else
{
echo "error";
}
},
"json"
);
});
</script>
Here is an example which uses a favorite jQuery plugin of mine, jQuery.tmpl(), and also the jQuery .text() function.
HTML and Javascript Code:
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="http://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js"></script>
</head>
<body>
<script id="UserTemplate" type="text/x-jquery-tmpl">
<li><b>Username: ${name}</b> Group ID: (${group_id})</li>
</script>
<button id="facebookBtn">Facebook Button</button>
<div id="UserCount"></div>
<ul id="userList"></ul>
<script>
function getData(group_id) {
$.ajax({
dataType: "json",
url: "test.php?group_id=" + group_id,
success: function( data ) {
var users = data.users;
/* Remove current set of movie template items */
$( "#userList" ).empty();
/* Render the template with the movies data and insert
the rendered HTML under the "movieList" element */
$( "#UserTemplate" ).tmpl( users )
.appendTo( "#userList" );
$( "#UserCount" ).text('Number of users: '+ data.count);
}
});
}
$( "#facebookBtn" ).click( function() {
getData("1");
});
</script>
</body>
</html>
PHP Code
<?php
//Perform a query using the data passed via ajax
$group_id = $_GET['group_id'];
$user_array = array(
array('name'=>'John','group_id'=>'1',),
array('name'=>'Bob','group_id'=>'1',),
array('name'=>'Dan','group_id'=>'1',),
);
$user_count = count($user_array);
echo json_encode(array('count'=>$user_count,'users'=>$user_array));
HTML:
//result div will display result
<div id="result"></div>
<input type="button" onclick="getcount();" value="Get Count"/>
JS:
//will make an ajax call to ustom_ajax.php
function getcount()
{
$.ajax({
type:"get",
url : "custom_ajax.php",
beforeSend: function() {
// add the spinner
$('<div></div>')
.attr('class', 'spinner')
.hide()
.appendTo("#result")
.fadeTo('slow', 0.6);
},
success : function (data) {
$("#result").html(data);
},
complete: function() {
// remove the spinner
$('.spinner').fadeOut('slow', function() {
$(this).remove();
});
}
});
}
custom_ajax.php:
//will perform server side function
//make a connection and then query
$query_txt = "SELECT count(*) FROM table ";
$result= mysql_query($query_txt) or die(mysql_error());
$total=mysql_num_rows($result) ;
$html= "Total result is $total";
echo $html; exit();
I have a page called getvalues.php, I need to call a function which is written in a different php page(fileclass.php) in a class from this page(getvalues.php), but the issue is i need to pass a variable also which is $i, and the value of $i passed should be 1 if we are selecting option B, and $i=2 if option=c, and $i=3 if option=D given in dropdown. I had simply wiritten an onchange event but had not written any code in javascript. Please help Thanks. Here is the code for getvalues.php
<html>
<select id="s" onchange="callsome();">
<option value='B' selected>B</option>
<option value='c'>c</option>
<option value='D'>D</option>
</select></html>
<?php include("fileclass.php")
$obj=new file;
echo $obj->func($i);?>
You could implement this using JQuery or Javascript (I use JQuery in the example because it is shorter and easier to make Ajax calls) :
<html>
<select id="s" onchange="callsome();">
<option value='1' selected="selected">B<option>
<option value='2'>C</option>
<option value='3'>D</option>
</select>
<script>
function callsome() {
var selected = $('select#s option:selected').val();
$.ajax({
type: "POST",
url: "fileclass.php",
data: ({selectedvalue : selected}),
success: function(data) {
alert(data);
}
});
}
</script>
</html>
After that the callsome returns the output of the fileclass.php script and you can use that however you like in your code. From your explanation it was not really clear what is happening in fileclass.php and what you want to do with it, so I hope it helps you.
If you want the function in Javascript only:
<script type="text/javascript">
function callsome() {
var e = document.getElementById("s");
var strVal = e.options[e.selectedIndex].value;
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) {
var data = xmlhttp.responseText;
//use the data as you wish
}
}
xmlhttp.open("GET","fileclass.php?selectedvalue=strVal",true);
xmlhttp.send();
}
</script>
This isn't the way PHP and HTML work.
PHP is rendered on the server. HTML is rendered on the client, after the PHP is completely done. To do what you want to do, you need to have the HTML (possibly Javascript) make a request to the PHP page at fileclass.php.