Am i getting html and javascript code when using ajax to pass parameters to the function on onClick event (Ajaxing on the same page) - javascript

<html>
tables, textbox, buttons
</html>
<?php
//some php, sql stuff
echo "<td><input type='button' name='disable' value='Disable' onClick='disable($id);'/></td>";
if(isset($_POST['action']) && $_POST['action']=="delete")
{
if(isset($_POST['ID']) && !empty($_POST['ID']))
{
$id = $_POST['ID'];
echo "Id:".$id;
//Call to another function
die();
}
?>
<script>
function disable(id) {
jQuery.ajax({ type: 'Post',
url: '',
data: {action: 'delete', ID: id}
})
.done(function(data) {
alert("Data Saved: " + data);
location.reload();
});
}
</script>
Alert box is showing html code which is in HTML block and successful messages from php block. I don't need to show HTML code, only need to show successful messages. How to do that??? many thanks

The issue is that you need to respond to the ajax request before any html is sent to the browser and call exit; to stop the remaining page content from being sent as well. Something like this would work:
<?php
if(isset($_POST['action']) && $_POST['action']=='delete'){
// process request......
$id = $_POST['ID'];
echo "Id:".$id;
//Call to another function
exit; // stop the script here so it doesnt also return the html content of the page
}
?>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
tables, textbox, buttons
<?php
//some php, sql stuff
// note that $id is not defined where you try to use it here in your code, not sure what that's about....
echo "<td><input type='button' name='disable' value='Disable' onClick='disable($id);'/></td>";
?>
<script>
function disable(id) {
jQuery.ajax({ type: 'Post',
url: '',
data: {action: 'delete', ID: id}
})
.done(function(data) {
alert("Data Saved: " + data);
location.reload();
});
}
</script>
</body>
</html>

Related

Ajax submit returning Error but updating the database fine

<script>
function addprescription() {
var Case_Histroy=$('#Case_Histroy').val();
var Medication=$('#Medication').val();
var Note=$('#Note').val();
var pname="<?php echo($patient->getUsername()); ?>";
var dname="<?php echo($doctor->getUsername()); ?>";
var id="<?php echo($id); ?>";
frmData={Case_Histroy:Case_Histroy,Medication:Medication,Note:Note,pname:pname,dname:dname,id:id}
console.log( frmData);
$.ajax({
type: "POST",
url: "loadfiles/AddAppointmentSubmit.php",
data: frmData,
success: function (msg) {
alert(msg);
$("#alert").html(msg)
}
,
error : function () {
alert("failure");
}
});
}
</script>
I have a function to submit the form. But ajax function alerts its as failure. But data base seems to be updated. when I click the button. I couldn't find the reason for the cause in the console.
this is the php file
<?php
echo "I'm in";
include "../../Adaptor/mysql_crud.php";
include ("Prescription.php");
$prescription=new Prescription();
if(isset($_POST)){
$Note=htmlspecialchars($_POST['Note']);
$Case_Histroy=htmlspecialchars($_POST['Case_Histroy']);
$medication = htmlspecialchars($_POST['Medication']);
$pname=$_POST['pname'];
$danme=$_POST['dname'];
$id=$_POST['id'];
$prescription->insert($pname,$danme,$Case_Histroy,$medication,$Note,$id);
?>
<div class="alert alert-success" id="alert"><strong><?php echo "Submitted succesfully"; ?></strong></div>
<?php
}
?>
Try adding an else statement to your if:
insert($pname,$danme,$Case_Histroy,$medication,$Note,$id);
?>
}
?>
Also, it's not necessary to stick the php in the middle of the <div> you can just use echo at the beginning since you're not introducing any variables to it:
echo '<div class="alert alert-success" id="alert"><strong>Submitted successfully</strong></div>';
Finally I got the answer for the Problem! Actual problem is button that fired up the AJAX request also reloaded the page interrupting AJAX inner workings. So the error message will be alerted.
I tried this code.
<script>
$(function() {
$("#button_Add_p").click(function(e){
e.preventDefault();
var Case_Histroy=$('#Case_Histroy').val();
var Medication=$('#Medication').val();
var Note=$('#Note').val();
var pname="<?php echo($patient->getUsername()); ?>";
var dname="<?php echo($doctor->getUsername()); ?>";
var id="<?php echo($id); ?>";
frmData={Case_Histroy:Case_Histroy,Medication:Medication,Note:Note,pname:pname,dname:dname,id:id}
console.log( frmData);
$.ajax({
type: "POST",
dataType: 'html',
url: "loadfiles/AddAppointmentSubmit.php",
data: frmData,
success: function (msg) {
alert(msg);
$("#alert").html(msg)
}
,
error : function () {
alert("failure");
}
});
});
});
</script>

Ajax and jQuery with PHP

I have this code which posts data using jQuery and ajax to itself.
<input type="button" id="butt" value="button11111111111111" >
<script>
$("#butt").on('click',function(e)
{
$.ajax(
{
type:'POST',
url:'test.php',
data:product_type:"cake"
});
});
</script>
<?php
if(isset($_POST['product_type']))
$abc=$_POST['product_type'];
if(isset($abc))
echo $abc;
?>
Now when I try to run this code.I do get the ok status inside the Network Console of Chrome but this code doesn't echo the output.
I simply want to display the result that has been passed by the ajax method.
I am new to ajax and jquery so i don't know much about how they work exactly but is it possible?
If yes, then how could i achieve that without actually refreshing the page?
Here is what I think you want, i.e. test.php is the source page AND the ajax page!
<?php
if(isset($_POST['product_type'])) {
Header("Content-type: text/plain; charset=utf-8");
$abc=$_POST['product_type'];
if(isset($abc)) {
echo $abc;
}
}
else {
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"> </script>
<input type="button" id="butt" value="button11111111111111" >
<script>
$("#butt").on('click',function(e) {
$.ajax({
type:'POST',
url:'test.php',
data: {
product_type:"cake"
},
success: function(data) {
alert('got ' + data);
}
});
});
</script>
</html>
<?php
}
?>

on page login with jquery

I want to create on-page login system.
Without javascript I can login perfectly in this structure:
<?php
require_once('login.php');
$login = new Login();
// if we are logged in here:
if ($login->isUserLoggedIn() == true) {
// yes we are
echo "<div id=\"login\">you logged in as $_SESSION[user_name]. Logout</div>";
} else {
// no
echo "
<div id=\"login\" style=\"display: none;\">
<form action=\"index_.php\" method=\"post\" name=\"loginform\" id=\"loginform\" onsubmit=\"return false;\">
<input type=\"text\" class=\"form-control\" id=\"user_name\" name=\"user_name\><br>
<input type=\"password\" class=\"form-control\" id=\"user_password\" name=\"user_password\"><br>
<label class=\"checkbox-label\" style=\"pointer-events: all;\" for=\"user_rememberme\"><input checked class=\"user_rememberme\" name=\"user_rememberme\" id=\"user_rememberme\" value=\"1\" type=\"checkbox\"/>
Remember me</label>
Forgot Password?
<input class=\"btn btn-success\" type=\"submit\" name=\"login\" id=\"loginbutton\" value=\"Login\">
</form>
</div><!-- login ends -->
";
}
?>
Currently on working system, I'm sending form to current page. And code below telling user the result: (for instance. you logged in, please activate your account, login failed.)
<?php
// I send the form same page upside.
// and if i login or not, codes below lets me know.
if (isset($login)) {
if ($login->errors) {
foreach ($login->errors as $error) {
echo "<div id=\"message\">$error</div>";
}
}
if ($login->messages) {
foreach ($login->messages as $message) {
echo "<div id=\"message\">$message</div>";
}
}
}
?>
As a next step, I want to login on-page with the help of ajax. So Here is my javascript code to start with:
<script type="text/javascript">
// login on page
$(function(){
$("#loginform").submit(function(){ // .click yerine .submit
if($("#loginform").valid()){
$.ajax({
type: "POST",
url: "index_.php",
data: $("#loginform").serialize(),
beforeSend: function(){
$('#message').html('Loading...');
},
success: function(data){
$('#message').html(data);
}
});
}
});
});
</script>
Specifically this part of javascript code
success: function(data){
$('#message').html(data);
I want to output my php result, but copying php inside of data obviously doesn't work.
What should I do?
You can add an extra POST-Field (for example "AJAX")
and return other output, if this is set
$.ajax({
type: "POST",
url: "index_.php",
data: $("#loginform").serialize() + "&ajax=1",

JS ProgressBar update from inside PHP While Loop called by AJAX?

I have a PHP page with a form. Once the form is submitted, it calls another PHP page via AJAX to make calls to MySQL, then process the results, and return them to the first PHP page. The MySQL processing takes place inside a while loop. I wanted to update a progress bar that indicates the progress of the loop. But I get:
parsererror
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
and nothing happens. Any ideas if what I am doing below is wrong? How Can I update a progress bar from an AJAX called while loop?
The following is a rough code:
Main PHP page:
<html>
<head>
<link rel="stylesheet" type="text/css" href="jquery-ui.css">
<script type='text/javascript' src='jquery-1.11.1.min.js'></script>
<script type='text/javascript' src='jquery-ui-1.10.4.min.js'></script>
<script type='text/javascript' src='my.js'></script>
</head>
<body onLoad="onLoad()">
<form action="" method="POST" id="myForm" name="myForm">
<div id="progressBar"></div>
<input class="txt"
id="btnSubmit"
style="margin-top: 12pt; font-family: arial; color: grey; font-weight: bold; font-size: 15pt;"
type="submit"
name="action"
value="SEARCH" />
</form>
</body>
</html>
The my.js has:
function onLoad() {
$('#progressBar').progressbar({ disabled: true });
$('#progressBar').hide();
}
$(document).ready(function() {
$("#myForm").submit(function(event) {
$(function () {
.ajax({
url: 'myCall.php', // the script to call to get data
type: "POST",
data: { data: 'something'}
},
dataType: 'json',
success: function(data) {
// do something
},
error: function (jqXHR, textStatus, errorThrown){
console.log(textStatus, errorThrown);
},
});
});
});
and myCall.php has some calls to MySQL database, then post processing:
$result = mysqli_query($mysqli, $sql);
$j = 1;
// enable and show the bar
echo '<script language="javascript"></script>';
echo '$("#progressBar").show();';
echo '$("#progressBar").progressbar({';
echo 'disabled: false,';
echo 'value: '.$j.',';
echo 'max: '.$result->num_rows.',';
echo '});';
echo '</script>';
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
// doing stuff and then update the bar
// update
echo '<script language="javascript"></script>';
echo '$("#progressBar").progressbar({';
echo 'value: '.$j.',';
echo '});';
echo '</script>';
}
// disable and hide the bar
echo '<script language="javascript"></script>';
echo '$("#progressBar").progressbar({';
echo 'disabled: true,';
echo '});';
echo '$("#progressBar").hide();';
echo '</script>';
It looks like the JSON you are parsing is not valid JSON. I would print out the JSON you are trying to run through the parser and run it through a JSON validator such as http://jsonformatter.curiousconcept.com/.
Also, the following code looks unclean to me, which might cause the problem. I'm not sure if you are using a more standardized JSON parser. If so, it would probably not expect a data object inside a data object. This is a complete guess, but you should probably change
.ajax({
url: 'myCall.php', // the script to call to get data
type: "POST",
data: { data: 'something'}
},
to
.ajax({
url: 'myCall.php', // the script to call to get data
type: "POST",
data: { "key1" : "value1"}
},
I don't think you are actually showing where the JSON is being parsed in your question. Are you able to show exactly how you parse it and what you are parsing?
Thanks!

AJAX form submission with php and jquery

I have looked at everything on here that I can find and I just can't figure out why I cannot perfect this code. What I am trying to do is allow users to delete something that they posted on my site without doing a page refresh. The form is going to be passed to a php file that will modify my MySQL DB. I am new to ajax and have only messed around with PHP for a short time as well.
form:
<form class='status_feedback' id='delete_status' onsubmit='delete_status()' action=''>
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='submit' value='X'/>
</form>
delete_status()
function delete_status(){
$.ajax({
type: "POST",
url: "/scripts/home/php/delete_status.php/",
data: status_id,
success: function() {
//display message back to user here
}
});
return false;
}
delete_status.php
<?php
$con=mysqli_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$status_id = $_POST['status_id'];
mysqli_query($con,"UPDATE status SET visibility = 'hidden' WHERE id = $status_id");
?>
at this point, all that happens when I strike the delete_status() function is my page refreshes and adds ?status_id=194 (when I click on status #194) to the end or my url.
Any help would be awesome. I have been researching for several days.
Change your HTML, Ajax and php a little.
HTML
Add this code:
<body>
<form class='status_feedback' id='delete_status' >
<input type='hidden' name='status_id' id='status_id' value='$status_id'/>
<input type='button' id='x_submit' value='X' />
</form>
<script>
$('#x_submit').on("click",function(){
var status_id= $('#status_id').val();
//Delete the alert message if you want.
alert("Check your status id :"+status_id);
$.ajax({
type: "GET",
url: "/scripts/home/php/delete_status.php?",
data: {status_id:status_id},
dataType:'JSON',
success: function(json) {
//display message back to user here
alert(json[0].response);
}
});
});
</script>
PHP:
<?php
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Methods: GET, POST');
header('Content-type: application/json');
$con=mysql_connect("localhost","USER","PASSWORD","DB");
// Check connection
if (mysql_connect_errno())
{
echo "Failed to connect to MySQL: " . mysql_connect_error();
}
$status_id = $_GET['status_id'];
$result = mysql_query("UPDATE status SET visibility = 'hidden'
WHERE id = '$status_id'");
if(! $result )
{
$data[]=array('response'=>"Unable to insert!");
}
else
{
$data[]=array('response'=>"Data successfully inserted into the database!");
}
$json_encode = json_encode($data);
print("$json_encode");
?>
Hope it will work.
You are not cancelling the form submission
onsubmit='delete_status()'
needs to be
onsubmit='return delete_status()'
and data: status_id, looks wrong unless you have a variable defined somewhere else

Categories

Resources