how the page content will reload after ajax success - php

How to reload only the page content, not the whole page after jquery ajax success function for the given php and javascript code. In that initially it displays
success
and after ajax call it will display as
failed
with reloading the whole page..
Php code :
<?php
require 'dbconnect.php';
$sql="select * from tbl_status where id='1'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
if($row['status']=='1')
{
?>
Success <div class="status" style="visibility:hidden;">0</div>
<?php
}
else
{
?>
Failed
<div class="status" style="visibility:hidden;">1</div>
<?php
}
?>
<input type="submit" class="send"/>
Javascript code :
<script type="text/javascript">
$(function(){
$('.send').click(function(){
var status=$('.status').text();
$.ajax({
type: 'POST',
url: 'http://localhost/status/updatestatus.php',
data: 'status='+status,
success : function (e)
{
var response=e;
alert(response);
},
error: function()
{
alert('error');
}
});
});
});
</script>

Try.Sorry for if there are some issues as it was written in notepad.
index.php
<?php
require 'dbconnect.php';
$sql="select * from tbl_status where id='1'";
$res=mysql_query($sql);
$row=mysql_fetch_array($res);
<div id="response">
if($row['status']=='1')
{
?>
Success <div class="status" style="visibility:hidden;">0</div>
<?php
}
else
{
?>
Failed
<div class="status" style="visibility:hidden;">1</div>
<?php
}
?>
</div>
<input type="submit" class="send"/>
<script type="text/javascript">
$(document).ready(function(){
$('.send').click(function(){
var status=$('.status').text();
$.ajax({
type: 'POST',
url: 'http://localhost/status/updatestatus.php',
data: 'status='+status,
success : function (data, status)
{
$("#response").html(data.status);
},
error: function()
{
alert('error');
}
});
});
});
</script>
updatestatus.php
<?php
require 'dbconnect.php';
$sql="update tbl_status set status=$_POST['status'] where id='1'";
$res=mysql_query($sql);
$count = mysql_affected_rows();
if($count > 0){
return json_encode(array('status'=>$count));
}else{
return json_encode(array('status'=>0));
}
?>

If you are having problem with reloading the page then you can use
window.location.href=window.location.href;
Hope this helps

use load instead reload in your success
...
success : function (e)
{
$('your id or class name').load(php_file_name +'your_id_or_class_to_refresh');
var response=e;
alert(response);
location.reload();
},
....
// location.reload(); // <-- does not work so

considering your ajax is working fine... and the response you are getting is HTML
you don't need to call location.reload()..
you just need to append the response to the DOMtree..
updated
HTML
....
?> //close php tag
<div id="displayStatus"> //create new div with id displayStatus
<?php
if($row['status']=='1')
{
?>
Success <div class="status" style="visibility:hidden;">0</div>
<?php
}
else{
?>
Failed <div class="status" style="visibility:hidden;">1</div>
<?php
}
?>
</div> //end the div
JQUERY
success : function (e)
{
var response=e;
alert(response);
$('#displayStatus').html(response); //replace the content in that
},
updatestatus.php
$status= $_POST['status'];
//make you query ..update your table
if($status == '0'){
echo 'Failed <div class="status" style="visibility:hidden;">1</div>';
}else{
echo 'Success <div class="status" style="visibility:hidden;">0</div>';
}

The problem is: your jQuery part and your PHP part are not compatible.
You didn't really change your return status, just text. To signal "Failed" use some header on PHP side. For example:
in PHP:
header('HTTP/1.0 403 Forbidden');
die('Failed');
Then you ajax will raise an "error" handler instead of "success".
OR you should use only "success" handler and test returned text in in:
in JavaScript:
success: function(data) {
if (data == 'Failed') {
alert('ERROR');
location.reload();
} else {
alert('Success');
}
},

I have used this code to change the status and show the changed value on the page. This is a Javascript function that uses an Ajax request to PHP that changes the value of status in the database.
function changeStatus(divID,id,action,frontOrAdmin)
{
xmlhttp=getobject();
var query="id="+id+"&action="+action+"&frontOrAdmin="+frontOrAdmin;
$oldStatus = document.getElementById(divID).innerHTML;
document.getElementById(divID).innerHTML='<img src="images/loading_icon.gif">';
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4)
{
var response = xmlhttp.responseText;
var responseArr = response.split(",");
if(($.trim(responseArr[1])=="0")||($.trim(responseArr[1])=="1")){
document.getElementById(divID).innerHTML=responseArr[0];
}
else{
alert(responseArr[0]);
document.getElementById(divID).innerHTML=$oldStatus;
}
}
}
xmlhttp.open("GET","pass.php?type=changestatus&"+query,true);
xmlhttp.send(null);
}

Related

jQuery AJAX POST to current page with attribute

This is an example of my own page.
<?php
$do = $_GET['do'];
switch($do){
case 'finalTask':
if(isset($_POST['url'])){
echo "It's Ok!";
}else{
echo "Problem!";
}
}
This is also written in the same page.
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script>
$(document).ready(function(e){
$('#send').click(function(){
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url:"index.php?do=finalTask",
cache:false,
data:dataStr,
type:"POST",
success:function(data){
$('#info').html(data);
}
});
});
});
</script>
When I try to input and press the send button. Nothing happened..... What's wrong with the code?
Make sure file name is index.php
You need to make sure that you check in the php code when to output the form and when the
Format of ajax post request is incorrect in your case.
You forgot to import JQuery JS script, without that you can not use JQuery. (at least at this point of time)
-
<?php
if (!isset($_GET['do'])) { // Make sure that you don't get the form twice after submitting the data
?>
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#send').click(function () {
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url: "index.php?do=finalTask",
cache: false,
data: {url: dataStr}, // you need to send as name:value format.
type: "POST",
success: function (data) {
$('#info').html(data);
}
});
});
});
</script>
<?php
} else {
error_reporting(E_ERROR); // Disable warning and enable only error reports.
$do = $_GET['do'];
switch ($do) {
case 'finalTask':
if (isset($_POST['url'])) {
echo "It's Ok!";
} else {
echo "Problem!";
}
}
}
?>
There seems to be no form in your page, just form elements. Can you wrap them in a form:
<form method="POST" onSubmit="return false;">
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
</form>

Execute window.location redirect AFTER ajax is complete

In summary, I have a form that is loaded via AJAX. Required fields for this form are checked via another AJAX call. Once all required fields have been filled, a new record is added to db and the user should NOW be sent to my payment page to complete the application process. I have tried adding window.location = "http://www.paymentPage.php"; but no matter where I place this code, it is executing along with my ajax code. I even tried adding a die(header:location('paymentPage.php')); at the end of my code in validMA.php. I know I'm missing something simple...just can't figure it out.
PHP code:
<?php
session_start();
include('header.htm');?>
</head>
<body>
<div id="container">
<div id="content"><div class="content">
<h1>New Member Application</h1>
<form method="post" name="checkUserMA" id="checkUserMA">
<label class="clear" style="width:120px">Username/Email<br><span class="small"></span></label>
<input type="text" name="usernameMA" id="usernameMA" class="green" style="width:300px;"/><br><br>
<input type="submit" id="checkUserMA" class="submit" value="Submit" />
</form>
<div id="errorMA"></div>
<div id="resultMA"></div>
</div></div><!--end content-->
<div id="footer">
<?php include("footer.htm") ?>
<!--<?php include("disclaimer.htm") ?>-->
</div><!--end footer-->
<div class="clear"></div>
</div><!--end container-->
<div class="clear"></div>
</body>
</html>
JS code:
$(document).ready(function() {
//NEW MEMBER APPLICATION
$('#resultMA').hide();
$('#errorMA').hide();
$("#checkUserMA").submit(function(event){
event.preventDefault();
$("#resultMA").html('');
var values = $(this).serialize();
$.ajax({
url: "checkMA.php",
type: "post",
data: values,
success: function(result){
$("#resultMA").html(result).fadeIn();
$('.error').hide();
validMA();
window.location = "http://184.154.174.162/~nsgpcom/memberAppPay.php";
},
error:function(){
$("#resultMA").html('There was an error.').fadeIn();
}
});//end ajax
});
function validMA(){
$("#fullFormMA").click(function(e){
e.preventDefault();
$("#errorMA").html('');
var fullForm = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: fullForm,
success: function(result){
$("#errorMA").html(result).fadeIn();
},
error:function(){
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end
});
$("errorMA").hide();
}//end function
validMA.php code:
<?php
session_start();
include('functions.php');
connect();
$firstName = protect($_POST['firstName']);
$lastName = protect($_POST['lastName']);
$address1 = protect($_POST['address1']);
$address2 = protect($_POST['address2']);
$city = protect($_POST['city']);
$state = protect(strtoupper($_POST['state']));
$zip = protect($_POST['zip']);
$required = array('firstName','lastName','address1','city','state','zip');
// Loop over field names, make sure each one exists and is not empty
$error = false;
foreach($required as $field) {
if (empty($_POST[$field])) {
$error = true;
}
}
if ($error){
echo "You need to fill in all required (*) fields";
} else {
$sql2 = "INSERT INTO newMembers (username,firstName,lastName,address1,address2,city,state,zip,publicEmail,workPhone,privateAddress1,privateAddress2,privateCity,privateState,privateZip,homePhone,cellPhone,website,facebook,twitter,linkedIn,education,licensure,certification,statement,dateAdded) VALUES ('$username','$firstName','$lastName','$address1','$address2','$city','$state','$zip','$publicEmail','$workPhone','$privateAddress1','$privateAddress2','$privateCity','$privateState','$privateZip','$homePhone','$cellPhone','$website','$facebook','$twitter','$linkedIn','$education','$licensure','$certification','$statement','$dateAdded')";
$result2 = mysql_query($sql2) or die(mysql_error());
}?>
Hoping to understand this logic. I know I will use it again and again.
Your window.location = ... should be inside the validMA function
function validMA(){
$("#fullFormMA").click(function(e){
e.preventDefault();
$("#errorMA").html('');
var fullForm = $(this).serialize();
$.ajax({
url: "validMA.php",
type: "post",
data: fullForm,
success: function(result){
$("#errorMA").html(result).fadeIn();
/* ====
* HERE YOU PLACE IT
* ====
*/
window.location = "http://184.154.174.162/~nsgpcom/memberAppPay.php";
},
error:function(){
$("#errorMA").html('There was an error. Please try again.').fadeIn();
}
});//end
});
$("errorMA").hide();
}//end function
You have
validMA();
window.location = "http://184.154.174.162/~nsgpcom/memberAppPay.php";
But I window.location goes inside that validMA();
success: function(result){
$("#errorMA").html(result).fadeIn();
window.location = "http://184.154.174.162/~nsgpcom/memberAppPay.php";
},
In here!
My problems using the suggestions above were that the user was redirected to the payment page before all validation was complete...actually upon the first form submission. I added the following code at the bottom of my validMA.php code (within the success portion of my if/else loop).
if ($error){
echo "You need to fill in all required (*) fields";
} else {
$sql2 = "INSERT INTO newMembers (username,firstName,lastName,address1,address2,city,state.....)";
$result2 = mysql_query($sql2) or die(mysql_error());?>
<script type="text/javascript">
alert('You completed step 1');
window.location.href = "http://www.paymentPage.php";
</script>
<?php
}?>
I feel it is not as elegant as it could be, but it does work. Thanks for everyone's suggestions.
Use
window.location.href="your URL"
instead of
window.location

Delete record using jquery ajax but table is loaded again

I am deleting records using jQuery and Ajax. The code I wrote deletes a record but the HTML table is loaded again, which means the page refreshes which I want to avoid.
Here is my code:
comment.php
<script type="text/javascript">
$(document).ready(function(){
function loadList(){
$.ajax({
url: "load_list.php",
cache: false,
success : function(html){
$(".name_list").html(html);
}
});
}
loadList();
$("#Submit").click(function() {
if($(":text").val().length==0)
{
// $(this).next().html("Field needs filling");
$(":text").after('<span class="errorkeyup">Field cannot be empty</span>');
//return false;
success = false;
}
else
{
var name=$("#name").val();
var message=$("#message").val();
$.ajax({
type:"post",
url:"save_list.php",
data:"name="+name+"&message="+message,
success:function(data){
loadList();
}
});
return false;
}
});
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var id = $(this).attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(){
loadList();
}
});
// }
return false;
});
});
</script>
</head>
<body>
<div id="form">
<form method="post" name="form" action="">
<div id="content">
Name : <input type="text" name="name" id="name" />
</br>
Message : <input type="text" name="message" id="message" />
</br>
</div>
<input type="button" value="Submit" id="Submit">
</form>
</div>
<div class="name_list"></div>
</body>
loadlist.php
<?php
include('connection.php');
$sqlnew = 'Select * from login order by id ASC';
$res = mysql_query($sqlnew);
echo'<table border="1">';
echo'<tr>';
echo'<td>SrNo.</td>';
echo '<td>Name:</td>';
echo '<td>Message:</td>';
echo '<td>Delete</td>';
echo'</tr>';
$i=1;
while($row = mysql_fetch_array($res))
{
echo '<tr>';
echo'<td>'.$i.'</td>';
echo'<td>'.$row['username'].'</td>';
echo '<td>'.$row['message'].'</td>';
echo"<td>
<a id='".$row['id']."' href=delete.php?id=".$row['id']."&type=Delete class=delete_button>Delete</a></td>";
echo"<td>
<a id='".$row['id']."' href=comment.php?id=".$row['id']."&type=edit class=edit_button>Edit</a></td>";
echo '</tr>';
$i++;
}
echo'</table>';
?>
delete.php
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
When you do the $.ajax() call for $('.delete_button'), you shouldn't call your loadList() function there because that is what reloads the table, instead you should just remove the one entry that's deleted from the table.
Perhaps you can remove it with something similar to this, placed inside the delete button success callback:
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function()
{
$(this).parent().parent().remove();
}
});
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
header("location: comment.php");
}
?>
in this code remove line
header("location: comment.php");
Final code would be,
<?php
include('connection.php');
if(isset($_REQUEST["id"]))
{
$cmd=mysql_query("delete from login where id=" .$_REQUEST["id"] .";");
echo '1';
} else {
echo '0';
}
exit;
?>
In delete function, after executing delete query, you need to echo '1' or '0'. Lets say echo '1'; when deleted successfully and echo '0' when delete not succeed. So based on 1 or 0 you can remove those deleted row from table by ,
$(".delete_button").on("click", function(){
//this deletes the row clicked on with an alert and then reloads the list
var obj = $(this);
var id = obj.attr("id");
/*var x=window.confirm("Are you sure you want to delete this item?")
if (x==true){*/
$.ajax({
type: "POST",
url: "delete.php",
data: "id="+ id,
success: function(response){
if(response == '1') {
obj.parent.remove();
}
}
});
// }
return false;
});

jQuery AJAX POST to PHP file to UPDATE database not updating

I'm trying to build a small CMS system, I want to use AJAX and jQuery to do so.
If I do not use AJAX the code works, I have no idea why the data is not being passed properly. AJAX success returns "Success"
Any help is appreciated.
Here is my Javascript:
$(document).ready(function(){
var aboutContent = $('#aboutContent').attr('value');
$('#aboutUpdate').submit(function() {
$.ajax({
type: "POST",
url: "scripts/update.php",
data: "aboutUpdate="+aboutContent,
beforeSend: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('processing...'); },
success: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('Saved Successfully!').delay(500).fadeOut(250); },
error: function(){ $('#aboutStatus').fadeIn(250).css('color', '#ff464a').html('An error occurred!').delay(500).fadeOut(250); }
});
return false;
});
});
Here is my HTML:
<?
$query = "SELECT * FROM pageContent WHERE page = 'about'";
$result = mysql_query($query);
while($rows = mysql_fetch_array($result)){
?>
<div class="pageContent">
<h2>About</h2>
<form id="aboutUpdate" method="post">
<textarea class="editor" id="aboutContent" cols="50" rows="20"><? echo $rows['content']; ?></textarea>
<input type="submit" value="Save Now"><span class="updateStatus" id="aboutStatus"></span>
</form>
</div>
<?
}
?>
Here is the PHP (scripts/update.php):
$aboutContent = mysql_real_escape_string($_POST['aboutUpdate']);
if(isset($_POST['aboutUpdate'])){
$query="UPDATE pageContent SET content='$aboutContent' WHERE page='about'";
$result=mysql_query($query)or die(mysql_error());
if($result){
echo "Success";
}
else{
echo "Update Error";
}
}
else{
header("location:http://google.com");
}
Fixed the issue. Here is how:
First on the TEXTAREA I need to specify the attribute
name="aboutUpdate"
so the PHP isset can pull the data.
Second, I noticed a variable was 'undefined' when submitting.
var aboutContent = $('#aboutContent').attr('value');
Here is the working Javascript:
$('#aboutUpdate').submit(function() {
$.ajax({
type: "POST",
url: "scripts/update.php",
data: { aboutUpdate: $('#aboutContent').attr('value') },
beforeSend: function(){
$('#aboutStatus').fadeIn(250).css('color', '#017c04').html('processing...');
},
success: function(){
$('#aboutStatus').fadeIn(250).css('color', '#017c04').html('Saved Successfully!').delay(2500).fadeOut(250);
},
error: function(){
$('#aboutStatus').fadeIn(250).css('color', '#ff464a').html('An error occurred!').delay(2500).fadeOut(250);
}
});
return false;
});
HTML:
<?
$query = "SELECT * FROM pageContent WHERE page = 'about'";
$result = mysql_query($query);
while($rows = mysql_fetch_array($result)){
?>
<div class="pageContent">
<h2>About</h2>
<form id="aboutUpdate" method="post">
<textarea class="editor" id="aboutContent" name="aboutUpdate" cols="50" rows="20"><? echo $rows['content']; ?></textarea>
<input type="submit" value="Save Now"><span class="updateStatus" id="aboutStatus"></span>
</form>
</div>
<?
}
?>
PHP update.php:
$aboutContent = mysql_real_escape_string($_POST['aboutUpdate']);
if(isset($_POST['aboutUpdate'])){
$query="UPDATE pageContent SET content='".$aboutContent."' WHERE page='about'";
$result=mysql_query($query)or die(mysql_error());
if($result){
echo "Success";
}
else{
echo "Update Error";
}
}
Try your Ajax function like this:
$.ajax({
type: "POST",
url: "scripts/update.php",
data: { aboutUpdate: aboutContent },
beforeSend: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('processing...'); },
success: function(){ $('#aboutStatus').fadeIn(250).css('color', '#017c04').html('Saved Successfully!').delay(500).fadeOut(250); },
error: function(){ $('#aboutStatus').fadeIn(250).css('color', '#ff464a').html('An error occurred!').delay(500).fadeOut(250); }
});
Notice the change in the POST data line.
Absolutely sure, that with this data: "aboutUpdate="+aboutContent you are sending something totaly wrong.
It should be data: {aboutUpdate: aboutContent}
Plus I'm not sure, that textarea actually has attribute value. Try
$('#aboutContent').val()
or
$('#aboutContent').text()

Submit form (jquery) and show results in colorbox

I have a form that I wish to submit which is posting to a php script to deal with the form data.
What I need to do is after hitting submit have a colorbox popup with the php results in it.
Can this be done?
This is what i've been trying:
$("#buildForm").click(function () { // #buildForm is button ID
var data = $('#test-buildForm'); // #test-buildForm is form ID
$("#buildForm").colorbox({
href:"build_action.php",
iframe:true,
innerWidth:640,
innerHeight:360,
data: data
});
return false;
});
UPDATE: This would need to be returned in an iframe as the
build_action.php has specific included css and js for those results.
This is simple, untested code but it'll give you a good jumping off point so you can elaborate however much you please:
<form action="/path/to/script.php" id="formID" method="post">
<!-- form stuff goes here -->
<input type="submit" name="do" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({html:data});
},
'html');
return false;
});
});
</script>
this article will help you with the problem
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
You will need to see the exact way to use your colorbox jQuery plugin. But here is a basic (untested) code example that I've just written to hopefully get you on your way.
If you wish to submit a form using jQuery, assuming you have the following form and div to hold dialog data:
<form id="myForm">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit" name="formSubmit" />
</form>
<div style="display: hidden" id="dialogData"></div>
You can have a PHP code (doAddition.php), which might do the addition of the two numbers
<?php
// Do the addition
$addition = $_POST['num1'] + $_POST['num2'];
$result = array("result" => $addition);
// Output as json
echo json_encode($result);
?>
You can use jQuery to detect the submitting of the code, then send the data to the PHP page and get the result back as JSON:
$('form#myForm').submit( function() {
// Form has been submitted, send data from form and get result
// Get data from form
var formData = $('form#myForm').serialize();
$.getJSON( 'doAddition.php', formData, function(resultJSON) {
// Put the result inside the dialog case
$("#dialogData").html(resultJSON.result);
// Show the dialog
$("#dialogData").dialog();
});
});
This is how I ended up getting it to work:
<div id="formwrapper">
<form method="post" action="http://wherever" target="response">
# form stuff
</form>
<iframe id="response" name="response" style="display: none;"></iframe>
</div>
<script>
function hideresponseiframe() {
$('#formwrapper #response').hide();
}
$('form').submit(
function (event) {
$('#formwrapper #response').show();
$.colorbox(
{
inline: true,
href: "#response",
open: true,
onComplete: function() {
hideresponseiframe()
},
onClosed: function() {
hideresponseiframe()
}
}
);
return true;
}
);
</script>

Categories