jQuery AJAX - Not receiving JSON data when on localhost using XAMPP - javascript

I'm using this code:
$.ajax({
type: 'post',
url: "http://www.localhost/do_getmemes.php",
dataType: 'json',
data: {userid: userid, lastid: lastID},
success: function(data) {
console.log('bla');
console.log(data);
}
});
inside do_getmemes.php the post parameters are received successfully and the json is getting generated but I don't get it on success?? Console isn't showing anything. It works fine on the website but not when on localhost using XAMPP
It all works inside the php file, this is at the end:
file_put_contents('test.json', json_encode($array)); // file generated and not empty
echo json_encode($array);
What's the problem here?
EDIT:
AJAX usually works, I tested by getting simple string:
$.ajax({
url: "http://www.localhost/contact/text.php",
success: function(data) {
console.log(data) // got it
}
});

The problem were irrelevant warnings which were also sent through the API back and causing parsererror SyntaxError: Unexpected token < in JSON at position 0 error.
Besides fixing them this is the way to ensure the APIs wills till work:
Disable the warnings inside the PHP file:
error_reporting(0);
ini_set('display_errors', 0);

Related

Trying to pass variable from JavaScript to PHP using Ajax but got error " Undefined array key"

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);
}
});

Post not working in PHP function, even though var_dump in same function shows the data

I'm befuddled. I have a JavaScript function that posts to a PHP function. PHP says, "undefined index" on mPicker. Yet if I call var_dump within the same function mPicker is plainly visible.
I've also ran an alert client side in JavaScript to be sure the form data was serialized, and it too shows that mPicker indeed has a value. Yet this line in PHP returns the error:
$es=$_POST["mPicker"];
This is just short hand for all your sake. The longer version of the code tests for SQL injection.
And the error in xdebug:
The JavaScript code:
$.post("./php/adates.php", { atype: apttype, data: $("#apptForm").serialize() })
.done(function(data) {
alert(data);
});
And more of the php function code:
if (isset($_POST["atype"]) && !empty($_POST["atype"])) {
$typ = test_input($_POST['atype'], $con);
} else {
echo "error ln 6: typ is undefined.";
}
$es=$_POST["mPicker"];
echo $es;
exit;
test_input is the function I mentioned that tests for SQL injection, and just for testing, have omitted temporarily on the post on mPicker. As you can see, the line $_POST["atype"] escapes error, and is perfectly resolved in the PHP function. I know I am tired and must be missing something stupid. Help, anyone!
try to use jQuery "ajax" instead of "post"
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: "html",
success: function(html){
console.log(html)
}
});
and set the dataType to "html", then use "echo" or "var_dunmp" in php, you can see ur data in console

Ajax request getting / receiving an incomplete response (limitation?)

I'm doing a simple ajax request on a html file to get it's code.
(Actually I don't need the type:"Get", because it doesn't do anything)
jQuery.ajax({
type: "GET",
url: "page-2.html",
dataType: "html",
success: function(response) {
alert(response);
}
});
The response is incomplete. The html file has 400 line sof code but the alert doesn't give me the full file. It is incomplete and stops at line +-130.
It seems that there is some character limitation. Is this possible?
The same happens when I use $.get()
Note: I also get a "Syntax Error -> page-2.html" in the console. Maybe both issues are connected.
jQuery.ajax({
type: "GET",
url: 'page-2.html',
dataType: "html",
success: function(response) {
console.log(response);
alert(response);
}
});
You were missing '' around page-2.html that's why there is error in console.
There is no issue with your ajax request because your script is perfectly working.if you get some error with response means there is some mismatched tag or html format issue that's why u got that error in response.
There is not need to encode URL in single quote ('') or double quote ("") in ajax request with this script.
Please verify your html code in page-2.html.

Extract Json response

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

Google Places API: json error Uncaught SyntaxError Unexpected token

I dont get why i get so many different errors.
I'm using Google Places API for a test, and using simply an ajax query call with callback, i receive back the json but in CHrome browser i get
"Uncaught SyntaxError: Unexpected token :"
why the hell is that?
I supposed Google does it right, and their json must be correct...so where could be the problem?
this is my code
$.ajax({
dataType: "json",
url: "https://maps.googleapis.com/maps/api/place/search/json?location=40.47,-73.58&radius=5000&sensor=false&key=MYOWN&name&callback=?",
success: function(data) {
console.log('success');
},
error: function(data) {
console.log('error');
}
});
You get this error, if a server returns plain JSON. As this is a cross-site request, jQuery has to use the JSONP-technique where the server-response is interpreted as script. This is the only way to do cross-site-requests in the browser.
The problem is that the server has to support JSONP and surround the JSON answer with a callback generated by jQuery. The response must look like that:
jQuery17101705844928510487_1324249734338({"data":"whatever"});
Server-Example with PHP:
<?php
header("Content-Type:text/javascript"); // avoid browser warnings
$request = new HttpRequest("http://programmingisart.com/json-data-source.php", HttpRequest::METH_GET);
$request->send();
$json_data = $request->getResponseBody();
// wrap the data as with the callback
$callback = isset($_GET["callback"]) ? $_GET["callback"] : "alert";
echo $callback."(".$json_data.");";
Client-Example with jQuery:
<div id="json-result"></div>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
dataType: "jsonp",
url: "jsonp-wrapper.php",
success: function(data) {
$("#json-result").html(JSON.stringify(data));
},
error: function() {
alert("error");
}
});
});
</script>
You can replace the PHP-code with any other server-platform and do the required steps.
HTTP-Request to a JSON source
Wrap the JSON as with a callback-function

Categories