//MAKE AJAX CALL TO REPOPULATE TABLE
var newData = 'page_number=1&type=2';
$.ajax({
type: 'POST', // HTTP method POST or GET
url: 'http://www.myurl.net/form_validate.php', //Where to make Ajax calls
dataType:'text', // Data type, HTML, json etc.
data:newData, //post variables
success:function(response){
//REFORMAT UPON SUCCESSFUL AJAX CALL
alert(response);
},
error:function (xhr, ajaxOptions, thrownError){
alert(xhr + " " + ajaxOptions + " " + thrownError); //throw any errors
}
});
All I've put in my PHP file is:
<?php echo "test"; ?>
When I go straight to that file, it echoes 'test.' When I try to run the AJAX function on the click of a button it gives me the error:
[object Object] error
in an alert window. I've put the absolute URL to the file because I was thinking that the relative linking I was using was wrong but it now seems like it's some other issue. Am I overlooking a simple syntax error? Sorry if this is super basic but I can't seem to figure this out after working on it for a really long time. Thanks for your help.
The problem is your absolute url . Some browsers have problems dealing with absolute urls, consider it as a cross-domain request and block it even if it's not a cross-domain request. You should try with relative url instead
The problem might be in the url, try with relative path instead of absolute.
You named the file was in the same folder as the .js file, so try
url: '/directory_path_to_the_same_folder_as_the_JS_file/form_validate.php',
Try using done with jQuery.post instead.
For example:
jQuery.post('form_validate.php', data).done(
function(data, textStatus, jqXHR) {
alert(jqXHR.responseText);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert(jqXHR.responseText);
}).complete(function() {
// Common code when request completes
});
If your error is [object Object] error NOT FOUND then the reason is
the specified url in AJAX is not correct.
If your error is [object Object] error INTERNAL SERVER ERROR , its
because of the error in your server file ie the php file ,error like variables not defined correctly etc..
Some times error may occur due to cross domain, if you have not
specified headers when in case your php file is not in the same
domain
Hope this helps
Thank you
function abc(){
var ret=true;
$.ajax({
type: 'POST',
url: 'send_password.php',
data: 'mail_to=mymail&new_password=pwd',
async:false,
success: function(response){
},
error: function(r){
ret=false;
}
});
return ret;
}
alert(abc());
Have a look at this testfiddle
Related
This command works great if I call it during page execution
exec('run.exe -something', $response, $status);
But I have a button on the page that executes the same command via AJAX:
// Attempt a call to change the password
$.ajax({
url: 'actions/runcommand.php',
type: 'POST',
data: {
cid: cid,
},
dataType: 'json',
success: function(msg)
{
if (ajaxErr(msg) return;
// Show success message
showMsg('success!');
},
error: function(jqXHR, textStatus, errorThrown){ajaxFail(jqXHR, textStatus, errorThrown)}
});
I've verified the two are executing literally the same string whether I do it in my code or via the AJAX, but the AJAX initiated one is returning an error code instead of functioning. The value of status is 1 which is a generic error so I have little to go on.
I looked around and found one similar post, but they solved it by removing https from the ajax command. If I do that the browser blocks it with scary messages.
This is running on a local machine which attempts HTTPS but fails because it's a self-signed cert or something. I turned off https redirection for the site, but that made zero difference. Not sure what it's unhappy about... please help!
if (ajaxErr(msg) return;
Error handling shouldn't be done in the success callback function. You can remove this or modify what this function is doing.
If you're requesting the URL from a different directory, make sure your URL parameter uses a leading slash for the root directory:
url: '/actions/runcommand.php',
Try this and see if there's still a generic error:
$.ajax({
url: '/actions/runcommand.php',
type: 'POST',
data: {
cid: cid,
},
dataType: 'json',
success: function(data, status) {
console.log(data);
console.log(status);
showMsg('success!');
},
error: function(jqXHR, textStatus, errorThrown) {
ajaxFail(jqXHR, textStatus, errorThrown)
}
});
Ok folks, this had all the signs of a boneheaded mistake and that's what it was. I'm leaving it here for posterity because it's an easy mistake to make and I saw other people ask similar questions with no good answer.
The SOLUTION was that my AJAX files were in a SUBDIRECTORY and that means when they executed the command the output which was trying to export to a subdir of the root was trying to find that subdir in ANOTHER SUBDIR. Sheesh!
I have the below function that I used in two different pages and worked perfectly in both cases. Suddenly my pages stopped updating and I got the error $.ajax not a function.
function update_report(data) {
var request = $.ajax({
url: "report?poids="+data,
type: "GET",
dataType: "html"
});
request.done(function(msg) {
$("#yw2").html(msg);
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus );
});
req ="a";
}
I then changed the $ to jQuery. Then it started sending AJAX requests but it didnt get the relative URL. Like I was generating the request from a page like /index.php/link1 and my code was sending request to /index.php/report rather then /index.php/link1/report
So, then I changed my url: to "link1/report=?"+data then it started sending request to the right page but couldnt update the response as it didnt find the div #id. Got error
TypeError: $(...) is null
What can cause all this issue and how to fix this? And why $.ajax suddenly stopped working, though I didnt make any changes?
JQuery can be not available by $.ajax(). Check if jQuery.ajax() is available or you included jquery twice.
You should not require jquery manually. The best way to include jquery is using Yii::app()->clientScript->registerCoreScript('jquery'). Path for library is set in config/main.php.
I copied this ajax call from another one that works and I can't figure out why it's not successfull. Here is the code:
$.ajax({
type: "POST",
url: "addTune.php",
data: {
database: setlist,
name: tune,
orderno: orderno,
midi: midi
},
error: function (e) {
alert("The PHP Call failed! hmmm");
alert(e.status);
},
success: function (response) {
alert(response);
}
});
I get the error function every time. Are there any blaring typos or other stupid mistakes?
Edit: trying to chase down the error with:
$.ajax({
type: "POST",
url: 'addTune.php',
data: {database : setlist, name : tune, orderno : orderno, midi : midi},
error: function(e){
alert("The PHP Call failed! hmmm");
alert(e.status);
$.ajaxSetup({
"error": function(jqXHR, status, thrownError) {
alert('error');
var responseText = jQuery.parseJSON(jqXHR.responseText);
console.log(responseText);
}
});
},
success: function(response){
alert(response);
}
});
});
Update: I was just able to add a row with the command line. any thoughts as to what I can do to try and narrow this down further?
i am no pro at this but maybe using single quote instead of double quotes? because i'm working on a project were i also have to do ajax calls and i use single quotes
i'm just suggesting something, not really good at this
If you get into the error callback then you have an error with the page you are calling and not with the js code. Check if the php page is reached. If it is check the php code if it returns a valid result.
From jquery DOCS.
error
Type: Function( jqXHR jqXHR, String textStatus, String errorThrown ) A
function to be called if the request fails. The function receives
three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a
string describing the type of error that occurred and an optional
exception object, if one occurred. Possible values for the second
argument (besides null) are "timeout", "error", "abort", and
"parsererror". When an HTTP error occurs, errorThrown receives the
textual portion of the HTTP status, such as "Not Found" or "Internal
Server Error." As of jQuery 1.5, the error setting can accept an array
of functions. Each function will be called in turn. Note: This handler
is not called for cross-domain script and JSONP requests. This is an
Ajax Event.
I am sending a json string using JQuery.ajax to a php page where I am trying to pull the array and mediate through the variables. For some reason, I can see the POST in firebug when I run the script but I when I attempt to get the parameters all I get is an empty Array(). I have been trying to figure this out for hours and am at my wits end. I moving from asp.net to .php so I am still a little fresh with my syntax, but this seems like it should be fairly simple.
Here is my code for the jquery send.
$('#form_add').submit(function() {
var serial_data = $(this).serialize();
$(".page_content").fadeOut("slow", function(){
$.get(uri_base +'/'+uri_cont+'/get_db_name/true/'+Math.random(), function(data) {
$.ajax({
type: 'POST',
url: uri_base +'/AJAX/add_record/'+data+'/'+Math.random(),
data: serial_data,
contentType: "application/json",
success: function(data){
$.ajax({
type: 'POST',
url: uri_base +"/"+ uri_cont +"/"+ uri_func,
data: data,
success: function(data){
alert(data)
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
},
error: function(xhr, ajaxOptions, thrownError){
alert(xhr.status);
alert(thrownError);
}
});
});
});
return false;
});
Ignore the first .get(), that just pulls back a variable to complete the next URL. The first.ajax() call sends the serialized form data to my AJAX controller and pushes into the db. The return from the controller sends back an Array of Objects that I converted to json.
if(isset($key)){
$data['add_msg'] = $this->model_ajax->add_record($table,$array);
$exploded_data = json_encode($data['add_msg']);
print_r($exploded_data);
exit;
}
From there the next .ajax() is supposed to send the data to my controller to pull back a view to display in the .pag_content div. I have tried echoing the json object, a for each loop to pull the keys out, and a myriad of other things. nothing ... I get either a JSON Invalid error (when trying to decode it), Just "Array()" output, or nothing at all when looping through them.
This is the controller code and the POST output that I am seeing in firebug...
echo $_POST;
$array = $_POST;
echo $array;
foreach($_POST as $key){
echo $key;
}
exit;
[{"id":"29","datetime":"2011-03-23 12:10:25","full_name":"Leroy Brown","email_address":"test#testing.com","password":"asdf","id_group":"0","id_sites":"0","active":"0"}]
before you output anything in php make sure you send the right content-type. The frameworks like JQuery and mootools tend to filter (as they should) with Accept charsets (you can see that in firebug)
header("Content-Type: application/json");
// could also be text/json, check the accept headers in firebug depending on your framework
:)
I am trying to use an ajax 'POST' call through the jquery $.ajax function to send data to a php file. For some reason the callback is a success but the data is not getting to the php file. Here is an example of the code:
In JS file:
$.ajax({ type: "POST",
url: "setData.php",
data: "myPOSTvar=myData"
success: function(){ alert("Data Saved"); }
});
In php file:
$var = $_POST['myPOSTvar']
...
$var ends up with a default value instead of the data it is sent.
Any ideas?
Sorry about the syntax errors...at work right now and don't have my code in front of me...the syntax is all correct in the actual script, just typed to quick when posting here...
Try this and see if you get any info.
$.post("setData.php", { myPOSTvar: "myData" },
function(data){
alert("Data saved");
});
I doubt it's a success, the url should be a string : url: "setData.php" .
I really doubt that piece of JS code is working as it should. POST and setData.php should be enclosed with quotes. Right now you should get some errors because "POST" variable is not defined and then because you're accessing a "php" property on a non existent object "setData".