ajax using php and mysql - php

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

Related

Safari error. Javascript ajax json object - could not fetch properties. object may no longer exist

I have an Ajax call to a PHP backend. It is working fine in chrome but when I ran it in safari I am getting a 'could not fetch properties, object may no longer exist' error against this line in the code -
dataType: "JSON",
Here is the function. Probably something really simple. I actually found this code online and repurposed it. Not really a developer just fudging my way through :)
Any tips would be greatly appreciated! As I say, no errors in Chrome.
Thanks
Dave
function insertProjectData() {
var projectuid=$("#projectuid").val();
var projectIdentifier=$("#projectIdentifier").val();
var projectPIRDate=$("#projectPIRDate").val();
var projectName=$("#projectName").val();
var projectManagerName=$("#projectManagerName").val();
var projectSponsorDept=$("#projectSponsorDept").val();
var projectSponsorName=$("#projectSponsorName").val();
var projectSponsorContact=$("#projectSponsorContact").val();
var projectGTMDate=$("#projectGTMDate").val();
var projectTargetBudget=$("#projectTargetBudget").val();
var projectActualCost=$("#projectActualCost").val();
var projectScope=$("#projectScope").val();
var projectScopeDelivered=$("#projectScopeDelivered").val();
if ($('#projectDeliveredTimeline').is(':checked')) {
var projectDeliveredTimeline = "Yes";
}
else {
var projectDeliveredTimeline = "No";
}
if ($('#projectDeliveredPlan').is(':checked')) {
var projectDeliveredPlan = "Yes";
}
else {
var projectDeliveredPlan = "No";
}
var projectComments=$("#projectComments").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST", q
url: "insert-projectdata.php",
data: {projectuid:projectuid,projectIdentifier:projectIdentifier,projectPIRDate:projectPIRDate,projectName:projectName,projectManagerName:projectManagerName,projectSponsorDept:projectSponsorDept,projectSponsorName:projectSponsorName,projectSponsorContact:projectSponsorContact,projectGTMDate:projectGTMDate,projectTargetBudget:projectTargetBudget,projectActualCost:projectActualCost,projectScope:projectScope,projectScopeDelivered:projectScopeDelivered,projectDeliveredTimeline:projectDeliveredTimeline,projectDeliveredPlan:projectDeliveredPlan,projectComments:projectComments},
dataType: "JSON",
success: function(data) {
closeitem(projectarea);
$("#ProjectSaved").show();
setTimeout(function() { $("#ProjectSaved").hide(); }, 2500,);
$('form[name=projectForm]').get(0).reset();
window.location.replace("lessons.php");
},
error: function(err) {
console.log(err);
}
});
}
Strangely this (another page) is working fine!?...
function insertAreaData() {
var areauid=$("#areauid").val();
var areaName=$("#areaName").val();
var areaDesc=$("#areaDesc").val();
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "insert-areadata.php",
data: {areauid:areauid,areaName:areaName,areaDesc:areaDesc},
dataType: "JSON",
success: function(data) {
closeitem(areaarea);
$("#AreaSaved").show();
$('form[name=AreaForm]').get(0).reset();
setTimeout(function() { $("#AreaSaved").hide(); }, 2000,);
window.location.replace("lessons.php");
},
error: function(err) {
console.log(err);
}
});
}
Edit: I have now tested in internet explorer also and having the same issue.
So turns out that the form was posting an page was reloading and for some reason Google Chrome was handling this for me, while Safari and IE were not.
I added the following onsubmit comment to the form:
<form id="Project" name="projectForm" onsubmit="return false;">
and it prevented it from executing when I was clicking the submit button and instead ran the javascript.
Just for completeness here is the submit:
<input type="submit" class="submit" id="projectSubmit" onclick="insertProjectData()" value="Save Project">
So as expected a simple thing in the end...

WordPress - Ajax success function giving empty response

I have this script:
<script type="text/javascript">
jQuery(document).on("click",".pending-post-approve-link",function(e){
jQuery('#review_post_status').val('approve');
var globalVar = jQuery(this).find('.review_post_id').val();
jQuery('#review_post_current_id').val(globalVar);
jQuery('#post-preloader-'+globalVar).fadeIn(500);
$.fn.wpjobusSubmitFormFunction();
});
$.fn.wpjobusSubmitFormFunction = function() {
var globalVar = jQuery('#review_post_current_id').val();
jQuery('#wpjobus-pending-posts').ajaxSubmit
({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: jQuery('#wpjobus-pending-posts').serialize(),
type: "POST",
success: function(response)
{
jQuery('#post-preloader-'+response).fadeOut(100);
jQuery('#post-'+response).fadeOut(100, function()
{
jQuery(this).css('display', 'none');
});
return false;
}
});
}
});
</script>
When this script runs, it gives me empty response. I don't know what causing this problem. This is happening in the success function of the ajax success: function(response).
Any help would be appreciated.
You might have done some of those steps, but myself I would take this approach to find the issues:
Use a tool such as Google Chrome console or Firebug for FF to check if your request is being sent to the expected url, and that it is getting an expected response.
If it is not getting the expected response, the issue is serverside and you should look there. You can also make some breakpoint using the same tools (console/firebug) to see if the parameters which you are passing look as expected (you can check the POST header details instead too).
Finally you can try placing a breakpoint on the success function to be sure that it gets executed at all and that the response is an empty string, and not something else.
I hope this helps.

What are the differece between these two forms of Ajax calls

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

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

How to set an input (text) value to a PHP variable on the fly

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!

Categories