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!
Related
I'm in a little trouble here. I'm trying to use ajax to get data from PHP server, that it gets from Mysql database; and then display into a specific html tag place. But, for some reason, nothing is showed off to html. I tested the PHP page and it works correctly. The point is, when ajax should get the data and display, it seems that there's nothing at database.
This is my html target :
<div class="container">
<table>
<thead>
<tr>
<th>TÃtulo</th>
<th>Curiosidade</th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
This is my Ajax Script:
function readData() {
$.ajax({
type: "POST",
dataType: "html",
url: 'http://localhost/Gravidapp/php/read.php',
success: function(data){
$('tbody').html(data);
},
error: function(xhr,desc,err){
ajax.error(xhr);
ajax.error(desc, err);
}
});
};
This is my PHP file:
<?php
require("bdconn.php");
$pdo = new db();
$pdo->mysql->beginTransaction();
$rs = $pdo->mysql->query("select * from timeline");
$rs->execute();
while($row = $rs->fetch()){
?>
<tr>
<td><?php echo $row['titulocuriosidade']?></td>
<td><?php echo $row['curiosidade']?></td>
</tr>
<?php
}
?>
Any suggests?
Thanks in advance
If the php response doesn't have the data type on headers ajax response could send an error.
Try setting dataType="text html" on your ajax request this will try to convert the response from text to html
also try to print errors on console to show whats is going wrong.
error: function(xhr,desc,err){
console.log(desc);
}
see dataType on: JQuery ajax
What's happening is: when you make an ajax call you must have a return of some data in the php called. When you need to include html you can call a method that return to you a template already ready to be included in the current html page. You can have for example an index.html that will be included when you load your page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div id="data-ajax"></div>
<script type="text/javascript" src="node_modules/jquery/dist/jquery.min.js"></script>
<script type="text/javascript" src="js/timeline.js"></script>
</body>
</html>
In you js timeline.js you will include in the current html page what has returned in the data of the ajax:
$.ajax({
type: "GET",
dataType: "html",
url: 'timeline.php',
success: function (data) {
$('#data-ajax').html(data);
}
});
You will have also your php returning the html to be used in the ajax:
<?php
getTimelineData();
function getTimelineData() {
//here you retrieve data from database
$results = array(0 => 'first-result', 2 => 'second-result', 3 => 'third-result');
include_once 'timeline-data.php';
}
And finally your timeline-data.php file:
Here is your data!
<?php foreach($results as $result) { ?>
<?= $result ?>
<?php } ?>
<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>
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
}
?>
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>';
?>
I'm trying to learn how does Ajax work and how I can send data by Ajax. I'm getting no error and nothing is being echoed.
index.html
<input id="name" type="text" /><input id="button" type="button" value="Load" />
<div id="feedback"></div>
<script type="text/javascript" src="../js/jquery.js"></script>
<script type="text/javascript" src="ajax.js"></script>
page.php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
}
?>
ajax.js
$('#button').click(function(){
var name = $('#name').val();
$.ajax({
url: 'page.php',
data: 'name='+name,
success: function(data){
$('#feedback').html(data);
}
});
});
I appreciate any help
You are missing an echo in your page php
<?php
if (isset($_GE['name'])) {
$name = $_GET['name'];
echo $name;
}
?>
also in your javascript send an object like this
data : { name : name}
should work
data : { name : 'John'}
you can check the success method is invoked or not invoked.
Also you need to echo something from php.
echo $name