I am struggling with a 500 internal server error. I have made just a basic script to test, but its just getting 500 anyways. Do you see a typo or logic errors? I am to blind right now to see an error.
AJAX
$("#select_kjede").change(function(){
var kjede = $("#select_kjede option:selected").val();
$.ajax({
type: "POST",
url: "bestilling/controller.php",
data: {
kjede: kjede
}
})
.done(function( msg ) {
alert(msg);
});
});
PHP
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$message = $_POST["kjede"];
echo "<script type='text/javascript'>console.log("."OLOL ".$message."</script>";
}
In the PHP-script i have tried a numerous methods, included if(isset($_POST['kjede'])
EDIT:
In Chrome console under the error -
send
b.extend.ajax
(anonymous function)
b.event.dispatch
v.handle
How can i console out the server errors?
I wanted to ask what your form looks like. But I could not comment. Your code works fine with the following form.
<form id="select_kjede">
<select>
<option>option_one</option>
<option>option_two</option>
<option>option_three</option>
</select>
<input type="submit" value="save"/>
</form>
Related
I can not get the PHP echo in my Ajax.
This is my test01.html code:
In my HTML code, I quote the jQuery, and I bind the event in my "sub01" button, I use Ajax provide the POST request:
$(".sub01").bind("click", function() {
$.ajax({
type: "POST",
url: "cms/test01.php?action=test01",
dataType: "json",
data: {
"var_01": "var_01_value",
"var_02": "var_02_value",
},
success: function(response) {
console.log(response) // there I want to console the response from PHP.
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<form>
<input type="text" value="var_01">
<input type="text" value="var_02">
<input id="sub01" type="submit" value="click me!">
</form>
</div>
And this is my PHP test01.php code:
in my PHP code I want to echo the $_POST, then I want the AJAX code get the response.
<?php
echo $_POST;
I want the code
success: function(response) {
console.log(response) // there I want to console the response from PHP.
}
shows the PHP echo, but there console nothing.
Problem 1
You never call your JS function
$(".sub01").bind
You are binding to the click event of elements with the class sub01.
<input id="sub01" type="submit" value="click me!">
Your button doesn't have that class!
Aside: bind is deprecated in favour of on.
$("#sub01).on("click" ....
Problem 2
You aren't letting the JS run
Since you are (trying) to run the JS when a submit button is clicked, the form is submitting.
The browser is leaving the page before the Ajax response comes back and triggers the success function.
You need to prevent the default behavior of the submit button.
$("#sub01").on("click", function (event) {
event.preventDefault();
// etc
});
Problem 3
You aren't parsing the response correctly
You said dataType: "json", which means "Tell the server I only Accept JSON and ignore the Content-Type and parse the response as JSON regardless".
Since the server is not responding with JSON, the attempt to parse the response fails and it errors.
Option 1
Remove dataType: "json".
This will process the response as invalid HTML (because PHP sends Content-Type: text/html by default).
Then you will echo the response (which is Array … probably not the response you want PHP to send though).
Option 2
Change the PHP so it responds with JSON
<?php
header("Content-Type: application/json");
echo json_encode($_POST, JSON_PRETTY_PRINT);
You need to output a json.
header('Content-Type: application/json');
echo json_encode($_POST);
I have the following extremely simple PHP tester:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<button id="button">send request</button>
<script>
$("#button").click(function(){
$.ajax({
type: "POST",
url: "ajaxTest.php",
data: {userresponse: "hi"},
success: function(data){
alert(data)
analyse()
}
})
})
var analyse = function () {
<?php
if(isset($_POST["userresponse"])){
$variable = $_POST["userresponse"];
switch($variable){
case "hi":
echo 'alert("' . $variable . '")';
break;
default:
echo 'alert("LOGIC")';
}
}
?>
}
</script>
What's supposed to happen is that when I click the button, it sends the data userresponse: "hi" to the server, and then PHP receives it and alerts the value (i.e. "hi")
However, despite the fact that the file paths are correct, the AJAX send is OK in XHR, the PHP does not receive the value of the data, and the alert(data) returns the entire HTML document.
What is going on and how do I fix this?
Remove analyze() and put your php code in external file called ajaxTest.php, your code works perfect just remove your php code fron analyze and request for external this is bad practice having both in same file(header problems).
Proof:
I've this code
$(document).on('click', '#button', function(){
var my_data = 'Test Test Tes';
$.ajax({
type: "POST",
url: "preview.php",
data: "my_data=" + my_data,
success: function() {
window.open('preview.php');
},
});
});
Above codes open the preview.php but I'm getting this error -
Notice: Undefined index: my_data in
C:\xampp\htdocs\tb-builder\preview.php on line 3
This is what I've in preview.php -
<?php
$data= $_POST['my_data'];
echo $data;
?>
Can anybody help me to solve this please? Thanks
Main error is , window.open('preview.php'); loads the page preview.php ,
You are not sending any data with post/get request while loading it using
window.open('preview.php'); and you are expecting value at $_POST['my_data']
$(document).on('click', '#button', function(){
var my_data = 'Test Test Tes';
$.ajax({
type: "POST",
url: "preview.php",
data: "my_data=" + my_data,
});
});
preview.php
<?php
if(isset($_POST['my_data']){
$data= $_POST['my_data'];
header('location:preview.php?my_data=$data'); //reload preview.php with the `my_data`
}
if(isset($_GET['my_data'])){
$data=$_GET['my_data'];
echo $data; //display `my_data` as you requested
}
?>
Update
With out using ajax ,to achieve what you required.
$(document).on('click', '#button', function(){
var my_data = 'Test Test Tes';
window.open('preview.php?my_data='+my_data);
});
preview.php
<?php
if(isset($_GET['my_data'])){
$data=$_GET['my_data'];
echo $data;
}
?>
final Update
Actually you don't need ajax at all , because you are going to another page with the data .
to avoid get request
Wrap the button inside a form with hidden input having value
my_data and set action="preview.php" like below
<form action="preview.php" method="post">
<input type="hidden" id="my_data" value="Test Test Tes">
<button type="submit" id="button">post</button>
</form>
use
if (isset($_POST['my_data']))
{
$data= $_POST['my_data'];
echo $data;
}
Please change your preview.php code with the following :-
<?php
if (isset($_POST['my_data']))
{
$data= $_POST['my_data'];
echo $data;
}
?>
It may help you.
It was completed question in
Is your error in new window ?? – HoangHieu 1 min ago
yes. in new window – Xahed Kamal
First Ajax post it completed when success: function called... In new window you doesn't have any post data, I don't know any solution post data by javascript to new window.. only one you can send data by GET request ..
window.open just create a new window object. That window will have no $_POST globals. Use window.open('preview.php?my_data=' + my_data); and use $_GET['my_data'] in that PHP.
The post is related to the ajax not for the new window.
EDIT
Ok guys, I see here is a little confusion.
Above codes open the preview.php but I'm getting this error -
So what happens?
OP is sending a data called my_data to the preview.php. This data is travelling through $_POST to the preview.php. At this point, there is $_POST['my_data'];
When it finish with success, the ajax call, then the window.open opens a new window, what has no $_POST data, this is why OP get this error message.
If he want to use the same data what he posted in my_data then he need to add it to the URL and use $_GET.
I think the misunderstood was what #HoangHieu wrote and me pointed:
yes. in new window – Xahed Kamal
And if you want to use response, then use
success: function(reponse) {
window.open('preview.php?my_data=' + response);
},
and then use $_GET['my_data'] in new window.
Your construct:
data: "my_data=" + my_data,
Is wrong. It should be:
data: {my_data: $my_data},
And I changed your JS variabale to $my_data, so it's less confusing.
I have the following AJAX:
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
})
.done(function(resp){
$('#plant-tree-inner').html(resp);
});
base is my base URL, tree is a controller and plant is a method in that controller.
The URL is correct, the controller and method are in place, with correct names. I've made sure of that by echoing a string in the plant method and it appeared correctly on the client after the AJAX response.
However, none of the post data seems to be arriving at the server.
Doing echo $this->input->post('name'); inside the plant method gives an empty string. Doing var_dump($_POST) gives an empty array. I even tried giving parameters to the plant method but that just throws a missing parameter error.
So where is the data getting lost and why?
EDIT: I see now that my question is wrong. It has nothing to do with CodeIgniter, since the data isn't being sent at all. The field values are undefined according to Javascript, but they certainly exist in HTML:
<input type="text" id="field_treename" placeholder="Tree name" value="" />
Seems like something is wrong with jQuery library.
For test' sake, try to send request avoiding it.
You may try this also..
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
success:function(resp){
$('#plant-tree-inner').html(resp);
}
});
Try to simulate the problem in the very basic method like creating another directory in your localhost or server like this and create files as describe below.
in the index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>POST Sending Problem</title>
<script src="jquery-1.12.2.js"></script>
</head>
<body>
Link
<script src="custom_function.js"></script>
</body>
</html>
Create js file for example test.js and put this as test
function test (id, base) {
$.ajax({
type: "POST",
data: {
'id': id
},
url: base,
success: function(data) {
alert(data);
},
error: function(data) {
alert('no data');
}
});
}
Next create a php file your_phpfile.php
<?php
if (isset($_POST['id'])) {
echo $_POST['id'];
} else {
echo "no-result";
}
?>
This would help you determine the problem. If this works fine, try applying it using codeigniter.
Good Luck
User this one..
var request = "name="+$('#field_treename').val()+"&"
request += "summary="+$('#field_summary').val()+"&"
request += "description="+$('#field_description').val()+"&"
request += "address="+$('#field_url').val()+"&"
request += "category="+$('#field_category').val()
and in set as data=request. This should work.
When I try to get the response from a php file using Jquery ajax, I just get (an empty string) (Accdg. to Firebug console using console.log(data))
Here's the Html code:
<form action="test.php" method="POST" id="ajax">
<input type="text" name="field" />
<input type="submit" value="submit" name="submit" />
</form>
Here's the Jquery code:
$('#ajax').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: $(this).serialize(),
url: 'test.php',
cache: false,
success: function(data) {
alert(data);
}
});
return false;
});
And the PHP code:
if ($_POST['submit'] == "submit")
{
echo 'Got your request';
}
Just basic. What frustrates me is that it's straightforward, I've done some research and still it doesn't work. I also want it to be as simple as possible.
Please enlighten me.
Don't check to see if you're in a POST situation by checking for fieldnames. That's incorrect - you might change your client-side form names and forget to update the PHP check.
The 100% reliable method is to use:
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
echo "Got your request";
}
However, since you just want to see if the server got pinged at all by your ajax call, why not do:
<?php
echo "Got your ", $_SERVER['REQUEST_METHOD'], " request";
Which'd just return Got your POST request or Got your GET request, etc...
As well, check your server log (or use HTTPFOX/Firebug Net tab, etc...) to see if that ajax request is actually going out and being received by the server.
The problem with the serialize() method is that it doesn't include the name of the button parameter which you use in your php script (submit=submit parameter). It doesn't do it because it doesn't know which button was clicked. This parameter is only included by the browser when you submit the form normally.
So one possibility is to manually attach this parameter as query string parameter:
url: 'test.php?submit=submit',
and in your PHP script:
if ($_GET['submit'] == "submit")
{
echo 'Got your request';
}