Pass external URL into ajax javascript - php

I am trying to fetch the contents of an external XML URL, into the javascript's ajax script, but it simply won't accept it, due to CROSS domain issue. I have searched through google regarding this issue, but nothing good so far, everything I've read so far stated that I need to incorporate PHP as well, but with that, the page would take reload.
I simply want that when a user enters a number that number gets passed as an argument in the URL, then displays the XML content in the screen without reloading.
SO any help will be highly appreciated.
Here's my code so far.
<script>
function myFunction() {
$("#dvContent").append("<ul></ul>");
$.ajax({
type: "GET",
url: "http://lx2.loc.gov:210/lcdb?operation=searchRetrieve&recordSchema=marcxml&version=1.1&maximumRecords=1&query=bath.isbn%3D9781452110103",
dataType: "xml",
success: function(xml){
$(xml).find('record').each(function(){
var sTitle = $(this).find('datafield[tag="245"]').find('subfield[code="a"]').text();
var sAuthor = $(this).find('datafield[tag="100"]').find('subfield[code="a"]').text();
var sIsbn = $(this).find('datafield[tag="020"]').find('subfield[code="a"]').text();
$(".mypanel").html(text);
});
$("<li></li>").html(sTitle).appendTo("#dvContent ul");
$("<li></li>").html(sAuthor).appendTo("#dvContent ul");
$("<li></li>").html(sIsbn).appendTo("#dvContent ul");
});
},
error: function() {
alert("An error occurred while processing XML file.");
}
});
}
</script>

Related

PHP: Assigning an AJAX response value into PHP Variable

I've read all the articles but cant seem to get my ajax response into a PHP variable. Please can you advice. I want to assign rowid to a PHP variable.
$(document).on('click', '#updateid', function() {
var vallab = $('#idval').val();
var rowid;
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
console.log(rowid);
return rowid;
});
my a.php code is below
<?php
# Fetch the variable if it's set.
$lab_id = (isset($_POST["labid"])) ? $_POST["labid"] : null;
echo $lab_id;
?>
I am getting the response back with the id, and want to use it on that page
I want to pass rowid into a PHP function so I need to get the value of rowid.
Please can you advice?
I cant seem to get my ajax response into a PHP variable
Well, the AJAX response came FROM a PHP file, right? So why don't you do whatever you need to do with the response right in that PHP file?
$.ajax({
url:'THIS IS YOUR PHP FILE',
type: 'POST',
data: {THIS IS THE DATA YOU SEND TO PHP},
success: function(data){
console.log(data); //THIS IS THE RESPONSE YOU GET BACK
}
});
You can't use it. Javascript is a scripting language which run in browser when the dom is loaded and elements are visible.
PHP is a serverside language and run on server before the page is loaded.
You need to understand the lifecycle of your application. Your php code executes once, it runs the full script from top to bottom when the page loads. At the point the script starts if can only access the post that came with the request (e.g if you clicked submit on a form then the 'action' of the form receives the post). Any number of things can happen in your script, but once it's finished the php is gone, and so is the post (in basic terms). So you no longer have any access to the php which created this page.
Ajax allows you to update a section of your page - it sends a request to your sever and runs some php code - you must understand that this is a new and separate request, so the new post submission only exists in the lifecycle of this new execution and is in now way linked to the page that has already finished loading. Now you could ask Ajax to call your original script, but that wouldn't affect your page at all because the page does not reload. What you would get is a strange looking response which you (probably) couldn't do anything useful with.
Ajax allows small specific changes to the page, so when you get your response (which I assume you get in a format you want since you don't ask about it and you have a console.log) you then need to do something with jQuery/javascript. Instead of returning rowid write a javascript function like :
function printRowId(rowid) {
$('#your html div id here').text('Row id is ' + rowid);
}
and then call it in your response:
$.ajax({
url:'a.php',
type: 'POST',
async: false,
data: {labid: vallab},
success: function(data){
// console.log(data);
rowid = data;
}
});
printRowId(rowid);
return rowid;
You can use Ajax to update your data, update your database and then reflect the changes on the current page, but you cannot use it to pass directly to the php that has already finished executing

Using POST data in a query with Ajax and PHP

I have a website that uses bootstrap tabs so I'm trying to make everything work with minimal refreshing with Ajax, however I'm having trouble with getting an ajax post to work with a mysql query until the page is refreshed.
Once a button is pressed the value is grabbed from the ID of that element by Ajax and a bootstrap tab is opened. This is where I want the data to be passed so the results are relevant to the option that the user has selected.
Modules.php
(Ajax request)
$(".completed").click(function() {
var element = $(this);
var ID = $(this).attr("id");
var dataString = 'id='+ ID;
$.ajax({
cache: false,
url: "includes/scripts/ajax/module_parts.php",
type: "POST",
datatype: "text",
data: dataString,
success: function (html) {
$('#moduleNum').html(ID);
console.log(ID);
},
error: function(data, errorThrown)
{
alert('request failed :'+errorThrown);
}
});
return false;
});
module_parts.php
$module_id = mysqli_real_escape_string($connection, $_POST['id']);
echo $module_id;
$query = mysqli_query ($connection, "SELECT number FROM Modules WHERE number = '".$module_id."'");
I know that the post is working correctly because I tried turning the post into a session then when refreshing the page the data was displayed.
Also the data is displaying correctly when appending the ID to an html element.
Many thanks,
Zack.
Just as a side note, I prefer to do this with ajax shenanigans. It may help you ...
Altered the anchor element:
Click me
Javascript:
ID = $(this).attr("id")
$('body').on('click', '[rel="completed"]', function() {
$.post('includes/scripts/ajax/module_parts.php', { id : ID }, function(data) {
$('#moduleNum').html(data); // data or ID ?
}).fail(function() {
alert('request failed');
});
});
The $('body').on part helps to keep scripts alive should you insert new links or buttons. It means anything within the body tag but you can and maybe should narrow it down further such as the surrounding div.
I, personally, find this way to be easier to deal with, especially if there is just simple data passing to and fro.
1) Check if id is passed by post and get by module_parts.
2) I'd rather use object when passing post data via ajax:
data: { id : ID }
3) Good option to check ajax requests is to use Firebug (on Console), you can check requests details without echoing.
At least two things in your script need resolution.
datatype should be changed to dataType (text is not one of jQuery's "intelligent guess" types (xml, json, script, or html), so dataType must be correctly spelled.
You should prevent the default behavior of the anchor click event.
(".completed").click(function(e) {
e.preventDefault
...
There may be some additional problems, but these two jumped out at me.

Ajax request multiple data info

I'm going crazy over this script, i'm trying to het this working by when some one click on a button then with ajax fetch data from another URL then fill form inputs with the fetched data can any one help please
my code look like this:
$(document).ready(function()
{
$("#getmetaData").click(function(){
var element = $(this);
var url = $("#url").val();
var dataString = 'url='+ url ;
//alert(dataString);
if(url=='http://')
{
alert("Please Enter URL to fetch Meta Data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="images/loader.gif" >');
$.ajax({
type: "POST",
url: "fetch-metadata.php",
data: dataString,
cache: false,
success: function(data){
$("#title").val(data);
$("#description").val(data);
$("#keywords").val(data);
$("#flash").hide();
}
});
}
return false;});});
If you see no error, which I am guessing is the case, it means your request is failing. Since you have no error function, when your request fails, your jQuery code will do nothing.
Add something like this to your $.ajax object argument:
error: function(jqXHR, textStatus, errorThrown) {
// now you can set a breakpoint or log textstatus/errorThrown
},
As per HackedByChinese's answer I would add an error callback function.
Also, in your success callback function you are simply using the 'data' variable without doing anything with it. Depending on the format of the response from 'fetch-metadata.php' I think you'll need to do something first. It's either XML in which case you'll need to parse it. If its json you can use object dot notation to reference it's properties.
Lastly, I'd use something like Firebug to look at the request and response for this Ajax request to make sure it's being processed and not returning a 404 or 500. Assuming its returning a valid response, using Firebug you can look at the response to see the raw data that is being returned to your js.
Hope this helps

Use Javascript variable in PHP

I have seen some answers to this question in previous posts, but no one has given a real working example, just psuedo code. Has anyone ever done this before?
Basically, what i have is a variable in javascript (jquery), and i want to use this variable to drive a query (for an overlay window) i am going to run in php.
From what i have read you can do this using an ajax call to the same page so it doesnt refresh itself, but i must be missing something because i can't get it working...
Any examples out there?
Thanks.
UPDATE 6/21/2010:
Ok, i tried to work through but still having some problems...here is what i have. The page I am working on in edit_1.php. Based on Firebug console, the page (edit_1.php) is receiving the correct 'editadid'.
When i try to echo it out though, i get an 'Undefined variable' error though...anything y'all can see i missed here?
Here is the javascript:
var jsVariable1 = $(this).parent().attr('id');
var dataString = 'editadid=' + jsVariable1;
$.ajax({
url: 'edit_1.php',
type: 'get',
data: dataString,
beforeSend: function() {
},
success: function (response) {
}
});
Here is my php:
if(isset($_GET['editadid']))
{
$editadid = (int)$_GET['editadid'];
}
echo $editadid;
It's hard to help without seeing the code you're currently using.
In jQuery:
var jsVariable1 = "Fish";
var jsVariable2 = "Boat";
jQuery.ajax({
url: '/yourFile.php',
type: 'get',
data: {
var1: jsVariable1,
var2: jsVariable2
},
success: function (response) {
$('#foo').html(response);
}
});
Then your PHP:
<?php
$jsVariable1 = $_GET['var1'];
$jsVariable2 = $_GET['var2'];
// do whatever you need to do;
?>
<h1><?php echo $jsVariable1; ?></h1>
<p><?php echo $jsVariable2; ?></p>
It's fairly generic... but it'll do stuff.
An important thing to note, and a very common mistake, is that any additions you make to the DOM as a result of an AJAX request (i.e in this example I've added a h1 and a p tag to the DOM), will not have any event handlers bound to them that you bound in your $(document).ready(...);, unless you use jQuery's live and delegate methods.
I would say instead of looking for an example you must understand how ajax works. How can you hit a URL via ajax and pass query parameters along with them (these can be the javascript variables you are looking for) How server side response is captured back in javascript and used into manipulate existing page dom. Or Much better you can post what you have tried and somebody can correct it for you.

How can I implement a jquery ajax form which requests information from a web api via a php request?

I'm trying to implement a simple api request to the SEOmoz linkscape api. It works if I only use the php file but I want to do an ajax request using jquery to make it faster and more user friendly. Here is the javascript code I'm trying to use:
$(document).ready(function(){
$('#submit').click(function() {
var url=$('#url').val();
$.ajax({
type: "POST",
url: "api_sample.php",
data: url,
cache: false,
success: function(html){
$("#results").append(html);
}
});
});
});
And here is the part of the php file where it takes the value:
$objectURL = $_POST['url'];
I've been working on it all day and can't seem to find the answer... I know the php code works as it returns a valid json object and displays correctly when I do it that way. I just can't get the ajax to show anything at all!!
...data: 'url='+encodeURIComponent(url),

Categories