Jquery Ajax no response - php

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

Related

How to console the PHP echo in my javascript?

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

AJAX call not sending data to PHP script

I have tried to run an AJAX call within a PHP file, which sends data to another PHP file on the server that is taken from an html input when I press the submit button. Unfortunately when I click on the button, nothing happens, not even in the console. I have tried to debug the issue by creating a window.alert() of the input within the AJAX call, but it somehow shows a certain "object Object" result in the alert box. I have tried to change the path to see if the file is being detected or not, but it seems it is being detected as when I deliberately add a wrong path it throws a 404, and even tried to add echo calls to the PHP file being called but nothing appears. The only issue I can really think of now is something wrong with my implementation, but I'm not sure what it is.
Update: I have tried looking up certain questions such as here and here, but they don't work for me
Code from where the AJAX calls are being made:
<?php
require "../../../AutoLoader.php";
use mvcApplication\core\controllers\ControllerFactory;
?>
<script>
$(document).ready(function () {
$('#submit').click(function () {
$.ajax({
url: '../app/views/generic/deletefunc.php',
type: 'GET',
data: {
Id: $('#Id'),
value: "0"
},
processData: false
});
});
});
</script>
<br>
<br>
<center>
<h3>Enter Teacher ID:</h3><input type="text" id="Id"
placeholder="Input ID here"/>
<br>
<button class="col-sm-4" id="submit">Submit</button>
</center>
<br>
deletefunc.php (code where the data should be received)
<?php
require_once '../../../AutoLoader.php';
use mvcApplication\core\controllers\ControllerFactory;
function deleteTeacher($a)
{
echo $a;
$entity = ControllerFactory::initTeacherC();
$entity->delete($a);
}
function deleteStudent($a)
{
echo $a;
/*$entity = ControllerFactory::initStudentC();
$entity->delete($data);*/
}
function deleteCourse($a)
{
echo $a;
/*$entity = ControllerFactory::initCourseC();
$entity->delete($data);*/
}
if (isset($_GET['Id']) && isset($_GET['value'])) {
switch ($_GET['value']) {
case "0":
deleteTeacher($_GET['Id']);
break;
case "1":
deleteStudent($_GET['Id']);
break;
case "3":
deleteCourse($_GET['Id']);
break;
}
}
According to ajax docs http://api.jquery.com/jquery.ajax/;
processData (default: true) Type: Boolean By default, data passed in
to the data option as an object (technically, anything other than a
string) will be processed and transformed into a query string, fitting
to the default content-type "application/x-www-form-urlencoded".
I think you have to set processData to True on your ajax call because you're using GET (get needs querystring, url data) or just don't set it so it would be the default which is true.

JQuery -> Ajax -> PHP -> 500 internal server error

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>

isset causing getjson to return undefined

I'm having a problem with my code. I want to validate my form by creating an array to contain a variable when the form is valid. But to do this I need to use the isset method to know that the information has been posted. Here's a simple example
http://richbaird.net/clregister
<?PHP
if(isset($_POST['username'])) {
$helloworld = array ("hello"=>"world","name"=>"bob");
print json_encode($helloworld);
};
if(!isset($_POST['username'])) {
echo json_encode(array('error' => true, 'message' => 'No username specified'));
?>
Simple enough if username has been posted create array helloworld.
I'm using the following method to get the json
<script>
//document ready
$(document).ready(function(){
var php = "helloworld.php";
//submit form
$("#loginform").ajaxForm
(
//on successful submission
function() {
//getjson
$.getJSON("helloworld.php",function(data) {
alert(data.message)
}) //close get json
.error(function(error) { alert(error.responsetext); })
.complete(function() { alert("complete"); });
} // close success
) // close submit
});
//end document ready
</script>
I'm using the jquery forms plugin to submit the form.
and my form looks like this
<form id="loginform" name="loginform" method="post" action="helloworld.php">
<label for="username">username</label>
<input type="text" name="username" id="username" />
<br />
<label for="password">password</label>
<input name="password" type="password" />
<br />
<input name="submit" type="submit" value="Login" id="subtn" />
</form>
the network console shows the method POST returns {hello:world name:bob} but the GET returns the no username specified which is what I get in my alert. It looks like jquery is trying to get the code before it has a chance to process entirely, how can I prevent this?
You're missing the quotes. Should be:
if(isset($_POST['username']))
You should check your console to see whether username is actually getting posted, as if it's not, you're not returning any data. You could instead consider returning an error if(!isset($_POST['username'])), perhaps something like:
echo json_encode(array('error' => true, 'message' => 'No username specified'));
EDIT
Also, remember it's $_POST, not $_post
Second Edit
Your code will be far more intuitive and readable written like this:
$return = array();
if(isset($_POST['username'])) {
$return = array("hello"=>"world","name"=>"bob");
} else {
$return = array('error' => true, 'message' => 'No username specified');
}
echo json_encode($return);
After a few hours of thinking and a lot of help from juco I realized, I'm making 2 seperate calls in this function. First I'm posting the data which works, then on a successful post I'm trying to make a seperate call, a GET request, that request contains the callback which is supposed to alert me of the result, however because it makes a 2nd call and it sends a GET request the variable POST is never set and therefore there is nothing to get back. I revised my code to only use the post method like so.
<script>
//document ready
$(document).ready(function(){
// bind form using ajaxForm
$('#loginform').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'json',
// success identifies the function to invoke when the server response
// has been received
success: processJson
}
);
function processJson(data) {
alert(data.hello);
}
});
//end document ready

No Ajax response even though PHP file set up correctly

I have a simple sign up mailing list form. It sends the user's email address to a store-address.php file. I use jQuery's ajax object to send a request to the php file and then receive a response.
The problem is I am not getting a response from the php file. I tried setting the cache to false in the request. I also tried send the information through the URL like so:
http://www.fifthtribe.com/inc/store-address.php?ajax=true&cache=false&email=test4%40gmail.com
When I do it that way it works and gives me a reponse. But when I do it through ajax it doesn't give me a response. This is from Firebug:
And here's snippets from my code:
HTML:
<div id="mlist">
<form id="mlist_form" method="POST" action="">
<input type="text" id="email" name="email" placeholder="Email" />
<input type="submit" id="submit_btn" value="Join" />
</form>
<div id="response"></div>
</div>
JQuery:
/* Add to mailing list */
$("#mlist_form").submit( function(e){
//$('#response').append('<div id="thanks-mce"><div id="mce-arrow"></div>Thanks for signing up!</div>');
var email = escape( $('#email').val() );
e.preventDefault();
data = {
"ajax" : "true",
"email" : email,
"cache" : "false"
}
$.ajax({
type: "POST",
url: 'inc/store-address.php',
data: data,
success: function( msg ){
// successfully signed up
$('#response').html( msg );
$('#email').val('');
},
error: function( err ){
// error while signing up
$('#response').html('Error: Is your email correct?');
}
});
return false;
});
PHP:
function storeAddress(){
// Validation
if(!$_GET['email']){ return "No email address provided"; }
if(!preg_match("/^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*$/i", $_GET['email'])) {
return "Email address is invalid";
}
require_once('MCAPI.class.php');
// grab an API Key from http://admin.mailchimp.com/account/api/
$api = new MCAPI('xxxxxxxxxxxxxxxxxxxxxxxxxxxxx-us4');
// grab your List's Unique Id by going to http://admin.mailchimp.com/lists/
// Click the "settings" link for the list - the Unique Id is at the bottom of that page.
$list_id = "xxxxxxxx";
if($api->listSubscribe($list_id, $_GET['email'], '') === true) {
// It worked!
return 'Success! Check your email to confirm sign up.';
}else{
// An error ocurred, return error message
return 'Error: ' . $api->errorMessage;
}
}
// If being called via ajax, autorun the function
if($_GET['ajax']){ echo storeAddress(); }
?>
You realize that your PHP script is using GET method but your jQuery code is using the POST method right?
If the information is being posted to PHP, PHP will need to use $_POST to retrieve it. This explains why the URL method using $_GET works but the jQuery POST doesn't.
Good luck!
It looks like you're using $_GET instead of $_POST. Try echoing out the contents of $_REQUEST to see what that holds.
Debug your script!
Place an alert in the success and error parts of your script and then you will know whether the AJAX is working.
If not, you can then work your way up the document and see where the problem is.
In addition, the error here is quite simple. You are using $_GET in PHP and you are POSTING your data using AJAX, this will not show an error. Although the PHP document will not process your request because it is not being fed any parameters.

Categories