I need to build a cross domain script, I decided to use jsonp instead of CORS (I found it easier)
This is my JS client code:
function logResults(json){
alert(json);
}
$.ajax({
url: "https://my-server-domain.com/api_gt/test/new2.php",
dataType: "jsonp",
jsonpCallback: "logResults"
});
This is my PHP code (new2.php)
<?php
$arr = array ('a'=>1,'b'=>2,'c'=>3,'d'=>4,'e'=>5);
echo json_encode($arr); // {"a":1,"b":2,"c":3,"d":4,"e":5}
?>
When I execute this I got
https://my-server-domain.com/api_gt/test/new2.phpcallback=logResults&_=1498645452001
returning 404 (not found)
But when I call for: https://api.github.com/users/jeresig instead of https://my-server-domain.com/api_gt/test/new2.php then everything is fine.
Note: when I enter https://my-server-domain.com/api_gt/test/new2.php I see the returned json, as I should (so the code is working)
Do I miss something ?
Maybe I miss something on my server side, some kind of header for example ?
Maybe there is something wrong with my json ?
I have already spent 2 days on this, and I would appreciate any hint.
jQuery.ajax({
type: "POST",
"dataSrc": "Data",
url: "https://my-server-domain.com/api_gt/test/new2.php",
dataType: 'json',
success: function(res) {
logResults(res);
}
});
function logResults(json){
alert(json);
}
Related
I have had this error for multiple days now, I have tried searching this error up but whenever I search this error up it gives a different reason for the error and when I try to add what other sites say it doesn't work which is why I am asking here as I don't see what else I can do.
I am trying to pass a variable from JavaScript to PHP but it is not working and I have no idea why.
Here is my JavaScript code:
<head>
<script type="text/javascript" src="jquery.js"> </script>
</head>
<script>
var variable = "hello";
console.log(variable);
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function() {
alert("Success");
}
});
</script>
Here is my PHP code:
$variable = $_POST['pass'];
echo($variable);
Everything seems to work perfectly. It writes the variable to the console, it comes up with the alert saying success. However I get an error message saying: 'Undefined array key "pass"'
What is causing this? Thank you?
Edit: People have told me to use isset, I have added that it removed the error however it still does not echo the PHP variable, meaning it is still not been passed to PHP, I am still trying to find how to fix this.
Your front end code looks OK, but I don't know your target PHP environement, but maybe your environnement doesn't accept formData.
By default, jQuery send ajax POST data as formData.
Try to send data as JSON
$.ajax({
url: "ajax.php",
type: "POST",
data: JSON.stringify({pass : variable}),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data){alert(data);},
});
And then you will probably have to adapt your php code:
$json = file_get_contents('php://input');
// Converts it into a PHP array
$data = json_decode($json, true);
$variable = $data['pass'];
echo($variable);
Can you please use the developer tools in chrome browser that will help you to find if data is properly sent to php file.
Also you can try $_REQUEST instead of post just to check what data is coming in REQUEST as it works for GET & POST both. If it still does not help you.
Also can you please use
data: {'pass':variable}
instead of
data: {pass:variable}
let me know if it works for you.
If you get this error in your ajax.php file which you Post the data to it, I say it's normal because when you open that file (ajax.php) it's like that there is no $_POST['pass'] because you just opened that file without running JS to send data.
If you want to receive data that you send you can do this:
Your JS code I call this file index:
var variable = "hello";
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(res) {
alert(res);
}
});
The PHP file:
$variable = $_POST['pass'];
echo($variable);
Then if You open up that index file, after running the JS code it'll send that post data to your PHP file and your PHP file will echo that, then the value will store in that res variable which when every thing went fine, you can see the alert of that res in the page (index file).
Notice that as I said you can't open up the PHP file lonely because it doesn't receive a post data on its own, it is normal for undefined to return.
Re: #puckloe your code is working, php echo wouldn't be printed with ajax(correction echo is working but wouldn't show on page if you don't print it with JS too), you have to catch the response in ajax success function ( like success: function(response) ) and print or alert the response --> success: function(response) { alert("hi look this is echo from php"+response) }
you ajax code should look like
$.ajax
({
url: "ajax.php",
type: "POST",
data:{pass : variable},
success: function(response) {
alert("hi look this is echo from php" + response);
}
});
I have this encode in JSON format as returned data:
{
"error": {
"msg":"Concurrent verifications to the same number are not allowed",
"code":10
}
}
and I want to access msg so I wrote the javascript as:
$("#buttonPhoneSubmit").click(function(e) {
$("#verifyForm").show();
e.preventDefault();
$.ajax({
type: 'post',
url: './process.php',
data: $('form').serialize(),
datatype:'json',
success: function (data) {
$('#error_message').html(data.error.msg);
}
});
but it said the data is undefined. Can someone tell me what's wrong with the code?
Thanks!
As Roy said, you have datatype: 'json' instead of dataType: 'json'. So I suspect jQuery isn't parsing the JSON for you.
While you could change it to dataType: 'json' instead, the better approach is to update the PHP file to send the Content-Type: application/json header with the response:
// In the PHP, prior to sending the body of the response
header('Content-Type: application/json');
...and remove datatype: 'json' from your ajax call. jQuery will see the content type and parse it for you, at which point your code should work (assuming the page return returns the JSON you've quoted).
I am trying to to extract a Json response in jquery sent from a php file.
This is the .js code:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
This is the response from the php file:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
I have tried all combinations I can think of in both files, but nothing seems to work. It is a simple check for a username in the database. If I console log the data I get from the response, I get this:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
So the info is there, but how do I access it? I have tried several syntaxes found around the internet, but no luck so far. I seem to recall that a json response only can contain valid json, so is the problem the html? I don't think I can avoid this due to the structure of my application, so hopefully it is possible to access the json with my present structure.
in you Ajax
EDIT:
change
datatype:"json",
the case of parameter name was not respected, the t must be T
dataType:"json",
now retry please
$.ajax
({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
dataType: 'json',
data: {'userCheck': username},
success: function(data)
{
// Check if username is available or not
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
in PHP
simply that, and don't forget to exit; to avoid include html page in your json response !
This is the code coming after the }".... who break your json output
and make it unreadable by javascript (worste, it simply break your javascript !)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
When you're responding to an AJAX call, you should just return the JSON response, not the HTML of the page. Add:
exit();
after this code so you don't display the HTML after the JSON.
In the JS code, use if (data.username == 'available') to tell whether the username is available.
The other problem in your code is that you have a typo here:
datatype: 'json',
It should be dataType, with an uppercase T.
You can also put:
header("Content-type: application/json");
before echoing the JSON in the script, and jQuery will automatically parse the response.
Also you can set request headers in your jQuery ajax call beforeSend function like follows
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Accept', 'application/json');
}
So you're strictly declaring the data type to be json
I have the following jquery ajax request:
jQuery.ajax({
url: serverAddress+'php/product.php',
type: 'GET',
jsonpCallback: "callback7",
dataType: 'jsonp',
data: sendInfo,
success: function(result)
{
alert(result);
//do something
},
error:function(jqXHR,msg,errorThrown){ alert(msg+" : "+errorThrown);}
});
on the server side the script is:
$callback = $_GET['callback'];
//do something
$result = //something
echo $callback.'('.json_encode($result).')';
I get the following error from the ajax call:
parseerror : callback7 was not called
I looked up this error but couldn't find anything relevant, either in SO or in google...
Hope you can help me.
Thanks!
EDIT:
I eventually solved the problem by transforming it into a regular json request.
I'll be happy to know what could be the problem ans solution nevertheless.
Try adding these name value pair as jsonp:false & crossDomain:true in your js file. And in your server side remove the line $_Get['callback'] and add echo $callback.'('.json_encode($result).')' and alse set $callback='callback7'
I'm sure this is a basic syntax error but I'm trying to make a rest call using jQuery mobile ajax (code below) and as far as I can tell the ajax is not triggering.
function triggerCall() {
alert("function triggered");
$.ajax({
type: "GET",
dataType: "jsonp",
url: REST Url,
success: function (data) {
alert(data);
}
});
Any help would be appreciated
if you're actually writing url: REST Url, then you must change it to either a var, or a string.. that would be a problem
I believe that if you're using JSONP, you need to specify the callback in the $.ajax request and then again in your REST file return. Here is an example of what I've been using succesfuly (It's not perfect though, I'm sure).
$.ajax({
url: 'www.domain.com/string/to/your/REST/api',
data: {
dataToBeSent: variable,
dataToBeSent: sessionStorage.getItem('local/session Storage'),
dataToBeSend: "or a string"
},
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
success: function(data){
alert("Huzzah!");
},
error: function(){
alert("Boohisssss");
}
}); //end ajax call
And then in the url, I'd place this code at the bottom of the file:
header("Content-type: application/json", true);
echo $_GET['jsoncallback'] . '(' . json_encode($data) . ');';
exit;
Where data is a array that is JSON encoded, using json_encode() in PHP, and then wrapped up in a callback function (the $_GET['jsoncallback'])
Like I said, it's not perfect, but it's been working for me.
Check for errors in browser console. eg. in chrome menu>tools>javascript console.
Also recommend adding an error handler to your ajax call: http://api.jquery.com/error/
Determine which method, JSONP or CORS, to use for your restful ajax calls: So, JSONP or CORS? .