AJAX/JQUERY/PHP issue - php

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".

Related

No response from PHP Script

Absolutely new to PHP and so far it isn't pretty.
Anyway, I'm trying to pass a variable over to a PHP script, do a couple things with it, and pass it back to my Javascipt code.
Here's where I pass it off to PHP:
var src=encodeURIComponent("http://www.someonlinesite.com/file.swf");
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response)
}
});
and here's the script:
<?php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>
I'm trying to pass the URL of a .SWF video file over to a small PHP script that will use getImagesize() to figure it's dimensions and pass them back.... but I'm not seeing anything in the response and the alert isn't firing.
What's going wrong?
UPDATE:
I've updated the code with the most recent - according to the advice from some nice SO members. When I hardcode the $src variable and navigate directly to the test.php it echoes everything perfectly. So, it looks like the PHP is working. However, it appears like either the callback is never firing or the PHP file isn't returning the data. In the console there still isn't anything in the response.
You need to concatenate your url string parameter in get():
$.get('test.php?src=' + src, function(data){
alert(data);
});
And also, your src variable begins with a double quote and is closed with a single quote. That will cause issues.
var src="http://www.someonelinesite.com/file.swf";
Also, it's probably a bad idea to do this via $_GET since you are passing a URL. $_POST would be better or encode the URL before you pass it. The current url you are passing right now would look like this in a browser:
http://www.mysite.com/test.php?src=http://www.someonelinesite.com/file.swf
That's not pretty. Using encodeURIComponent(), your whole URL will end up looking like this:
http://www.mysite.com/test.php?src=http%3A%2F%2Fwww.someonelinesite.com%2Ffile.swf
Edit to $.ajax
$.get above would work just fine, but going with the implementation of $.ajax works too:
$.ajax({
url:'test.php',
type: 'GET', //Add the type
dataType:'json',
data: {'src': src}, //Add the data, leave it out the url
success:function(data){
alert(data)
}
});
Try this :
In Jquery :
var src="http://www.someonelinesite.com/file.swf";
$.ajax({
url:'test.php?src='+src,
dataType:'json',
success:function(response){
alert(response.size);
}
});
In php
$src=isset($_GET['src'])?$_GET['src']:'';
$size=getimagesize($src);
echo json_encode(array('size'=>$size));
?>

ajax always going to error

Im trying to learn to use ajax at the moment, but unfortunately I cannot get it to success.
$('.engineering-services').live('click', function() {
$.ajax({
url: 'index.php?route=information/information/homepage_info',
type: 'post',
data: {info_description : 'test'},
dataType: 'json',
success: function(json){
alert('pass');
},
error: function(json) {
alert('fail');
}
});
});
Here is the php function...
public function homepage_info() {
$json = array();
if (isset($this->request->post['info_description'])) {
echo $this->request->post['info_description'];
echo '<br /> test2';
}
$this->response->setOutput(json_encode($json));
}
However this always makes a fail alert instead of a pass one.
Am I missing something obvious here?
EDIT: Its finding the function ok, as in the console it is giving the correct response,
i.e.
test
test2
Thank you
If your dataType is set to json, anything returned that is not JSON will cause the ajax call to error out. Try sending some json back to the script... {"test":"abc"} or similar. I see a couple of calls to echo in your code, for example.
Not just this, but any PHP error/warning/notice printed to the browser will break calls.
Hint: you can generate valid JSON from PHP variables using json_encode().
You cannot combine an existing query string with data. Something like this should work (or at least be syntactically valid):
$.ajax({
url: 'index.php',
type: 'post',
data: {information:'information/information/homepage_info',info_description:'test'},
dataType: 'json',
success:function(json){
alert('pass');
},
error:function(json) {
alert('fail');
}
});
Also as was mentioned, anything that is not json will potentially cause an error, so you not echo those html components ... if anything, you print them.
Also, as a side note your dataType should be done server side with a header('Content-type: application/json'); declaration in index.php rather than in your jQuery script. Its guaranteed to be recognized as json that way, and also less Javascript code.

JQuery Ajax call failing but service is hit

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....

JS Ajax calling PHP and getting ajax call data

I have a standard javascript ajax call where I'm setting the data: to json data.
$.ajax({
type: "POST",
url: BaseUrl + "User/Login",
//url: BaseUrl + "User/Limit/1/2",
data: '{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
},
});
I was trying to get the data in php $_POST["data"] this doesn't work.
However, data: 'test={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}' works.
I was wondering is it possibly my framework or anything like that preventing $_POST["data"] from working or is this just not possible at all? Or is there something else I could use to get that data?
EDIT:
So the framework YII and the extension Restfullyii has a method to get the data it is using one line
return json_decode(file_get_contents("php://input"), true);
Which is getting all the data without the need for data= or {data: However it seems to be returning an array so Im accessing my properties like $data["userName"] where a true json object should be $data->["userName"]. Correct me if I'm wrong on any of this am I getting array in this case because I'm really sending a json string? versus a json object?
EDIT x2:
So php is making it an assoc array because it is sending true to the json_decode..
I think problem with your code is in the line where you set data: '{....}'.
It should be in json format in order to be passed properly (though it also could be in string format but you'll need to parse it on the server side)
The code below should be working right:
$.ajax({
type: "post",
url: BaseUrl + "User/Login",
data: {"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"},
success: function(data){
console.log(data);
},
error: function(request){
console.log(request);
}
});
On the server side try: $_POST['apiKey'] $_POST['appIDGiven'] and so on.
data option must be an object or serialized(e.g. "name1=value1&name2=value2") string.So you need to pass like this:
data: /*object*/{data:'{"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}'},
// ^-----this is added for $_POST["data"]
or like:
data: /*serialized string*/'data={"apiKey":"c7089786-7e3a-462c-a620-d85031f0c826","appIDGiven":"200","userName":"matt2","password":"pass"}',
// ^-----this is added for $_POST["data"]
First, the data sent must be a JSON object and not a string. Remove the quotes.
Also, in your server-side, you'll better decode the input $_POST['data'] with json_decode() (see documentaion)

POST a javascript objet to a PHP file

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)

Categories