I'm not sure how to best explain this so bear with me.
I have the following in some javascript (using jQuery)
$(document).ready(function(){
$("#myForm").submit(function(){
var request = $.ajax({
url: "myPage.php", //sits on localhost
crossDomain: true,
type: "POST",
data: {
var1 : "foo",
var2 : "bar"
}
});
request.done(function(res){
alert("DONE");
});
request.fail(function(jqXHR , textStatus){
alert(textStatus);
});
}
MyPage.php uses SoapClient to call a service. And then return some data.
I can directly call MyPage.php from the webBrowser and get a result (failed because there is no POST data).
If I try to make the MyPage.php call from the AJAX and put a breakpoint in my service, I see the service being called and returning a value.
But the request.Fail ALWAYS calls. It appears that it just directly jumps to that fail before the service can even finish.
How would I remedy this?
I may be wrong but aren't you missing the colon between data and the data map? and then you should be doing key : value not key = value inside the map.
Your syntax is wrong, it should be:
data: {
var1: "foo",
var2: "bar"
}
I do not know why, but apparently changing it from
$("#myForm").submit(function(){
And moving it into function SubmitForm(){...}
and then making the call from
Fixed the whole thing. Thanks for the advice....
Related
I've got an AJAX script in my index.php of my CI application. I am just trying to return a simple string at this point for my testing. I'm using the following code for this:
<script>
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'index.php/loader/opc_client',
dataType: 'json',
cache: false,
success: function(data) {
console.log(data);
$('#opc-results').html(data.test);
}
});
});
</script>
The url in this call is a standalone file with it's own controller. When I access this file directly in the browser it's loaded normally and returns expected results. Following is my PHP code:
<?php echo json_encode("test"); ?>
I can see the post results in Firebug after the function is fired but the Firebug window just displays "an empty string" under the POST in console view.
Any clues? I'm not understand this...
UPDATE: If I console.log('success') in the success parameter of the AJAX call, it logs it properly so for some reason data is empty
you shouldn't just json_encode a string although technically php can deal with a string as an array but I guess in this case things get weird. Just wrap it in an array, and when youre done testing you'll probably be better off using key value pairs as it makes thing on the client side easier to deal with, ie obj.property.
try echo json_encode(arrray('test'));
I try to post an JS object to PHP, but the PHP says nothing.. It looks like it don't recognize the POST...
Here is the JS :
$('.send').click(function() {
var Scommand = JSON.stringify(command);// Command is my JS obj
if (commande.type) {
$.ajax({
url:'test.php',
context:$(this),
type:'POST',
data:Scommande,
success : function(data){
commande = {};
window.location='test.php';
}
});//End Ajax
}
else {'PLz specify a type');}
});
And my PHP :
<?php
echo $_POST['type'];
?>
It returns : Notice: Undefined index: type in /Applications/MAMP/htdocs/BackOfficeDavid/test.php on line 2
Like nothing go throw the POST ... Any clue ?
Disable/remove window.location='test.php';.
What might be happening is that the success callback is called, redirecting you to the test.php after everything is actually done. This would be a plain move to test.php, by GET, so there will be no parameters in $_POST.
Actually, better yet, replace window.location='test.php'; with alert(data), so you'll see what is returned. Otherwise it will seem like nothing happened since the ajax just completes successfully and silently in the background.
The problem is that you're converting the command to a string. The data on the ajax call has to be a JSON object, not a string. What you can do is pass the command variable directly:
var command = { type: "whatever" };
$.ajax({
url:'test.php',
context:$(this),
type:'POST',
data: command,
success: function(data){
command = {};
window.location='test.php';
}
});
You probably mean
data:'type=' + encodeURIComponent(Scommande),
instead of
data:Scommande,
This will URL-encode the Scommande variable and assign its value to the type POST variable.
Alternatively, you can rely on jQuery to do that for you by using
data: {'type': Scommande},
(PS. Not sure if the variable is meant to be named Scommand or Scommande. You probably have a typo somewhere)
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.
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.
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".