Ajax and jQuery with PHP - javascript

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
}
?>

Related

How to put the ajax response/result into variable php

Can I put the ajax response into variable? So that I can echo the variable into php?
ajax.php
<script>
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
$("#random_no_container").html(result);//the result was displayed on this div
}
});
}
</script>
On my sample code above, i call the query result from test.php and the result was displayed on the div but i want to put that on the variable and echo the variable. something like the code below
<?php echo $variable;?>
Can this possible? please help me. Thank you so much.
You can't PHP is executed on server and Ajax from the client so you cannot assign PHP variable an ajax response.
Once a PHP is rendered on the client side it is just HTML no PHP code.
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
var result_val=result;
alert(result);
}
});
}
As #dev answered , you need to execute server and client code differently ! I answered here for your need variable only .But in developing website, should not use javascript in php tag <?php ?>
ajax.php
<div id="random_no_container">
<?php
if(isset($_GET['variable'])) {
$variable = $_GET['variable'];
echo $variable;
} else {
echo "<script>sessionStorage.setItem('stopped',0);</script>";
}
?>
</div>
<script>
var stopped = sessionStorage.getItem("stopped");
if(stopped == 0) {
random_no();
}
function random_no(){
$.ajax({
url: "test.php",
success: function(result){
sessionStorage.setItem("stopped",1);
//$("#random_no_container").html(result);//the result was displayed on this div
location.href = "ajax.php?variable="+result;
}
});
}
</script>

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

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

Posting html form data to php and accessing that through javascript

I'm trying to post some data to an html form, then that form sends the data to php, and finally javascript takes the data from that php.
This is my html form:
<form action="search.php" method='POST'>
<input id="movie_name" name="movie_name" type="text">
<input name="myBtn" type="submit" value="Submit Data">
</form>
This is my php file which is called search.php:
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo '<script>', 'hello();', 'var movie = '$movie_name';', '</script>';
}
?>
Finally my js script which is in the same file as the php one:
function hello(){
console.log('<?php echo $movie_name?;>');
}
What happens when I load this is that my html redirects ok and then for some in search.php nothing happens, the page goes white and the only thing the console says is "Resource interpreted as Script but transferred with MIME type text/html..."
What exactly you want is not clear. But i suggest you to use jQuery ajax like this:
<input id="movie_name" name="movie_name" type="text">
<input id="myBtn" name="myBtn" type="button" value="Submit Data">
$('#myBtn').click(function(e){
var movie_name = $('#movie_name').val();
$.ajax({
url: "search.php",
type: "POST",
data: {
'movie_name': movie_name
},
beforeSend : function() {
},
success : function(response) {
console.log(response);
},
error : function()
{
},
complete : function() {
}
});
});
in your search.php
<?php
if (isset($_POST['movie_name']))
{
$movie_name = $_POST['movie_name'];
echo $movie_name;
}
?>
This is better way from my point of view.
This should work:
<?php
if (isset($_POST['movie_name'])){
$movie_name = $_POST['movie_name'];
}
?>
<script type="text/javascript">
function hello(){
console.log('<?php echo $movie_name; ?>');
}
</script>
<?php
echo '<script> alert("'.$movie_name.'"); hello(); </script>';
?>

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!

jQuery Ajax is not getting posted to a PHP file

I am new to AJAX so I know there could be a silly mistake in my code but anyways I will go ahead.
I have a function created that is called when a button is clicked. The function calls .ajax() method of jquery. I send the data to a file named 'delete_post.php`.
HTML:
<button class="btn btn-primary" onclick="deletePost(<?php echo $_GET["id"]; ?>);">Yes</button>
The above code works.
JS:
function deletePost(postid) {
$.ajax({
type: 'post',
url: "delete_post.php?id="+postid,
success: function(data) {
if(data.error == true) console.log('error');
else console.log('problem?');
}
});
}
The above code is calling the .ajax() function but is not logging 'problem?' into the console.
Here's the PHP file:
<?php
require_once '...';
if(isset($_GET["id"])) {
$id = $_GET["id"];
echo "YEAH!";
} else {
header("location: index.php");
}
?>
What's the issue and how can I fix it?
as we discussed in the chat side, you can use it like this:
JS:
function deletePost(postid) {
$.post('delete_post.php', {id : postid}, function(data){
console.log(data);
}, 'json');
}
PHP:
<?php
require_once '...';
if(isset($_POST["id"])) {
$data['res'] = 'yes';
echo json_encode($data);
} else {
header("location: index.php");
}
?>
There is an escape issue in the following part:
onclick="deletePost(<?php echo $_GET["id"]; ?>);"
It must be as below:
onclick="deletePost(<?php echo $_GET['id']; ?>);"
And, you are echoing 'YEAH!', so the if condition should be:
if(data == 'YEAH!')
Here is your working code, In your AJAX you are doing "POST" and in your PHP file your using "GET".
trigger.html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
function deletePost(postid) {
$.ajax({
type: 'GET',
url: "http://localhost/overflow/delete_post.php?id="+postid,
success: function(data) {
console.log('success:'+data);
}, error: function(xhr, status, error){
console.log(xhr.responseText);
}
});
}
</script>
</head>
<body>
<button class="btn btn-primary" onclick="deletePost(9); return false;">Yes</button>
</body>
</html>
delete_post.php
<?php
//require_once '...';
if(isset($_GET["id"])) {
$id = $_GET["id"];
echo "YEAH!";
//do something
} else {
// header("location: index.php");
echo "not set";
}
?>
Try this and let us know your problem in detailed and clear. good luck

Categories

Resources