I'm getting some data using php json, well the result bring me the html code too, so the page is giving me a unexpected token. Here my code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).on("ready", function(){
loadData();
});
var loadData = function(){
$.ajax({
type:"POST",
url:"Users.php"
}).done(function(data){
console.log(data);
var users = JSON.parse(data);
for(var i in users){
$("#content").append(users[i].nombre + " " + users[i].apellido + "<br>");
}
});
}
</script>
and this is what I see in the console
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
</head>
<body>
[{"nombre":"Joelbis","apellido":"Rosas"},{"nombre":"William","apellido":"Mazo"},{"nombre":"Mariana","apellido":"De Barros"},{"nombre":"Daniela","apellido":"Ramirez"}]
</body>
</html>
VM396:1 Uncaught SyntaxError: Unexpected token <(anonymous function) # userview.php:22l # jquery.min.js:4c.fireWith # jquery.min.js:4k # jquery.min.js:6(anonymous function) # jquery.min.js:6
How I avoid the html code in the result?
Thank you.
You need a php file that ONLY prints out the data you need returned. Like this:
Ajax Call
var loadData = function(){
$.ajax({
type:"POST",
url:"UserData.php"
}).done(function(data){
console.log(data);
var users = JSON.parse(data);
for(var i in users){
$("#content").append(users[i].nombre + " " + users[i].apellido + "<br>");
}
});
}
UserData.php
<?php
$sql = "SELECT nombre, apellido FROM pruebaUsuarios"; $result = mysqli_query($conexion, $sql);
$array_user = array(); while($data = mysqli_fetch_assoc($result)){ $array_user[] = $data; }
echo json_encode($array_user)
?>
Your backend script must stop right after echo json_encode($data), using die() or exit() which are the same. Otherwise it will feed the rest of your page to your AJAX frontend, which is what's currently happening.
var loadData = function(){
$.ajax({
type:"POST",
url:"Users.php"
}).done(function(data){
console.log(data);
data = $(data).find('body').html();
var users = JSON.parse(data);
for(var i in users){
$("#content").append(users[i].nombre + " " + users[i].apellido + "<br>");
}
});
}
Try to parse data from html
Related
Please help me.. I have the following codes..
//Get the value of Start and End of Week
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
});
now I want to pass the firstDate and the lastDate to a php. How should I do this. and how can I retrieve the passed value in the php. I'm not very familiar with javascripts. Hope anyone can help me. Thanks in advance.
Here is my full code..
JS tags
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.css" rel="stylesheet"
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.11.1/moment.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/bootstrap.datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>
HTML
<div class="input-group" id="DateDemo">
<input type='text' id='weeklyDatePicker' placeholder="Select Week" class="form-control" />
<span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>
JS
$("#weeklyDatePicker").datetimepicker({
calendarWeeks:true,
format: 'MM/DD/YYYY'
});
//Get the value of Start and End of Week
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
alert(firstDate);
$.post("SAMPLE1.php",{"fdate" : firstDate ,"ldate" : lastDate});
});
$('#DateDemo').on('dp.change', function (e) {
var kk = $("#weeklyDatePicker").val();
$("#output").html(
" Week Number: " + moment(kk, "MM/DD/YYYY").week() + " of " +
moment(kk, "MM/DD/YYYY").weeksInYear()
);
});
SAMPLE1 CODE
<?php
echo $_POST["fdate"]; //for firstdate
echo $_POST["ldate"]; //for lastdate
?>
You can use jquery for that. Try this code :
YOUR JS FILE CODE :
$('#weeklyDatePicker').on('dp.change', function (e) {
var value = $("#weeklyDatePicker").val();
var firstDate = moment(value, "MM/DD/YYYY").day(0).format("MM/DD/YYYY");
var lastDate = moment(value, "MM/DD/yyyy").day(6).format("MM/DD/YYYY");
$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
$.post("main.php",{fdate : firstDate ,ldate : lastDate},function(data) {
alert(data);
});
});
YOUR PHP FILE CODE (main.php)
<?php
if(isset($_POST["fdate"])) {
echo $_POST["fdate"]; //for firstdate
}
if(isset($_POST["ldate"])) {
echo $_POST["ldate"]; //for lastdate
}
?>
Make sure both the files are in same folder.
I would use $.ajax() function, which will let you handle the error status as well, because it is both a good practice to handle errors for the users and an indicator of what is going wrong with your script.
$.ajax({
url: 'test.php',
type: 'POST',
data: {fdate : firstDate ,ldate : lastDate},
dataType: 'text',
beforeSend: function(){
// initiate some spinner or loading infobox
// to inform the user about the AJAX request
},
success: function(response){
alert(response);
// you may use result like any standard argument
// and call or trigger other functions according to its value
},
error: function(jqXHR, textStatus, errorThrown){
alert(textStatus + ': ' + errorThrown);
// call some error handler or do nothing
},
complete: function(){
// close the spinner or loading box
}
});
In your PHP file, you get the variables as $_POST['fdate'] and $_POST['lDate']. Once you complete the query and get the results, echo a response something like that:
echo 'success';
or
echo 'failure';
according to the result of the query. You may use any string, not just success or failure. Just don't forget that is what you will handle in the success part of your $.ajax() function and not the error part of it. The error part is only for whatever goes wrong with the request (e.g. file not found or server error).
Well, here is the tricky part: If the only thing you want to return is a status, you may use dataType: 'text' in your $.ajax() function as I did in this example. However, if you want to return an object with some useful data, such as what has gone wrong with the PHP query or what has been accomplished by the PHP query, then you'd better to use dataType: 'json' and get a JSON response. In such a case, the end of your PHP script will change too.
$result = ['statusCode'=>1,'details'=>'Some details according to the query here'];
echo json_encode($result);
The success handler of your $.ajax() function will get an object as the argument (i.e. response will be an object) which you can use like this:
alert(response.statusCode); // will alert 1
Ajax is probably the easiest.
Javascript:
$.get("test.php", { firstDate: firstDate, lastDate: lastDate } );
or
$.post("test.php", { firstDate: firstDate, lastDate: lastDate } );
and in php
<?php
echo $_REQUEST['firstDate'];
echo $_REQUEST['lastDate'];
?>
Hi Kath Dee please check below code, I hope solve your problem using below code.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('#weeklyDatePicker').on('dp.change', function (e) {
// I am using test value, you can change var value base on id.
var firstDate = '08/02/2016';
var lastDate = '10/02/2016';
//$("#weeklyDatePicker").val(firstDate + " - " + lastDate);
$.post("test.php",{fdate : firstDate ,ldate : lastDate},function(data) {
alert(data);
$("#weeklyDatePicker").val(data);
});
});
</script>
<input type="text" value="" id="weeklyDatePicker" />
test.php
<?php
// set your format as you want for display.
echo $_POST['fdate'].'-'.$_POST['ldate'];
?>
I hope this is working fine for you.
I have an image hyperlinked as:
<a id="register" href = "javascript:void(0)"
data-fancybox-group="gallery"><img src="<cms:show my_image_thumb />" alt="" class="fade"></a>
I have a getsession.php class to get the session variable:
<?php
session_start();
if(isset($_SESSION['logged_in']))
echo "1";
else
echo "0";
?>
I want to read the session variable value on click of the image. I am trying to do this as:
<script type="text/javascript">
$(document).ready(function(){
$("#register").click(function(){
$.ajax({
url:'getsession.php',
cache:false,
success:function(data){
// Do something with the result
if(data=="1"){
window.location = "www.google.com";
}else{
document.getElementById('light').style.display='block';
document.getElementById('fade').style.display='block';
document.getElementById('fade').scrollIntoView(true);
}
}
});
});
});
</script>
However, when clicking the image there is no effect. Any pointers?
First, make sure to log ( console.log('button clicked'); ) that the function is entered and then log the data ( console.log(data); ) when the response arrives.
Also, check that the php script is working by simply opening it in the browser.
By the way, window.location should have an absolute url assigned to it
window.location = "http://www.google.com";
Chances are your php file is not placed in the proper position. Try running the file directly from url. It should print 1 if session is set. And after this,try changing the url to absolute url of the file like http://localhost/getsession.php .
try this :
php:
<?php
session_start();
if(isset($_SESSION['logged_in']))
echo "1";
else
echo "0";
?>
js:
$.ajax({
url:'http://localhost/getsession.php',
cache:false,
type: 'POST',
success:function(data){
// Do something with the result
alert("ajax call success returns: "+ data);
if(data=="1"){
window.location.href = "http://www.google.com/";
}else{
window.location.href = "http://www.stackoverflow.com/";
}
},
error: function (jqXHR, textStatus, errorThrown) {
alert("Error Code: " + jqXHR.status + ", Type:" + textStatus + ", Message: " + errorThrown);
}
});
I'm not sure if it is an ajax issue or if I have an infinite loop, I'm trying to get the values of one page to another.
My 1st page is a cakephp contoller:
$arr = ($this->Phone->find('all'));
$arr2 = json_encode($arr);
echo $arr2;
$_GET ['var1'] = $arr2;
die();
My 2nd page that gets and displays the output is this one
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="sizeof.js"></script>
<script type="text/javascript">
var results;
{
$.ajax({
type: 'GET',
url: 'http://localhost/restdemo/',
data: {
var1: results
},
success: function(data) {
console.log('success');
var output = JSON.parse(data);
for (x = 0; x <= output.length - 1; x++) {
var hello = (output[x]["Phone"]["name"]);
document.write('<table border="1" cellspacing="1" cellpadding="5">');
document.write('<tr>');
document.write('<td>' + hello + '</td>');
document.write('</tr>');
document.write('</table>');
}
}
});
}
</script>
</head>
<body>
</body>
</html>
I am getting my desired results however the page doesn't stop loading which makes me think that I have an error in my code to cause such an action. What causes this?and how can I fix it?. any feedback, comments and suggestion is highly appreciated.
I m sending some checkbox which are selected,their value to next php page with ajax call.but in the above code i m not able to send it to ajax call
code is as below
<html>
<head>
<title>Insert title here</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
</head>
<body>
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="services"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function () {
alert("hi");
//var os = $('#originState').val();
\ //var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
//var queryString = "os=" + os;
var queryString = "&ser=" + ser;
alert("hi");
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: "query=" + queryString,
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
<form name="searchForm">
<input type="checkbox" name="services" value="twic" />TWIC
<br/>
<input type="checkbox" name="services" value="enclosedTrucking" />Enclosed Trucking
<br/>
<input type="checkbox" name="services" value="flatBedTrucking" />Flat Bed Trucking
<br/>
<input type="submit" id="btnSubmit" value="Submit" />
</form>
<div id="results">
</div>
</body>
</html>
In above code.When i select checkboxes from page,and on click of submit.i want to pass them to next php page with ajax call.but its not going to next page and no response is coming back....
Please help guysss
ajaxphp page
<?php
include('connection.php');
$query=$_GET['query'];
echo $query;
$countsql='SELECT * FROM XML';
$countsql1=mysql_query($countsql);
$numrows = mysql_num_rows($countsql1);
$countArray2=array();
print($countsql);
while($row = mysql_fetch_array($countsql1)) {
// Append to the array
$countArray2[] = $row;
//echo $row['PID']."<BR />";
}
?>
<?php
foreach($countArray2 as $array)
{
?>
<div class="search">
hi
</div>
<?php $i++; } ?>
data: "query=" + queryString, is wrong because the "query=" + is a syntax error. It should be:
var queryString = "os="+os+"&ser="+ser;
and then
data : queryString,
Or you can format it like:
data : {
'ser' : ser,
'os' : os
}
Then there is the fact that your Ajax is using POST but you're trying to read the request with $_GET rather than $_POST or $_REQUEST in your PHP.
You can try with these two amends:
var data : "?ser=" + ser; // put '?' instead of '&'
Or more jQuery way:
data : { ser : ser },
And you are missing the dataType in your ajax:
dataType : 'html',
On the php side, as this is a post request, so you have to put this:
$query=$_POST['ser'];
Maybe you're forgetting to prevent the Submit button default behavior:
<script type="text/javascript">
function get_check_value() {
var c_value = [];
$('input[name="services"]:checked').each(function () {
c_value.push(this.value);
});
return c_value.join(',');
}
$(document).ready(function(){
$('#btnSubmit').on('click', function (evt) {
evt.preventDefault();
alert("hi");
//var os = $('#originState').val();
\ //var c = $('#commodity').val();
//var ds = $('#destState').val();
var ser = get_check_value();
//var queryString = "os=" + os;
var queryString = "&ser=" + ser;
alert("hi");
$.ajax({
//alert("ajax");
type: "POST",
url: "sortingajax.php",
data: "query=" + queryString,
success: function (b) {
// alert(a+' ok. '+b)
$('#results').html(b);
console.log(b);
}
});
});
});
</script>
I need to give a javascript alert to users browser when a new record is added to database. So far i have done this:
PHP chatalert.php
require("../system/config.php");
$result = mysql_query("SELECT * FROM chat");
$rows = mysql_num_rows($result);
echo $rows;
Javascript: test.php
<?php
define('BASEPATH', true);
require("../system/config.php");
?>
<script>
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "chatalert.php",
success : function(data){
if (data > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);
</script>
But I always recive an error: "Uncaught ReferenceError: $ is not defined". So I will need some advice on this.
Mairo
Have you included jquery? if not try adding this in your head tags
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
also make sure to parse the string to integer/Float for accurate result. The data returned by php can also be in string format:
var old_count = 0;
setInterval(function(){
$.ajax({
type : "POST",
url : "chatalert.php",
success : function(data){
if (parseFloat(data) > old_count) {
alert('new record on i_case');
old_count = data;
}
}
});
},1000);