I would like to trigger the php post to database script without refreshing the page (like it happens with regular php self).
Check out jQuery $.post( ) functionality. Here is a link to get you started: http://api.jquery.com/jQuery.post/
I'm using this to do what you want:
function parseJsonIfPossible(code){
try {
return $.parseJSON(code);
} catch (e) {
return code;
}
}
function cmd(command,p1,p2,p3,p4,p5,p6){
return parseJsonIfPossible($.ajax({
url: core_url,
global: false,
type: "POST",
data: {command : command,p1:p1,p2:p2,p3:p3,p4:p4,p5:p5,p6:p6},
dataType: "html",
async:false,
success: function(msg){
//alert(msg);
}
}).responseText);
}
PHP:
function cmd()
{
$command = &$_POST['command'];
$p1 = &$_POST['p1'];$p2 = &$_POST['p2'];$p3 = &$_POST['p3'];$p4 = &$_POST['p4'];$p5 = &$_POST['p5'];$p6 = &$_POST['p6'];
if($command)echo($command($p1,$p2,$p3,$p4,$p5,$p6));
}
function test($i)
{
//simple
return mysql_query("UPDATE ... SET b='$i'");
//array
return json_encode(array(
mysql_query("UPDATE ... SET b='$i'"),
"fklsdnflsdnl",
));
}
usage (script):
$('#btn').click(function(){
var i = 99;
var result = cmd("test",i);
//simple
alert(result);
//array
console.log([result[0],result[1]]);
});
Here is a basic sample code for Ajax request.
function postData()
{
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 anything you want with the response
alert(xmlhttp.responseText);
}
}
xmlhttp.open("POST","page_to_be_post.php",true);
xmlhttp.send();
}
However you can use some frameworks to do this easily with less code.
Ex:
http://www.prototypejs.org/learn/introduction-to-ajax
http://api.jquery.com/jQuery.post/
There are many more frameworks available.
Cheers!
The below code might help you in php post using jquery ajax.
Suppose you have a form with id=form and a button to submit the form whose id=submit1.
Now to send the form data to another page using jquery ajax you need the following code just before the end of body.Dont forget to attach the jquery script before writing the below code.
$(document).ready(function(){
$('submit1').click(function(event){
//first stop the default submit action
event.preventDefault();
//now we will do some ajax
$.ajax({
url:'test.php',//the target page where to submit the data
type:'post',
cache:false,
data:$('#form').serialize(),//data to be sent from the form
dataType:'json',//expected data type from the server
error:function(xhr){
alert("the error is"+xhr.status);
}
})
//success function in terms of .done
.done(function(data){
alert("your data successfully submitted");
});
});
});
Related
I want to pass multiple values from from different <div> tags to another php page(onewaytrip_passenger_data.php) using ajax code on button onclick() function. This is my ajax function:
<script language="javascript">
function continoue(){
var a=$("#temp").text();
var b=$("#sno").text();
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("temp").innerHTML=xmlhttp.responseText;
document.getElementById("sno").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","onewaytrip_passenger_data.php?count="+a+"seatno="+b,true);
xmlhttp.send();
}
</script>
#temp and sno are my two different <div> id's these are my <div> tags
<div id="temp" style="visibility:hidden;"></div>
<div id="sno" style="visibility:hidden;"></div>
This is my button:
<input name="continoue" type="image" src="images/contioue.png" onclick="continoue()"/>
Use jQuery ajax function:
function continoue(){
var a=$("#temp").text();
var b=$("#sno").text();
$.ajax({
type: "GET",
url: "onewaytrip_passenger_data.php",
data : {count:a, seatno:b},
success: function (response) {
if (response == "success" ) {
//do something
} else {
//something
}
},
error: function () {
//console.log('Error --------');
}
});
}
in PHP file after your success code is done,
just write
<?php echo "success"; ?>
for failure,
<?php echo "failure"; ?>
Try this :
<script type="text/javascript">
var a = $("#temp").html();
var b = $("#sno").html();
$.get("onewaytrip_passenger_data.php", {count: a, seatno: b})
.done(function (data) {
alert("Data Loaded: " + data);
}).fail(function () {
alert("error");
});
</script>
Please read this also for your reference.
<html>
<head>
<script>
$('patientlist').click(function showpatient()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST","ajaxlistpatient.php",true);
xmlhttp.send();
})
</script>
</head>
<body>
<form>
<input type="button" id="patientlist" name="patientlist" value="List Patient"/>
</form>
</body>
</html>
please help, i want to list my patientlist using a button in the same page without reloading my mainpage.
ajaxlistpatient.php contains my sqlquery ..
You can't access the DOM like this $('patientlist'). It has to be either $('.patientlist') or $('#patientlist')
Assuming 'patientlist' is a class,
$('.patientlist').click(function (){
console.log("Clicked"); //Check you got here without any problem
$.ajax({
type: "POST",
url: "ajaxlistpatient.php",
dataType: 'json',
success: function (data)
{
console.dir(data);
},
error: function (jqXHR,textStatus,errorThrown)
{
//Check for any error here
}
});
});
try using jQuery library for this, because ajax operation is quirky and complicated.
Take a look at this document:
http://api.jquery.com/jQuery.ajax/
Even though you havn't tagged Jquery in your question it looks like Jquery is being used for the click event anyway. So here you go:
$('#patientlist').on('click', function(e){
e.preventDefault();
e.stopPropagation();
$.ajax({
url : "ajaxlistpatient.php",
type: "post",
complete: function(d){
//do something with the return data'd'
}
});
});
You will need to decide what you want to do with the response. Make sure you have access to something like firebug in firefox which will help you out massivly so you can see the ajax call being sent out and see the response via the firebug console. Chrome also has a console and debug tools but I prefer firefox/firebug.
You could juse use the jQuery ajax method:
$('#patientlist').click(function showpatient() {
$.ajax({
type: 'POST',
dataType: "xml",
url: 'ajaxlistpatient.php',
success: function (data) {
$('#myContentContainer').html(data);
}
});
});
Here is the general and simplest syntax of using ajax:
$('patientlist').click(function ()
{
$.post('ajax_files/ajaxlistpatient.php', {var_id:anyData},
function(data)
{
$('#yourDataHolder').html(data);
});
});
All responses are in the right direction, Jquery+php is your best bet, and to further extend those responses, here are some previous similar posts that might help you to have a reference:
AJAX to call PHP file which removes a row from database?
AND
How to pass jQuery variables to PHP variable?
are good sample resources,
hope this helps.
I am trying to write a function that will call getproduct.php?id=xxx when clicked. I can get the innerHTML portion to appear, but how do I also call the php page that actually does the work?
var id = id;
document.getElementById("digital_download").innerHTML =
"Downloading...Please be patient. The process can take a few minutes.";
url = getproduct.php?id=id;
you can call or load php page inside a div using this line as :-
$("#content_div").load("ajax/page_url.php");
the "ajax/page_url.php" its a relative path of php file.
so here you can replace it with external url as well.
please share you knowledge if i am wrong.
You can do it with jQuery for example.
var id = 1;
$('#digital_download').html('Downloading...'); // Show "Downloading..."
// Do an ajax request
$.ajax({
url: "getproduct.php?id="+id
}).done(function(data) { // data what is sent back by the php page
$('#digital_download').html(data); // display data
});
There are many ways by which you can load a page into a division .
The very method is
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('digital_download').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", 'getproduct.php?id=' + id,true);
xmlhttp.send();
}
this is a typical method with no external reference.
If you go with reference then there are 5 ways to make a ajax call with jQuery
load(): Load a piece of html into a container DOM.
jQuery.getJSON(): Load a JSON with GET method.
jQuery.getScript(): Load a JavaScript.
jQuery.get(): Use this if you want to make a GET call and play extensively with the response.
jQuery.post(): Use this if you want to make a POST call and don’t want to load the response to some container DOM.
jQuery.ajax(): Use this if you need to do something when XHR fails, or you need to specify ajax options (e.g. cache: true) on the
fly.
Edit: the original question didn't reference jQuery. Leaving this answer here as others may find it useful.
Here's how you would do this using the XHR object for an ajax request without jQuery or Prototype or other JS library.
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('digital_download').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", 'getproduct.php?id=' + id,true);
xmlhttp.send();
}
Hi You can call the below function to perform this it loads the data from server on success you can create fail function as well
function setValue(Id) {
document.getElementById("digital_download").innerHTML =
"Downloading...Please be patient. The process can take a few minutes.";
var data1 = {
message: Id,
};
$.ajax({
data: data1,
type: 'GET',
url: "http://urltoscript/index.php",
cache: false,
dataType: "json",
crossDomain: true,
success: function(data) {
console.log("Response for cancel is: " + data);
document.getElementById("digital_download").innerHTML = data
}
});
}
You can use get or post request using query
$.ajax({
type: "POST",
url: url,
data: data,
success: success,
dataType: dataType
});
example
I've been trying to figure out how to send a variable from a form to multiple pages using ajax and have each pages script alter the a div contents.
The script I have is working, but it seems like a huge waste of resources and im sure there is a simpler way.
// Function to process the input form
function ConsoleUpdateFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
$('#outputDiv').Typewriter({animDelay: 10,text: ajaxRequest.responseText, div: 'outputDiv' });
//clear the form
$('#inputForm').each(function(){ this.reset();});
//hide the input form till the out has finished showing
window.setTimeout(function(){ document.getElementById('inputForm').style.visibility="visible"; },ajaxRequest.responseText.length*10);
}
}
var age = document.getElementById('inputfield').value;
var queryString = "?inputfield=" + age;
ajaxRequest.open("GET", "consoleprocess.php" + queryString, true);
ajaxRequest.send(null);
//hide the input form
document.getElementById('inputForm').style.visibility="hidden";
}
// Function to process the input form
function VisualInterfaceUpdateFunction(){
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('visualWindowContent');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
//clear the form
$('#inputForm').each(function(){ this.reset();});
//hide the input form till the out has finished showing
window.setTimeout(function(){ document.getElementById('inputForm').style.visibility="visible"; },ajaxRequest.responseText.length*10);
}
}
var age = document.getElementById('inputfield').value;
var queryString = "?inputfield=" + age;
ajaxRequest.open("GET", "visualinterfaceprocess.php" + queryString, true);
ajaxRequest.send(null);
//hide the input form
document.getElementById('inputForm').style.visibility="hidden";
}
// Function to process the input form
function CommandExecutionFunction(){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
eval(ajaxRequest.responseText);
}
}
var age = document.getElementById('inputfield').value;
var queryString = "?inputfield=" + age;
ajaxRequest.open("GET", "commandexecution.php" + queryString, true);
ajaxRequest.send(null);
}
I'm basically creating the same function 3 times while only changing the page to send the variable to and how to deal with the returning content. But I can't figure out how to get it working in one function.
Any help will be appreciated.
EDIT:
Thank you for the help all. I believe I have solved the problem as this works fine. Of course if you see something I've done wrong let me know!
$('#inputForm').submit(function() {
$string ="inputfield=" + $('#inputfield').val();
$.ajax({
type: "GET",
url: "consoleprocess.php",
data: $string,
success: function(data) {
$('#outputDiv').Typewriter({animDelay: 10,text: data, div: 'outputDiv' });
}
});
$.ajax({
type: "GET",
url: "visualinterfaceprocess.php",
dataType: "html",
data: $string,
success: function(data) {
$('#visualWindowContent').replaceWith(data);
}
});
$.ajax({
type: "GET",
url: "commandexecution.php",
dataType: "script",
data: $string,
});
//clear the form
$('#inputForm').each(function(){ this.reset();});
return false;
});
First I think you better use jQuery $.ajax to send your ajax request. You are not really consistent in your code:
var age = document.getElementById('inputfield').value;
but later you use jQuery selector
$('#inputForm').each(function(){ this.reset();});
Also I think the better solution for your problem is to use Events. An action (click, submit, ...) trigger an event called MyEvent.
Then you can have an Event Listener that will trigger all you functions: ConsoleUpdateFunction(event, data), VisualInterfaceUpdateFunction(event, data), CommandExecutionFunction(event, data)
To resume, use jQuery $.ajax() (documentation here) and Events using jQuery $.trigger(), $.bind() or $.on() (documentation here).
I hope this will help you. It will simplify a lot of your code.
First try using Prototype or jQuery to simplify your code.
You can try sending your request to a single script instead of three and return data from PHP as JSON. See php json_encode() and http://prototypejs.org/learn/json
Basically I'm using datepicker from jQuery to have my client pick a date. I then want to take that date (once they select it) and process it through the DB to pre-fill a timepicker.
Problem is, I don't know how to take the value of that input box and process it without actually having to submit a form. I want to deal with the value once they choose.
Here is my datepicker code:
$(function() {
$( "#datepicker" )
.datepicker({ minDate: '+1' });
});
I guess I would somehow have to add an onblur event, but I'm not sure what the best way to go about doing this is.
To actually have the server process the value of the date picker without submitting a form you would have to pass that value to the server via AJAX.
$('.datepicker').datepicker({
onSelect: function(dateText, inst) {
$.ajax({
url: "yourscript.php",
type: "POST",
data: ({date : dateText}),
success: function(data){
alert(data);
}
});
}
});
You can do this using the JQuery AJAX support.
$("#datepicker").change(function(){
$.ajax({
type:"GET",
url :"URL here",
Success:function(responsed){ alert("added"); }
});
});
You'll have to use ajax for this if you don't want a form sent.
// code for IE7+, Firefox, Chrome, Opera, Safari
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
// code for IE6, IE5
} else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET",site,false);
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
Where the var site is the php page with get vars attached, or if you have to use a POST request change "GET" to "POST" and replace the null in xmlhttp.send(null) with a string of post vars.
Hope this helped!