Ok, so my Ajax call looks like this:
var poststring = "id_Client=" + id_client + "&id_File=" + id_file;
alert(poststring);
$.ajax({
type: "POST",
url: "addclpermission.php",
data: poststring,
error: function(xhr, textStatus, errorThrown){
alert("Error: " +textStatus)
}
});
Everything works fine until the $.ajax(). If I use alert(poststring) the output looks like this:
id_Client=7&id_File=32
Using firebug, I found out that the url "addclpermission.php" is actually requested, but then 'aborted'. The path is correct though, if I copy the url out of firebug and call it directly, no error is displayed.
The alert in the 'error' option returns "Error: error"
The file addclpermission.php:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = $_POST['id_File'];
$id_Client = $_POST['id_Client'];
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>
I'm pretty sure this code once worked and that I haven't changed that much.
Any ideas?
Thanks!
Edit: I don't think that the error is in the php script, I have multiple ajax calls to several php scripts, but all of them fail the same way.
Edit 2: Now it works! Well, at least half of it. The request is still aborted, but the data gets inserted in the database. But as I said, this isn't the only ajax call and the others still aren't working, and this one is aborted. So I'd really like to know what caused this error and how I can fix it for good. Thanks!
Does the data get inserted to mysql despite the error? If so, can you put echo on your addclpermission.php file to return 'success' and/or 'fail' for mysql_query()? How about stripping this php file to just echo "hello"???
First, I would try just requesting addclpermission.php in the browser and see what happens.
Then, if that works, what if you just make addclpermission.php contain some text, no PHP content at all. Then for each stage that works, gradually add content (so first the include, for example).
I think the error could be in dbonnect.php or addclpermission.php. Save this in addclpermission.php (make a backup of your current file) and browse to it directly:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = 1;
$id_Client = 1;
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>
Please let us know if it works or if you get an error.
When I do jQuery Ajax, I set the data as a Javascript object that jQuery then serializes. Do you have better luck if you provide data: property as an object like this:
data: {
id_Client: id_client,
id_File: id_file
}
I am pretty sure your problem is that you are not returning an expected dataType to the .ajax call, if you explicity set the datatype (json or text for example):
$.ajax({
type: "POST",
url: "addclpermission.php",
data: poststring,
dataType: "json",
error: function(xhr, textStatus, errorThrown){
alert("Error: " +textStatus)
}
});
Then just echo out the expected datatype, just so the server responds, then ajax will know the request was successful.
<?php
// if your dataType is json
echo json_encode(true);
// if your dataType is text
echo ' ';
// exit so the server can return the request
exit;
problem is a --> require_once
require_once("../allgemein/includes/dbconnect.php");
remove this line in a php and write all code here
but I don't know why ?
Related
This is what am trying to achieve, I have a function in controller that generates a random password and returns the same, on button click I want to capture the generated password and display it in the view (password field). Here is the jquery/ajax call:
$(document).ready(function(){
$("#generate_password").click(function(){
$.ajax({
type: "GET",
dataType: 'text',
url: "http://127.0.0.1/public/admin/content/manufacturers/generate_password",
async:false,
success: function(resp){
alert(resp); //this alerts BLANK
},
error: function(xhr, textStatus, error){
console.log(xhr.statusText);
console.log(textStatus);
console.log(error);
}
});
});
});
Controller function:
public function generate_password($length = 9)
{
return $password_str;
}
Is this the correct way to call controller method?
Why am I getting blank value on alert, even though when printed in php am getting correct value?
Coz it's in the admin area can that be the reason, don't think so but is there any interference because of tokens?
In most cases, it is going to work okay, however you can use json format(and just json_encode/json_decode will finish the job for you), not sending via GET method and some other modifications.
Are you sure that the url is correct, if you open it in your browser, what happens?
You have to echo the variable in your function in place of return. Because return returns the value to the caller whereas echo sends something to the browser. JavaScript will only understand data which is sent to the browser. So, edit your function code as follows:
public function generate_password($length = 9)
{
echo $password_str;
}
On the other hand you should be doing this over HTTPS rather than HTTP as mentioned by #rodamn
Well strange but changing the url from:
url: "http://127.0.0.1/public/admin/content/manufacturers/generate_password",
to this:
url: "generate_password",
did the trick and everything is working fine now :)
Thanks everyone for their valuable inputs.
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 am trying to edit a file on my server when a user clicks a button on my web page. I generate a table of buttons using php. STRING1, STRING2 and BOOL are variables I pass to my function. The editPlist() function I made is called and the test alert() shows. The problem is that the php file is to run. I am not getting any errors either. I can't seem to figure out what is wrong.
Sample HTML button:
1 : Round 1
The button click runs this script: (the PHP in the url line generates the address of the file I want to run.)
<script type='text/javascript'>
function editPlist(stage, dance, oldValue)
{
alert('test ' + stage + dance + oldValue);
$.ajax({
type: "POST",
url: <?php echo '"'.dirname(curPageURL()).'/PlistEditorFunction.php"' ?>,
data: {"var1" : stage , "var2" : dance , "var3" : oldValue},
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
}
In the external php file PlistEditorFunction.php, I try to log a fake error and load the variables, but the error never shows. this is the beginning of the php file:
$msg = 'test error message';
error_log('['.date("F j, Y, g:i a e O").']'.$msg."<br /> \n", 3, $phperrorPath);
if (isset($_POST['data']) and trim($_POST['data']) != '' ) {
$stage = trim($_POST['var1']);
$dance = trim($_POST['var2'])
$oldValue = trim($_POST['var3']);
}
I know that the php script will only be run if the domain name matches file where the ajax is being run from. The two files are next to each other so I know that this isn't the problem.
What can I do to fix this?
change this line
url: <?php echo '"'.dirname(curPageURL()).'/PlistEditorFunction.php"' ?>
to
url: 'PlistEditorFunction.php'
and see if it works
Several things look strange.
Please verify that the url you call is in fact what you think it is. In order to do that, use a console / inspector. I recommend firebug. When you make the ajax call, it will display the url of the page you're requesting with ajax.
If it is correct, then your url param is not the problem. Next I would look at the php file itself. Try throwing an echo statement in the php file so that way your ajax response can verify that its being run. whatever you echo in the file PlistEditorFunction.php will be the response param in the success function
success: function( response ) {
console.log(response); //should be the echo'd statement of PlistEditorFunction.php
}
After mwotton's comment, I figured out that ajax was undefined. jQuery was imported, so that wan't the problem. I found the answer was I had to change $.ajax to jquery.ajax.
Some hosts don't use "$" to denote jQuery. My web host uses "jquery" instead.
I've never worked with JSON before and it's not going well...
I have a PHP script that returns a JSON array(is that the correct term?)
The script returns:
{"items":1000,"mitems":0,"donations":0,"total":1000}
NOTE: The script also sets the Content-Type to application/json
Here is my front-end javascript to handle that response:
function ajax(){
$.ajax({
url: '../ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function( data ){
// data.responseText is what you want to display, that's your error.
alert(data.responseText);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
When that function is called I get an alert with the following message:
{"items":1000,"mitems":0,"donations":0,"total":1000}
If everything was successful, I should get an alert that says success, right?
Can someone please tell me what is going on here?
Thank you!
This is the least documented thing in jquery what you need to do is alert the actual error in order to debug it. so do the following:
function my_ajax(){
$.ajax({
url: '/ajax/goal_ajax.php',
dataType: 'json',
success: function( data ){
// success! :D
alert('success');
}, error: function(jqXHR, textStatus, errorThrown){
// data.responseText is what you want to display, that's your error.
alert(jqXHR+","+textStatus+","+errorThrown);
}
})
//progressBar.set('value',data.total);
//document.getElementById('txtCDInfo').innerHTML=txt;
}
So two things I've done:
Change the name of the function (ajax is kinda a bad name :S) and improved the error reporting.
You should be getting the alert "success" yes. So something is going wrong.
EDIT:
Just noticed another thing, I dont think "../" would be a great way to reference the url, usually its either "/foo/ajax" which will allow you to use this function on any page.
It could be that your PHP script returns an error status code and even though it prints out the correct result, it still fails. I tested your scripts on my system and I got the 'success' alert. Then I changed my PHP script to the following:
<?php
header('Content-type: application/json', true, 401);
echo '{"items":1000,"mitems":0,"donations":0,"total":1000}';
?>
Note that the third parameter of the header function sets the http response code to 401 - Even though the correct output is sent back to the client; officially, the request has failed because of that status code. After running this code, I got the exact same problem as you.
So in summary, there might be something in your script which is causing a non-fatal error which doesn't show in the output of the script.
Are you defining the MIME type in your HTTP response?
Try adding a Content-type header to the output of your script.
<?php
...
$output = json_encode(...);
header('Content-type: application/json');
echo $output;
...
?>
You can also try using the mimeType parameter in your $.ajax() call to override the response type.
http://api.jquery.com/jQuery.ajax
Are you running your PHP scripts under Apache or on their own (chmod u+x on the script)? You probably need to use a PHP framework such as Zend, CodeIgniter or CakePHP and define a controller action that handles your AJAX request to have a proper HTTP response.
As the guy above me said, you should be using the json_encode(); function in PHP then echo'ing that output.
Make sure you encode an array though:
<?
$send = array(
'items' => '1000',
'mitems' => '0',
'donations' => '0',
'total' => '1000',
);
echo json_encode($send);
?>
I'm writing a small function to get the URL of an image and save to locally to server.
Here's the AJAX call (confirmed it's sending the correct URL to "getimdbpic.php" with firebug)
$.get("getimdbpic.php", { posterURL: data.Poster, movieTitle: data.Title },
function(picData){
alert("Data Loaded: " + picData);
});
The problem I'm having is with my PHP.
$url = $_GET['posterURL'];
$title = $_GET['movieTitle'];
file_put_contents($img, file_get_contents($url));
I simply can't get the values that are being passed. The file_put_contents throws an error stating that the "File name cannot be empty". (referring to $url being empty)
Edit: Fixed the casing, still not receiving values.
You seem to be mixing up the case between posterURL in the Javascript, and posterUrl in the PHP.
Make sure you're using the latest JQuery. I saw a very bizarre bug like regarding values not getting sent that was fixed by an upgrade.
EDIT: Might want to try a fallback to standard $.ajax() since $.get() is just a wrapper around it:
$.ajax({
url: "getimdbpic.php",
data: { posterURL: data.Poster, movieTitle: data.Title },
type: 'GET', // this is default, but just in case
success: function(picData){
alert("Data Loaded: " + picData);
}
});
Typo in the casing here:
$url = $_GET['posterURL'];