This is driving me crazy. I'm trying to post a variable to a PHP script using AJAX but while I can verify that $_POST is set, the varibale remains undefined.
I've used almost identical code elsewhere and it works fine - I just cant see what the problem is here.
Here is a very stripped down version of the code -
The JS
$(function(){
$('#load_more_comments').click(function(){
var newLimit = 40;
$.ajax({
url: "scripts/load_comments.php",
data: { limit: newLimit },
type: "post",
success: function(result){
// execute script
},
error: function(data, status, errorString)
{
alert('error');
}
});
return false;
});
});
The PHP
if (isset($_POST)) {
echo "POST is set";
if (isset($_POST['limit'])) {
$newLimit = $_POST['limit'];
echo $newLimit;
}
}
UPDATE
var_dump($_POST) returns array(0) { } so I know that AJAX is definitely is not posting any values
Using slightly modified version of the above I am unable to reproduce your error - it appears to work fine.
<?php
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
if( isset( $_POST['limit'] ) ){
echo $_POST['limit'];
}
exit();
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
<script src='//code.jquery.com/jquery-latest.js'></script>
<script>
$(function(){
$('#load_more_comments').click(function(){
var newLimit = 40;
$.ajax({
url: location.href, //"scripts/load_comments.php",
data: { limit: newLimit },
type: "post",
success: function(result){
alert( result )
},
error: function(data, status, errorString){
alert('error');
}
});
return false;
});
});
</script>
</head>
<body>
<!-- content -->
<div id='load_more_comments'>Load more...</div>
</body>
</html>
Try :
if (count($_POST)) {
Instead of
if (isset($_POST)) {
I am trying to learn ajax, because it will be useful for the project I am developing. I am only getting started at it. I've watched some tutorials and now I testing out some code. I am using laravel. Here is my view:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<button type="button" class="btn btn-warning" id="getRequest">get Request</button>
<div id="teste"></div>
<script type="text/javascript">
var id = 12; // A random variable for this example
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#getRequest').click(function(){
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: '/customer/ajaxupdate', // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
var theDiv = document.getElementById("teste");theDiv.innerHTML += response->'teste';
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
})
})
</script>
</body>
</html>
Here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function updateCustomerRecord(Request $request)
{
$datda = $request->all(); // This will get all the equest data.
$teste = "teste";
return response()->json(['success' => true, 'teste' => $teste]);
echo "ole";
}
}
And lastly we have my routes:
Route::post('/customer/ajaxupdate', 'AjaxController#updateCustomerRecord');
Route::get('/teste', function(){
return view('teste');
});
As you can see this is simple code... When I get more used to Ajax I will do a select from database and show data on the view. But now I am trying to pass data from one variable on the controller to the view using json response. I also wish you could give me a tip how I should do a simple db:select and the best way to pass it through to the view.
I am expecting this code to pass data from controller to view.
There's a mistake in your JavaScript code. You are using arrow -> instead of period or dot .
Please replace this
theDiv.innerHTML += response->'teste';
with this
theDiv.innerHTML = response.teste;
I'm making a AJAX call and I'm trying to receive json from an array json_encode(), but doesn't seem to be working. Thanks for any help.
I'm not getting any errors and i've checked some other stackoverflow questions, but can't find a complete example.
The problem is i'm nothing it going in to the div (#form_response) when the ajax is called and its returning everything from results
The response I get using the code below is:
{"success":true,"error":false,"complete":"<div class=\"ser_mess\">success<\/div>","error_msg":{"empty":"<div class=\"ser_mess\">empty<\/div>"}}
HTML & AJAX:
<script type="text/javascript" src="js/jquery.js"></script>
<div class="" id="form_response"></div>
<form id="add_property_form" action="" method="POST">
<input type="text" name="input">
<button type="submit">Send</button>
</form>
<script type="text/javascript">
$("#add_property_form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'thescript.php',
type: 'POST',
data: formData,
async: false,
cache:false,
contentType: false,
processData: false,
dataType: "json",
success: function (data) {
$('#form_response').html(data);
}
});
return false;
});
</script>
thescript.php
header('Content-Type: application/json');
$success = true;
$false = false;
$results = array(
'success' => $success,
'complete' => '<div class="ser_mess">success</div>',
'error' => $false,
'error_msg' => array('empty' => '<div class="ser_mess">empty</div>',)
);
if(empty($_POST['input']) ){
$results['error'];
$results['error_msg']['empty'];
}else{
$results['success'];
$results['complete'];
}
echo json_encode($results);
exit();
My testing steps with your code. Resolving problems.
If you are submitting the data with an ajax request, then you don't want to natively submit the form. So, use just a button of type "button", not of type "submit". Statements like evt.preventDefault(); and return false are correctly used only when the form should be natively submitted (e.g. not through a button of type "submit", or similar) and, for example, you are validating it. If the user input is not valid, then you apply such statements, so that you can stop the form from submitting.
Your ajax doesn't start, because it's not included into a $(document).ready(function () {...}.
I receive "TypeError: 'append' called on an object that does not implement interface FormData. Use var formData = $('add_property_form').serialize(); instead of var formData = new FormData($(this)[0]);.
The async:false property gave the warning: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/ jquery-3.2.1.min.js:4:15845". So, remove async. Also, you don't need cache, contentType, processData. Remove them.
Since, by setting dataType: "json", you are already telling the server that you are expecting JSON encoded data back from the server, you don't need to send the response header with header('Content-Type: application/json');. Remove it.
Use method: "post" instead of type: "post", because the latter is used only up to version 1.9.0 of jquery. Read the ajax specification.
Your php code inside the if statements was error-prone. I made my version out of it.
If you are receiving JSON encoded data from the server, you can not directly pass it as html content into a div. You must read its values separately and do something with them. In analogy: in php you can also not simply write echo $results, because then you would receive Notice: Array to string conversion. The same is with the client-side code.
test.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title></title>
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#add_property_form").submit(function (evt) {
evt.preventDefault();
var formData = $('#add_property_form').serialize();
$.ajax({
url: 'thescript.php',
type: 'POST',
dataType: "json",
data: formData,
success: function (data, textStatus, jqXHR) {
var formResponse = $('#form_response');
var success = data.success;
var message = data.message;
if (success) {
formResponse.removeClass('error').addClass('success');
} else {
formResponse.removeClass('success').addClass('error');
}
formResponse.html(message);
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR);
}
});
return false;
});
});
</script>
<style type="text/css">
.success,
.error {
max-width: 400px;
color: white;
margin-bottom: 15px;
}
.success {
background-color: green;
}
.error {
color: white;
background-color: red;
}
</style>
</head>
<body>
<div id="form_response" class="message"></div>
<form id="add_property_form" action="" method="POST">
<input type="text" name="input">
<button type="submit">Send</button>
</form>
</body>
</html>
thescript.php
<?php
if (empty($_POST['input'])) {
$results['success'] = false;
$results['message'] = 'No input value provided!';
} else {
$results['success'] = true;
$results['message'] = 'You provided the value ' . $_POST['input'];
}
echo json_encode($results);
exit();
Another example
Since you were looking for a complete example I took the liberty to create one for you.
The main point of it is to define an "error" callback for the ajax request. Because, when you throw errors, you actually want your ajax "error" callback take its role. For activating it, you just have to send a custom response header - having a status code of class "4xx: Client errors" - from the server (search.php) to the client (custom.js). Such a header is used like this: "Dear browser, I, the server, am sending you this response: 'HTTP/1.1 420 Please provide the city.'. As you see, its status code is 420, e.g. of class 4xx. So please be so kind and handle it in the 'error' callback of your ajax request". Here is the List ofStatus Codes.
You can run the code as it is. Create a folder in your document root, paste the files in it, then let test.php running.
test.php
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<meta charset="UTF-8" />
<!-- The above 3 meta tags must come first in the head -->
<title>Demo</title>
<!-- CSS resources -->
<link href="custom.css" type="text/css" rel="stylesheet" />
<!-- JS resources -->
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="custom.js" type="text/javascript"></script>
</head>
<body>
<div class="page-container">
<form class="user-input">
<div class="messages">
Here come the error/success messages
</div>
<div class="form-group">
<label for="city">City:</label>
<input type="text" id="city" name="city" placeholder="City">
</div>
<div class="form-group">
<button type="button" id="searchButton" name="submit" value="search">
Search
</button>
</div>
</form>
<div class="cities">
Here comes the list of the found cities
</div>
</div>
</body>
</html>
search.php
<?php
// Get the posted values.
$city = isset($_POST['city']) ? $_POST['city'] : '';
// Validate the posted values.
if (empty($city)) {
/*
* This custom response header triggers the ajax error because the status
* code begins with 4xx (which corresponds to the client errors). Here is
* defined "420" as the custom status code. One can choose whatever code
* between 401-499 which is not officially assigned, e.g. which is marked
* as "Unassigned" in the official HTTP Status Code Registry. See the link.
*
* #link https://www.iana.org/assignments/http-status-codes/http-status-codes.xhtml HTTP Status Code Registry.
*/
header('HTTP/1.1 420 Please provide the city.');
exit();
} /* Other validations here using elseif statements */
/* The user input is valid. */
/*
* Perform the search operation in a database, for example, and get the data.
* Here just an array simulating a database result set with two records.
*/
$foundCities = [
[
'name' => 'Athens',
'isCapital' => 'is a capital',
],
[
'name' => 'Constanta',
'isCapital' => 'is not a capital',
],
];
// Print the response.
$response = [
'message' => 'Great. ' . count($foundCities) . ' cities were found.',
'cities' => $foundCities,
];
echo json_encode($response);
exit();
custom.js
$(document).ready(function () {
$('#searchButton').click(function (event) {
ajaxSearch();
});
});
function ajaxSearch() {
$.ajax({
method: 'post',
dataType: 'json',
url: 'search.php',
data: $('.user-input').serialize(),
success: function (response, textStatus, jqXHR) {
/*
* Just for testing: diplay the whole response
* in the console. So look unto the console log.
*/
console.log(response);
// Get the success message from the response object.
var successMessage = response.message;
// Get the list of the found cities from the response object.
var cities = response.cities;
// Display the success message.
displayMessage('.messages', 'success', successMessage);
// Display the list of the found cities.
$('.cities').html('');
$.each(cities, function (index, value) {
var city = index + ": " + value.name + ' (' + value.isCapital + ')' + '<br/>';
$('.cities').append(city);
});
},
error: function (jqXHR, textStatus, errorThrown) {
// Handle the raised errors. In your case, display the error message.
handleAjaxError(jqXHR);
},
complete: function (jqXHR, textStatus) {
// ... Do something here, after all ajax processes are finished.
}
});
}
/**
* Display a user message.
*
* #param selector string The jQuery selector of a message container.
* #param type string The message type: success|danger|warning.
* #param message string The message text.
* #return void
*/
function displayMessage(selector, type, message) {
$(selector).html('<div class="message ' + type + '">' + message + '</div>');
}
/**
* Handle an error raised by an ajax request.
*
* If the status code of the response is a custom one (420), defined by
* the developer, then the corresponding error message is displayed.
* Otherwise, e.g. if a system error occurres, the displayed message must
* be a general, user-friendly one. So, that no system-related infos will be shown.
*
* #param jqXHR object The jQuery XMLHttpRequest object returned by the ajax request.
* #return void
*/
function handleAjaxError(jqXHR) {
var message = 'An error occurred during your request. Please try again, or contact us.';
if (jqXHR.status === 420) {
message = jqXHR.statusText;
}
displayMessage('.messages', 'danger', message);
}
custom.css
body {
margin: 0;
padding: 20px;
}
.page-container {
padding: 30px;
background-color: #f4f4f4;
}
.messages {
margin-bottom: 20px;
}
.message {
padding: 10px;
margin-bottom: 10px;
border: 1px solid transparent;
}
.success {
color: #3c763d;
border-color: #d6e9c6;
background-color: #dff0d8;
}
.danger {
color: #a94442;
border-color: #ebccd1;
background-color: #f2dede;
}
.warning {
color: #8a6d3b;
border-color: #faebcc;
background-color: #fcf8e3;
}
form {
width: 400px;
}
.form-group {
margin-bottom: 20px;
}
.form-group label {
display: inline-block;
min-width: 40px;
}
button {
padding: 7px 10px;
margin: 10px;
display: block;
color: #fff;
font-size: 14px;
border: none;
background-color: #8daf15;
}
success: function (data) {
$('#form_response').html(data);
}
this block is your response handler - and data is the JSON object you're getting back from the AJAX call. if you want to display a particular attribute of your JSON object, you'll want to reference something like data.complete, which looks like a little bit of HTML, which you can then put into your div#form_response
success: function (data) {
$('#form_response').html(data.success);
}
you can access all of the object in the same way:
{"success":true,"error":false,"complete":"<div class=\"ser_mess\">success<\/div>","error_msg":{"empty":"<div class=\"ser_mess\">empty<\/div>"}}
so to get the html for the "empty" error message, you'd use
$('#form_response').html(data.error_msg.empty);
alternatively, if i misunderstand the question, if you want the RAW json to appear in div#form_response, you can convert the json object into a string:
json_string = JSON.stringify( data );
$('#form_response').html( json_string );
I am fairly confident this should work for you :)
Your HTML/JS file:
<script type="text/javascript" src="js/jquery.js"></script>
<div class="" id="form_response"></div>
<form id="add_property_form" action="" method="POST">
<input type="text" name="input">
<button type="submit">Send</button>
</form>
<script type="text/javascript">
$("#add_property_form").submit(function(evt){
evt.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'thescript.php',
type: 'POST',
data: formData,
async: false,
cache:false,
contentType: false,
processData: false,
dataType: "json",
success: function (data) {
var resultData = data.response_msg; // get HTML to insert
$('#form_response').html(resultData);
// You can also use data.status (= true or false), to let you know which HTML was inserted :)
}
});
return false;
});
</script>
your PHP file:
header('Content-Type: application/json');
// construct original array
$results = array(
'status' => false,
'response_msg' => ''
);
// analyze $_POST variables
if(empty($_POST['input'])){ // if input post is not empty:
$results['status'] = false;
$results['response_msg'] = '<div class="ser_mess">empty</div>';
}else{ // if input post is empty:
$results['status'] = true;
$results['response_msg'] = '<div class="ser_mess">success</div>';
}
echo json_encode($results); // encode as JSON
exit();
I am trying send an array from php to js via ajax but don't it run, no matter what I do.
I'm sure it must be simple but I've tried everything.
<!doctype html>
<html lang="es">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Test</title>
<link type="text/css" rel="stylesheet" href="styles.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="scriptJS.js"></script>
</head>
<body>
<div>
<div class="tweets-container">
<p>Loading</p>
</div>
</div>
</body>
</html>
$(document).ready(function() {
var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
'<h1>Welcome!</h1>' +
'<div class="seeTweets"><select>';
var count = 0;
$.get({
url: 'scriptPHP.php',
type: 'GET',
data: {
usUsers: 'usuarios'
},
success: function(response) {
contPrincipalLastTwitter += '<option value =' + response + '>' + response + '</option>';
count++;
},
error: function(e) {
console.log(e.responseType);
);
}
});
console.log(count); contPrincipalLastTwitter += '</select></div></div>'; $(document.body).append(contPrincipalLastTwitter);
});
<?php
$test = array('uno'=>'uno', 'dos' => 'dos');
echo json_encode($test);
?>
I reduced it as much as I could, originally this one was sent to a class and this one, having several requests acted according to who have called it.
the problem is that you try to concatenate the same string in two different time and place (first inside the document ready, secondly in the success of the ajax call)
js code:
$(document).ready(function() {
var contPrincipalLastTwitter = '<div class="principalSeeTwitter">' +
'<h1>Welcome!</h1>' +
'<div class="seeTweets"><select id="test-select"></select></div></div>';
$(document.body).append(contPrincipalLastTwitter);
$.get({
url: 'scriptPHP.php',
type: 'GET',
data: {
usUsers: 'usuarios'
},
success: function(response) {console.log(response);
console.log(response);
for(var idx in response){
$('#test-select').append('<option value =' + idx + '>' + response[idx] + '</option>');
}
},
error: function(e) {
console.log(e.responseType);
}});
});
scriptPHP.php
<?php
$test = array('uno'=>'uno', 'dos' => 'dos');
// add header
header('Content-Type: application/json');
echo json_encode($test);
A slightly simpler option
const target = document.querySelector('#target');
$.ajax({
url: 'script.php',
dataType: 'JSON',
success: response => {
for (let key in response) {
const option = `<option value="${key}">${response[key]}</option>`;
target.innerHTML += option;
}
},
error: error => {
// todo
}
});
ajaxcheck.js
var val = "hai";
$.ajax(
{
type: 'POST',
url: 'ajaxphp.php',
data: { "abc" : val },
success :function(data)
{
alert('success');
}
}
)
.done(function(data) {
alert("success :"+data.slice(0, 100));
}
)
.fail(function() {
alert("error");
}
);
ajax.html
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="ajaxcheck.js"></script>
<title>ajax request testing</title>
</head>
<body>
</body>
</html>
ajaxphp.php
<?php
$v_var = $_POST["abc"];
print_r($_POST);
if(isset($_POST["abc"]))
{
echo $v_var;
}
else
{
echo "Data not received";
}
?>
When I run the ajax.html file ,I get success alert. But when I run ajaxphp.php file it shows notice like:
undefined index abc
Why is that the data is not received in $v_var ? where i am mistaking ?please help.
Actually the ajaxphp.php file is used to receive the data from the
post method and i will give response .
In First case by using ajax post method it will call to ajaxphp.php file.
In Second case your using direct file call without any post data(that's way it shows error)
Try this
var val = "hai"
$.post( "ajaxphp.php", {'abc':val}function( data ) {
alert( "Data Loaded: " + data );
});
jQuery expects an object as data, remove the double-quotes:
data: { abc : val }