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
Related
I have a link, delete, that removes an item from an array, and then removes a row from a table on my html page.
It runs the ajax request first to amend the array, then removes the row. If for some reason the ajax request was to fail then the html table row would still be deleted I think.
Is there a way to make sure subsequent code afer the ajax request only runs if it is successful? I tried moving it into the success function but then it didn't run at all..
This is how I have it set up at the moment...
$(document).ready(function () { //delete
$(document).on("click", "a[class='del']", function () {
var ID = $(this).attr("id"); //<----- get the ID of the column
$.ajax({
//contentType: "text",
url: 'proDel.php', //the url you are sending datas to which will again send the result
type: 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data: 'val1=' + ID, //Data you are sending
success: function (data) {
// do nothing, array was amended in php file
}
})
//Code here that deletes the table row(runs whether the array was changed or not!!
})
})
The problem might be that you are not returning valid JSON.
You were correct in thinking that you should move the code that deletes the table row into the success callback. You say you tried that, but the success callback was not executed.
Since you specify dataType: 'json', jQuery will attempt to parse the response body into a JavaScript object (or array or null). If the response body cannot be parsed (because it is not valid JSON), jQuery will call the error callback, rather than the success callback.
An empty response body is not valid JSON. You must at least return "null". Or if you do not plan on returning any data, just change to dataType: 'text'.
Move the code that deletes row to success callback.
$.ajax({
//contentType: "text",
url : 'proDel.php', //the url you are sending datas to which will again send the result
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// Code here that deletes the table row
}
});
Try you ajax with success parameter as well as an error to see if there is a problem, hope this helps..
$(document).ready(function (){
$(document).on("click", "a[class='del']", function(){
var elem = $(this); //to make $(this) accessible in you success callback
var ID= elem.attr("id"); // get ID of the column
$.ajax({
url : 'proDel.php', //the url you are sending datas to
type : 'GET', //type of request, GET or POST
dataType: 'json', // jQuery will parse the response as JSON
data : 'val1='+ID, //Data you are sending
success : function (data){
// success, Code here that deletes the table row , do something with 'elem'
},
error: function(x,e) {
//log error if any
console.log("failed with: "+x.status+", e="+e+", response="+x.responseText);
}
});
});
});
Since jQuery 1.5 you may use chainable methods of object returning by jQuery.ajax(). In your case (ensure executing code on ajax request completion) you have to use deferred.always() method. Somehow like this:
$.ajax({
...
})
.always({
//Code here that deletes the table row
})
In earlier jQuery versions you have to use complete option (handler) in jQuery.ajax() for your purpose.
First thing is that when looking at the ajax request success does not mean that the request returned a correct/true value. That just means that there was a response from the other end.
That tripped me up during my first couple times working with and debugging ajax calls.
I don't know if that's part of what is not working for you here, but something to consider.
Secondly, and to answer your real question, you'll have to put a function call in the success branch, else it might never get called, or be called at a non-deterministic time (the whole nature of an asynchronous call).
var a = function(){
$.ajax({
success : function (){
// code here fires if there is a response to your ajax request
// you should put in an function callback here to check the response for
// your success conditions.
// if your conditions are met, make the changes that you need to
b();
}
failure: function() {
// code here fires if the ajax request receives no response
}
})
// any code here will fire immediately after the ajax call is fired.
// it will not wait for the ajax response.
}
var b = function(){
// stuff you want to do according to the ajax response parameters
}
I am trying to get a text value('selected crate') from the server using an ajax call. Ajax call is:
var selected_crate ='';
$.ajax({
url: OC.linkTo('crate_it', 'ajax/bagit_handler.php')+'?action=get_crate',
type: 'get',
dataType: 'text/html',
success: function(data){
selected_crate = data.responseText;
$('#crates option').filter(function(){
return $(this).attr("id") == selected_crate;
}).prop('selected', true);
},
error: function(data){
var e = data.responseText;
alert(e);
}
});
And the server side code snippet is:
case 'get_crate':
$msg = $bagit_manager->getSelectedCrate();
print $msg;
break;
I want to do something upon success but this call always end up in error handler. If there were complete handler, it would go in that handler. But I want to use both success and error handlers because I want to
Send error response if something is wrong from the server side
Do something on success in the client side
I am struggling to achieve this. Why this call always end up in error handler and how can I actually send an error response with regard to this call that would end up in error handler if any error occurs otherwise success response?
If the URL is right then try this:
dataType: "html"
See: http://api.jquery.com/jQuery.ajax/
see if in error handler data is been retrieved or not if data is been retrieved correctly it means your data-type is not matched for response in ajax call [see your server code that it must be returning some extra values in that case]
url: OC.linkTo('crate_it', 'ajax/bagit_handler.php')+'?action=get_crate',
in place of this try directly url like
url: www.yoursite.com/ajax/bagit_handler.php?action=get_crate
i think it will help you to get Sucess.
I would like to create an app that will send out a get request, then take the response and display it on the page,
this is part of my learning process, ultimately i would like to have the response be parsed and turned into
elements etc. but for now i am having trouble accessing the information within the response.
How can i alert() any of the results in the response?
the results of the script below ranged from undefined, to [object ojbect]
<script type="text/javascript">
var bbz;
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "MyDomain - its defined and on the web",
success: function(response) {
bbz = response;
alert(bbz.length);
alert(bbz);
alert(bbz[0]);
}
});
</script>
It looks to me like you are expecting a JSON response...
I am assuming this because of the way you are accessing properties of the response object -
bbz = response;
alert(bbz.length);
You'll want to set your dataType to "json".
If you set the dataType property to html, you should be able to simply return HTML.
You set dataType: "jsonp" which attempts to parse a jsonp object out of the data that is to be returned. However, what you really want is the markup that is in the file you are requesting data from. In order to do this, you must state the correct return type, so that the AJAX knows what data to give you, i.e. you tell the AJAX how to parse the data.
My AJAX request to pings the server, and the URL but returns an error because it doesnt like the '<' as the open tag for the php script.
AJAX script.
$.ajax({
url: "data.php",
type: "POST",
data: JSON.stringify({"data":transaction}),
dataType: "json",
success: function(data, textStatus, jqXHR){
alert("success");
currentProcesses -= 1;
$("<span>").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
},
error: function(jqXHR, textStatus, errorThrown){
alert("error with ajax call "+textStatus+" "+errorThrown);
}
});
php script
<?php
$win = $_POST['data'];
?>
Am I using the wrong flag settings for the AJAX call?
The body of your POST request is encoded as application/json instead of application/x-www-form-urlencoded.
You aren't doing anything to make the request say that the data is encoded in JSON and you aren't doing anything in PHP to try to parse JSON.
As a result, PHP fails to populate $_POST, because the data is in the wrong format.
The solution is: Don't send JSON. Just give the data property an object as its value, and jQuery will serialise it to application/x-www-form-urlencoded data for you.
data: { "data": transaction },
(Assuming that transaction is not a complex data type (like an array or object).
Additionally, the body variable is undefined. You should either use a string (to make it a selector: "body") or pass the body element directly: document.body.
Is it choking on what it's receiveing? Try this...put an id attribute on your span tag, and reference that.
In the page:
<span id="someName">...</span>
In your ajax call:
$("#someName").html(...
Try making the span more unique using class or id like
<span id="output"></span>
and try this.
$("#output").html("Ajax Call Complete. Releasing lock for process").appendTo($(body));
}
I have an AJAX request (using JQuery) that calls a PHP script which does some database business. The request code is as follows:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
alert(output);
}
});
However, I wanted to see if there was a way to also (in addition to the unchanged output string) return a status. It can be as simple as an integer. The point is I want to disable a button (with Javascript) if the PHP script for any reason fails to connect to mySQL, but I still want the PHP scripts output exactly as it would be.
I tried the error option:
...
success: function(output){
alert(output);
},
error: function(output){
// do something
}
but I do not know how to make PHP display an error and continue on the rest of the script. Again, I don't want to tamper at all with the output string.
In pseudo-code, I'm looking for something like this:
$.ajax({
url: "script.php",
data: { value: value
},
type: 'post',
success: function(output){
if(output.status == 0){
alert(output);
}else{
// do something else
}
}
});
Is anything of the sort possible? Thanks for any and all help!
I usually return data from the server in JSON format. This way I can return as many different types of data as may be needed by the success function in javascript.
basically in PHP you would do something like
$response = new stdClass();
$response->error = 'Could not connect to Mysql';
$response->message = 'Some other text';
echo json_encode($response);
in JQuery, the ajax() method would automatically detect that the response is json and parse it into a javascript object, so you could access like this
if (typeof response.error !== undefined) alert(response.error);
for more on that look at dataType argument for the ajax() method in the jQuery documentation.
Yes. You can use HTTP status codes:
header('HTTP/1.1 500 Internal Server Error');
And use jQuery's statusCode property for jQuery.ajax():
$.ajax({
// stuff
statusCode: {
500: function(data) {
alert('Something went wrong!');
}
}
});
If your needs extend beyond what HTTP can offer, you can just return a status code within your data and process it in the success function, switching on data.status.
If I haven't misunderstood your question...
What I usually do is set the datatype of the AJAX call to 'xml' and output an xml from my PHP script. So I get multiple values in result. I usually make these attribute values.
<result status="success" something="etc" />
// vs.
<result status="failure" error="1" />
// consider 1 as the DB error
With this approach you might need to use the # tags in some PHP functions to prevent outputting the default errors.