Getting JSON data with jquery ajax not working [closed] - php

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to understand how to fetch and display data with jquery ajax. I have a php page (data.php)that successfully retrieves data from a mysql database and encodes that data into a json array. Client side I have a page called get.php. I just can't figure out why my script will not fetch any data from data.php I get nothing in the firebug console.
data.php
echo json_encode($mydata);
which outputs:
[
{
"id":"236",
"title":"The Jungle Book"
},
{
"id":"235",
"title":"The Shallows"
},
{
"id":"232",
"title":"For Your Eyes Only"
},
{
"id":"231",
"title":"Ice Giants"
}
]
get.php
<script>
("button").click(function(){
{
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var title = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});
</script>
<h3>Output: </h3>
<button>Get Data</button>
<div id="output"></div>

You have few mistake like: you didn't specify jquery($) for button
selector, you use multiple bracket { inside click function, inside
ajax success you have assigned full object against id and title it
should be id=data[0]['id'] and title=data[0]['title] and another
mistake there no defined variable vname. php better json output you should use header('Content-Type: application/json'); in data.php.
Try this:
index.php
<h3>Output: </h3>
<button>Get Data</button>
<div id="output"></div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$("button").click(function(){
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data){
//console.log(data);
var id = data[0].id;
var title = data[1].title;
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+title);
}
});
});
</script>
data.php
<?php
header('Content-Type: application/json'); //use header to specify data type
//echo json_encode($mydata); // un-comment this line
echo '[{"id":"236", "title":"The Jungle Book"}, {"id":"235", "title":"The Shallows"}, {"id":"232", "title":"For Your Eyes Only"}, {"id":"231", "title":"Ice Giants"} ]'; // comment this line
?>

<script>
$("button").click(function()
{
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var title = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});
try like this

Related

Data doesn't transfer to PHP from Ajax [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to pass data that comes from a prompt, but the PHP doesn't receive the data.
<script>
function test(){
var r=prompt("blaksasda");
if(r){
$.ajax({
type: "POST",
url: "file.php",
data: {
param:r,
}
});} };
</script>
PHP file:
<?php
echo "$_POST['param']";
?>
Are you sure PHP doesn't receive the data? Probably Ajax call works correctly. The problem is that you don't handle the echoed result.
Try the following:
$.ajax({
type: "POST",
url: "file.php",
data: {param: r}
}).done(function(result) {
alert(result);
});
Ok, let me add the whole thing.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function test(){
var r=prompt("blaksasda");
if(r){
$.ajax({
type: "POST",
url: "test.php",
data: { param: r }
}).done(function(result){
alert(result);
}).fail(function(result){
alert('failed: ' + result);
});
}
}
</script>
</head>
<body>
<button onclick="test()">Click me!</button>
</body>
</html>
test.php looks like this
<?php
if (isset($_POST['param'])) {
echo $_POST['param'];
} else {
echo 'Whoops';
}
So when I click on the button 'Click Me', it's going to call the test function and give you a prompt and you type the text in and when you submit, you get the result back from test.php. I tried it and it worked fine.
UPDATE:
Instead of doing an alert in the success handler, just set the result like this:
.done(function(result){
$('#result').html(result);
});
Your page will look something like this. Whatever you get from your page, your span will have that. Hope it makes sense.
<body>
<button onclick="test()">Click me!</button>
<br/>
Prompt result: <span id="result"></span>
</body>

How to handle click event on Submit Button [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
Here is my script for handling submit button click event
$('#subbtn').on("click",function(){
var stcode = $('.stcode11').val();
var sem = $('.sem11').val();
var doa = $('.doa11').val();
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: 'stcode='+stocde+'&sem='+sem+'&doa='+doa,
success: function(msg)
{
$('.atnresult').html(msg);
}
});
});
And here is the button code
<button id='subbtn' type='submit' class='button'> Change </button>
But it not working properly. Please help me to handle click event of submit button.
You should handle the submit event of form Then you can use event.preventDefault() to cancel the default action.
$('YourFormSelector').on("submit",function(event){
//Cancel default event
event.preventDefault();
//Rest of your code
});
First, the way you are doing the submit requires you using e.preventDefault(); to prevent your form from being submited via html.
Second, the way you pass the data is wrong/the way you would do for a GET operation. As you are trying to submit via POST, you need to create data like this:
data: {
stcode : stocde
sem : sem
doa : doa
}
Full code:
$('#subbtn').on("click",function(e)
{
e.preventDefault();
var stcode = $('.stcode11').val();
var sem = $('.sem11').val();
var doa = $('.doa11').val();
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: {
stcode : stocde
sem : sem
doa : doa
}
success: function(msg)
{
$('.atnresult').html(msg);
}
});
});
Try this:
$(document).on("click","#subbtn",function(e)
{
e.preventDefault();
var formData = new FormData();
formData.append( 'stcode', $('.stcode11').val());
formData.append( 'sem', $('.sem11').val());
formData.append( 'doa', $('.doa11').val());
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: formData,
success: function(msg)
{
$('.atnresult').html(msg);
}
});
});
replace this line
data: 'stcode='+stcde+'&sem='+sem+'&doa='+doa,
with
data: 'stcode='+stcode+'&sem='+sem+'&doa='+doa,
full code with preventdefault
$('#subbtn').on("click",function(e) {
var stcode = $('.stcode11').val();
var sem = $('.sem11').val();
var doa = $('.doa11').val();
$.ajax({
type:'post',
url: 'includes/atneditprocess.php',
data: 'stcode='+stcode+'&sem='+sem+'&doa='+doa,
success: function(msg)
{
$('.atnresult').html(msg);
}
});
e.preventDefault();
});

Updating page using AJAX

On my main page I have a page called logs.php which I have set to update every 4 seconds using jquery/ajax. This will update the details of an .xml file which is stored locally.
file_put_contents("../../scripts/xml/logs.xml", $dom) or print_r(error_get_last());
Here is the jQuery:-
$(function(){
setInterval(function(){
$.ajax({
url:'scripts/php/log.controller.php',
success:function(data){
if(data == "scripts/php/status.controller.php"){
}else{
alert(data);
}
}
});
},4000);
});
When I alert(data); it shows me the changes of the updated XML file:
<?xml version="1.0"?>
<loglist resultcount="24"><log id="0"><messagedate>20/06/2014 10:34:48</messagedate><car></car><stat>Ping</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="1"><messagedate>20/06/2014 10:34:47</messagedate><car></car><stat>Ping</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="2"><messagedate>20/06/2014 10:34:35</messagedate><car>6</car><stat>Quit</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="3"><messagedate>20/06/2014 10:34:32</messagedate><car>8</car><stat>Ping</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="4"><messagedate>20/06/2014 10:34:31</messagedate><car>10</car><stat>Ping</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="5"><messagedate>20/06/2014 10:34:30</messagedate><car>3</car><stat>Ping</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="6"><messagedate>20/06/2014 10:34:28</messagedate><car>2</car><stat>Ping</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="7"><messagedate>20/06/2014 10:24:27</messagedate><car></car><stat>Ping</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="8"><messagedate>20/06/2014 10:15:16</messagedate><car>10</car><stat>Quit</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="9"><messagedate>20/06/2014 10:14:01</messagedate><car>4</car><stat>Quit</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="10"><messagedate>19/06/2014 14:07:35</messagedate><car></car><stat>Ping</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="11"><messagedate>19/06/2014 13:43:54</messagedate><car></car><stat>Ping</stat><ping></ping><job>Operator</job><operator></operator><jobref></jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="12"><messagedate>19/06/2014 13:42:58</messagedate><car>1</car><stat>Disp</stat><ping></ping><job>100 BLYTHE ROAD</job><operator></operator><jobref>220213</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="13"><messagedate>19/06/2014 13:42:57</messagedate><car>9</car><stat>Disp</stat><ping></ping><job>4 LILESTONE STREET; LONDON</job><operator></operator><jobref>220620</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="14"><messagedate>19/06/2014 13:42:56</messagedate><car>8</car><stat>Disp</stat><ping></ping><job>4 LILESTONE STREET; LONDON</job><operator></operator><jobref>220618</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="15"><messagedate>19/06/2014 13:42:56</messagedate><car>6</car><stat>Disp</stat><ping></ping><job>3P+3HL 22 MOUNT STREET</job><operator></operator><jobref>221165</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="16"><messagedate>19/06/2014 13:42:54</messagedate><car>5</car><stat>Disp</stat><ping></ping><job>GODOLPHIN LETYMER SCHOOL , IFFLEY ROAD</job><operator></operator><jobref>220211</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="17"><messagedate>19/06/2014 13:42:53</messagedate><car>4</car><stat>Disp</stat><ping></ping><job>32 ABERDEEN PLACE</job><operator></operator><jobref>220774</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="18"><messagedate>19/06/2014 13:42:52</messagedate><car>2</car><stat>Disp</stat><ping></ping><job>45 LOCKBRIDGE COURT WOODFIELD ROAD</job><operator></operator><jobref>221121</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="19"><messagedate>19/06/2014 13:42:50</messagedate><car>89</car><stat>Disp</stat><ping></ping><job>C------ GATWICK AIRPORT NORTH___EZY 8894__MARACUS</job><operator></operator><jobref>220793</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="20"><messagedate>19/06/2014 13:42:48</messagedate><car>43</car><stat>Disp</stat><ping></ping><job>183 EDGWARE ROAD; LONDON</job><operator></operator><jobref>221193</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="21"><messagedate>19/06/2014 13:42:45</messagedate><car>32</car><stat>Disp</stat><ping></ping><job>BEST WESTBURY SHAFTESBURY HOTEL, 27 DEVONSHIRE TERRACE</job><operator></operator><jobref>220989</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="22"><messagedate>19/06/2014 13:42:43</messagedate><car>111</car><stat>Disp</stat><ping></ping><job>22/17 ST. EDMUNDS TERRACE; LONDON</job><operator></operator><jobref>220973</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log><log id="23"><messagedate>19/06/2014 13:42:42</messagedate><car>10</car><stat>Disp</stat><ping></ping><job>WESTMINSTER ACADEMY;255 HARROW ROAD</job><operator></operator><jobref>220617</jobref><gpsx></gpsx><gpsy></gpsy><carspeed></carspeed></log></loglist>
But the page logs.php is not updating as it should be.
The logs.php file is populating a list as follows:-
<ul id="loglist" class="main-logs"></ul>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: "GET",
url: 'scripts/xml/logs.xml',
datatype: "xml",
success: function(xml) {
var select = $('#loglist');
$(xml).find('log').each(function(){
var car = $(this).find('car').text();
var stat = $(this).find('stat').text();
var job = $(this).find('job').text();
select.append("<li>"+car+' - '+stat+' - '+job+"</li>");
});
}
});
});
</script>
Anyone have any idea why this is not updating?
I tried your example on fiddle and it seems to work perfectly if xml is a string. Try to change your dataType parameter to string instead of xml and it should work.
Here is my example: http://jsfiddle.net/8gEAN/
Try this:
<html>
<body>
<!--list to update-->
<ul id="loglist" class="main-logs"></ul>
<script type="text/javascript">
$(document).ready(function(){
$(function(){
//every 4 seconds send an ajax request to update the XML file
setInterval(function(){
$.ajax({
url:'scripts/php/log.controller.php',
success:function(data){
//when the XML is updated, send another ajax request to retrieve it and update the list
$.ajax({
type: "GET",
url: 'scripts/xml/logs.xml',
datatype: "string",
success: function(xml) {
var select = $('#loglist');
$(xml).find('log').each(function(){
var car = $(this).find('car').text();
var stat = $(this).find('stat').text();
var job = $(this).find('job').text();
select.append("<li>"+car+' - '+stat+' - '+job+"</li>");
});
}
});
}
});
},4000);
});
});
</script>
</body>
Put below function in your ajax call. This may be cache issue.
$.ajaxSetup ({
// Disable caching of AJAX responses
cache: false
});
For more details

refreshing php content inside div when input onchange [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a simple <input> and when user writes there something I need to refresh php inside div so it will look like some.php?key=thevaluefrominput. How would I do that? I guess I need to use query but I'm not sure how.
I want something like this when you write something to Type to find tags it changes the the tags bellow.
Thanks for the answers.
This sounds like a job for AngularJS :)
However this is jQuery solution:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape($.trim($('#myinputfield').val())),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
});
});
If you mean that while user types (before submission), div content changes? Then remove
$('form').submit(function (e) {
e.preventDefault();
and instead put
$('#myinputfield').keydown(function () {
There is a setInterval method that I mentioned in comment, so the first chunk of code I posted, replace it with this one:
$(function () {
var old_val = '';
var curr_val = '';
setInterval(function () {
curr_val = $.trim($('#myinputfield').val());
if (old_val != curr_val) {
old_val = curr_val;
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape(curr_val),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
}
}, 2000);
});
It checks if value of the field changed every 2s, please replace amount in ms (2000) if you like.

Ajax request for PHP to return HTML [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have an element on a page that when clicked will make an ajax request to a receiver.php file:
<script>
function send(id){
$.ajax({
type: 'POST',
dataType: 'html',
url: 'receiver.php',
data: {id: id}
});
}
</script>
<img src="foo.bar" onclick="send(id)"/> <!-- simplified -->
My idea is that this receiver.php file will receive the id, then output a whole page of HTML based on that id
However, when I click on the element, the new HTML page that I expect doesn't show up. When I go to the Chrome inspector, Network tab I can see the request and the response is exactly the HTML content I need, but why doesn't it change to that new page and stay on the old page instead?
EDIT: This is my receiver.php, for testing purpose:
<html>
<head></head>
<body>
<?php
echo "<p>".$_POST['comid']."</p>";
echo "<p> foo foo </p>";
?>
</body>
</html>
this is the response:
<html>
<head></head>
<body>
<p>3</p><p> foo foo </p> </body>
</html>
Perhaps in your receiver.php script you're doing something like this, where you determine which HTML page to output depending on the id that it is receiving.
switch ($_POST['id']) {
case 'foo':
$filepath = 'bar';
break;
...
}
readfile($filepath);
You would have to reflect that in your AJAX query, using the success function of $.ajax.
function send(id) {
$.ajax({
type: 'POST',
dataType: 'html',
url: 'receiver.php',
data: {id: id},
success: function (data) {
// Replace the whole body with the new HTML page
var newDoc = document.open('text/html', 'replace');
newDoc.write(data);
newDoc.close();
}
});
}
You have to do something with the result that comes back from you AJAX call:
function send(id){
$.ajax({
type: 'POST',
dataType: 'html',
url: 'receiver.php',
data: {id: id},
success: function(data){
console.log(data);
}
});
}

Categories