get only specific data in success message from ajax - javascript

i have an ajax call and i am getting a response from the call. the code is like this:
<div id="flow_#id#~#sid#" style="margin: 0 10px 0 0;float:right;height:150px;" class="code">
<img src="/assets/codes/#code#.jpg" style="max-height: 230px;">
</div>
What i am doing is the response i get from my ajax, i want to replace the contents of the div tag with the value coming from my ajax success
ajax call is like this
$.ajax({
url: 'bc.cfm?ID=' + getID + '&ssID=' + getSID,
type: "GET",
cache: false,
success: function(data){
$("#flow_" + getID + "~" + getSID + " img:last-child").remove();
$("#flow_" + getID + "~" + getSID).html(data);
}
});
But a complete html page is coming in success, i can the img in firebug, but a complete html source is there, how can i extract that img tag and replace with the one which is already there above [the id is going to be same for both for identification, only 1 will be used, we will be removing and adding again]

If you want to just extract image from the response, you can try this. I have not tested the code, but it should work. Please check it.
success: function(data){
// get the image tag from the response
var $img = $(data).find('img');
$("#flow_" + getID + "~" + getSID + " img:last-child").remove();
// replace
$("#flow_" + getID + "~" + getSID).html($img.html());
}

Use JSON instead
for example:
javascript
$.ajax({
type: 'POST',
url: 'yourphpfile.php',
dataType: 'json',
success: function (x) {
console.log(x.imgtag); // img
}
});
return false;
php
<?php
header('Content-Type: application/json');
$output=array();
$output['imgtag']='<img src="myimg.jpg">';
echo json_encode($output);
?>
Place whatever you want into the $output array (such as img tags) and you may easily access it in JavaScript.

Related

Send variable from Javascript to PHP using AJAX post method

I am trying to pass a variable from javascript to php, but it doesn't seem to be working and I can't figure out why.
I am using a function that is supposed to do three things:
Create a variable (based on what the user clicked on in a pie chart)
Send that variable to PHP using AJAX
Open the PHP page that the variable was sent to
Task one works as confirmed by the console log.
Task two doesn't work. Although I get an alert saying "Success", on test.php the variable is not echoed.
Task three works.
Javascript (located in index.php):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
// Task 2 - send var to PHP
$.ajax({
type: 'POST',
url: 'test.php',
dataType: 'html',
data: {
'itemNum' : itemNum,
},
success: function(data) {
alert('success!');
}
});
// Task 3 - open test.php in current tab
window.location = 'test.php';
}
}
PHP (located in test.php)
$item = $_POST['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
Thanks to anyone who can help!
From what i can tell you don't know what ajax is used for, if you ever redirect form a ajax call you don't need ajax
See the following function (no ajax):
function selectHandler(e) {
// Task 1 - create variable
var itemNum = data.getValue(chart.getSelection()[0].row, 0);
if (itemNum) {
console.log('Item num: ' + itemNum);
console.log('Type: ' + typeof(itemNum));
window.location = 'test.php?itemNum='+itemNum;
}
}
change:
$item = $_GET['itemNum'];
echo "<h2>You selected item number: " . $item . ".</h2>";
or better you do a simple post request from a form like normal pages do :)
Try this:
success: function(data) {
$("body").append(data);
alert('success!');
}
Basically, data is the response that you echoed from the PHP file. And using jQuery, you can append() that html response to your body element.
you should change this code
'itemNum' : itemNum,
to this
itemNum : itemNum,
Seems contentType is missing, see if this helps:
$.ajax({
type: 'POST',
url: 'test.php',
dataType: "json",
data: {
'itemNum' : itemNum,
},
contentType: "application/json",
success: function (response) {
alert(response);
},
error: function (error) {
alert(error);
}
});
you can easily pass data to php via hidden variables in html for example our html page contain a hidden variable having a unique id like this ..
<input type="hidden" id="hidden1" value="" name="hidden1" />
In our javascript file contains ajax request like this
$.ajax({
type: 'POST',
url: 'test.php',
data: {
'itemNum' : itemNum,
}
success: function (data) {
// On success we assign data to hidden variable with id "hidden1" like this
$('#hidden1').val(data);
},
error: function (error) {
alert(error);
}
});
Then we can access that value eighter on form submit or using javascript
accessing via Javascript (Jquery) is
var data=$('#hidden1').val();
accessing via form submit (POST METHOD) is like this
<?php
$data=$_POST['hidden1'];
// remaining code goes here
?>

Get Gravatar Img from JSON

I'm trying to parse data that will display a users Gravatar image. The JSON is the following : http://api.bfhstats.com/api/playerInfo?plat=pc&name=stewartps&output=js On line 34 is 'uGava' which is their gravatar URL. It should be then http://gravatar.com / + uGava
At the moment I have a form which asks for the user to input a name and select a platform.
This is the code I have for that:
$("#playerstuff").submit(function() {
$.ajax({
type: "GET",
url: 'http://api.bfhstats.com/api/playerInfo?plat=' + document.getElementById("platform").value +'&name=' + document.getElementById("playername").value,
//datatype : "json",
success: function(data)
{
document.getElementById("playerrank").innerHTML = '<img src="http://gamingstats.ga/' +data["player"]["rank"].imgLarge + '" />';
$("#formpanel").hide();
$("#dataret").show();
$("#playerimg").show();
}
});
return false;
});
I also just have a standard Image
<div class="user-img-div" id="playerimg" style="display: none;" >
<center><img src="img.png" class="img-circle"></center>
</div>
So my question is how will i use that standard Image to display the users Gravatar from the JSON data?
The data you get is plain JS, not JSON. Also, you don't need to use the bracket notation when the object properties don't have special characters in them. Change your AJAX call to the following:
$("#playerstuff").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: 'http://api.bfhstats.com/api/playerInfo?plat=' + document.getElementById("platform").value +'&name=' + document.getElementById("playername").value,
// script data type
datatype: "script",
success: function(){
var data = window.pd;
$("#playerrank").html('<img src="http://gamingstats.ga/' +data.player.rank.imgLarge+'"/>');
$("#formpanel").hide();
$("#dataret").show();
// Use Gravatar as user image
$("#playerimg").attr('src', 'http://gravatar.com/'+data.player.uGava).show();
}
});
});
Alternatively, since their API does support JSON, you can change the output GET parameter and use this instead:
$("#playerstuff").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
url: 'http://api.bfhstats.com/api/playerInfo?output=json&plat=' + document.getElementById("platform").value +'&name=' + document.getElementById("playername").value,
// script data type
datatype: "json",
success: function(data){
$("#playerrank").html('<img src="http://gamingstats.ga/' +data.player.rank.imgLarge+'"/>');
$("#formpanel").hide();
$("#dataret").show();
// Use Gravatar as user image
$("#playerimg").attr('src', 'http://gravatar.com/'+data.player.uGava).show();
}
});
});

ajax json php callback lost css jquery mobile

I'm developing a web app, using Jquery Mobile, I have to make an Ajax/Json to a PHP to retrieve MySQL data, when I get the JSON Callback, and create the "list" from the array, the path of the jquery mobile css file get lost, and my is not well formed. This is my code :
$.ajax({
url: "busca_reservas.php",
data: "fecha=" + fecha + "",
dataType: 'json',
type: "POST",
cache: false,
success: function(data){
var output = '<ul data-role="listview" data-inset="true" id="reservas" class="listareservas">';
var logsData = data;
for (var i in logsData.logs){
regis = logsData.logs[i].recid;
nombre = logsData.logs[i].nombre;
ape = logsData.logs[i].apellido;
output+= '<li>' + regis + " " + nombre + " " + ape + '</li>';
}
output+='</ul>';
$('.listareservas').listview('refresh');
$("#result").append(output).fadeIn(500);
console.log(output)
}
});
The content in my looks like plain text, instead of Jquery Mobile "List View".
Any help wil be welcome ?
Thanks in advanced
Try putting the refresh after the append:
$("#result").append(output).fadeIn(500);
$('.listareservas').listview('refresh');
I vaguely remember this issue when I was working on a jquery mobile project ahwile back. I basically came to this solution
function refreshLayout() {
$("div[data-role=page]").page("destroy").page();
}
which I would call with every ajax success function. You may have to modify the data-role portion to fit what needs to be refreshed in your project. Hope that helps

Ajax GET request, why does success function not print?

I have this function that performs a GET request for a given id:
var findById= function(id) {
console.log('findById: ' + id);
$.ajax({
type: 'GET',
url: rootURL + '/' + id,
dataType: "json",
success: function(data){
console.log('findById success: ' + data.name);
currentRaceEntry = data;
renderList(currentRaceEntry);
}
});
};
When I enter sitename/rest/entries/8 it returns a page with the xml for the object requested(as expected). (I can show this code but I dont think the problem is there). When I preform this request the console shows:
findById 8
My question is why doesn't it show console.log('findById success: ' + data.name);? The xml displays in the browser which looks to me like it was successful. So why doesn't the success function appear to be called? Thanks!
EDIT
this is what it looks like:
The console in the browser is blank
If you ajax request returns XML data, you need to set dataType as "xml".
At that point, the data object in the success function is an XML fragment, not a javascript objet, and you need to process it as such. The data.name property doesn't exist.

Ajax being called twice on setInterval

I'm doing ajax calls in a specific time interval using javascript setInterval function however the ajax code is being executed twice, so I'm getting the same response twice and I have no idea why this is happening, here's the code:
setInterval(function () {ajaxCall();},15000);
function ajaxCall(){
var uri = "url here";
$.ajax({
type: "GET",
url: uri,
dataType: "jsonp",
success: function(response){
console.log(response);
var txt = $("#textarea");
txt.val( txt.val() + response.user + " (" + response.time + ") > "
+ response.text + '\n');
}
});
}
Any help would be appreciated.
Thanks
Ok so I just figured it out, I had that script inside the html body tag but if I move it inside head tags it stops calling it twice, not sure why this is but it solved the problem.
Sorry for wasting your time for something that simple xD

Categories

Resources