What are the differece between these two forms of Ajax calls - php

This code is from tiztag tutorial
function ajaxFunction(){
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){
document.myForm.time.value = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "serverTime.php", true);
ajaxRequest.send(null);
}
This is another one I find throughout jQuery website:
$.ajax({
type:"GET" // or "POST"
url: url,
data: data,
success: success,
dataType: dataType,
error: //function
});
I've been trying to use both ways to get some sort of response from PHP file. The first example works but I also want to get the second form to work... could someone give me some guidance? In my php all i have is:
<?php
echo("Response from PHP");
?>

The difference between the two is almost nothing. jQuery just prevents you from doing the extra boiler plate code surrounding the cross browser compatibility.
The jQuery documentation should give you all the information you need.
You will need to have an url variable, and a success variable.
The url variable will be a string to the URL in which you're trying to send this information.
The success variable will be a 'callback' function that will do whatever it is you're trying to do. It will ONLY be called if your call was a success.
Always check your Javascript console to see what your errors are.

Try this
$.ajax({
type:'GET' // or "POST"
url: 'http://www.yoursite.com/yourPhpFile.php',
data: 'some text',//Can be multiple data using object
success: function(data){
alert(data);
},
error: function(){
//Do something if an error is occurred
}
});

Related

ajax using php and mysql

<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.

How to load a PHP page into a div with jQuery and AJAX?

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

Sometimes only some data lose, calling a javascript function but not calling a php function, from the same javascript

I have a code like:
function doSomething(customer)
{
var xmlhttp = new getXMLObject();
var customer1 = customer;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtSomething").innerHTML=xmlhttp.responseText;
}
}
var params = "customer=" + customer;
xmlhttp.open("POST","/something.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
post.call(this, customer1);
}
In some executions, the second function called post lose the value on the variable customer1, but it arrives well to something.php.
Is there something wrong?
Thank you.
AJAX is asynchronous. You fire off the AJAX call, but that .send() returns IMMEDIATELY, without waiting for a response. So your code continues on and does that post.call() call, without waiting for anything from the server.
Have you tried jQuery Ajax, where you can setup some callbacks to check the response?
And, it is even more cross-browser than your code probably is! :)
You can do some cool stuff just with this. Check an example:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
Check here.

Sending form variable to multiple php scripts using ajax

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

PHP post with ajax

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");
});
});
});

Categories