Why doesn't the die() function work? - php

I have an ajax call that sends data from a form to a php file that will then insert that data to the database. I put a call to die in said php file because I want to try something but it doesn't work.
addUserForm.php
<script>
$(document).ready(function () {
var $form = $('form');
$form.submit(function (event) {
event.preventDefault();
var formData = $form.serialize(),
url = $form.attr('action');
$.ajax({
type: "POST",
url: url,
data: formData,
success: function () {
//$("#div1").load("table.php");
alert('User Successfully Added');
document.getElementById("form1").reset();
}
});
});
});
</script>
Here is the php file:
addUser.php
<?php
include('sqlconnection.php');
die('here');
$firstname = $_POST['fname'];
$lastname = $_POST['lname'];
$middlename = $_POST['mname'];
$password = $_POST['pword'];
$username = $_POST['uname'];
$gender = $_POST['gender'];
$utype = $_POST['utype'];
$query = "INSERT INTO user (firstname,lastname,middlename,gender) VALUES ('$firstname','$lastname','$middlename','$gender')";
mysqli_query($con,$query);
$result = mysqli_query($con,"SELECT id FROM user WHERE firstname = '$firstname'");
$row = mysqli_fetch_assoc($result);
$uid=$row['id'];
$result = mysqli_query($con,"INSERT INTO accounts (u_id,username,password,account_type) VALUES ('$uid','$username',md5('$password'),'$utype');");
?>
Even when there is a die call in adduser.php it still alerts that the user was successfully added.

That's because die() only terminates/ends the PHP script. From an AJAX point of view the request was successful.
You should echo the info in the PHP page and then output the content of the response in your AJAX.
You could also set the response header in your PHP Script to something other than 200/OK, such as 401/Unauthorized or 400/Bad Request. Basically all 400 and 500 status codes indicate error.

Since the PHP code executes successfully even thou die(), the ajax will trigger the success and you will recevie the success message.
to stop your javascript at any point you can add return false;
In your success block
success: function () {
//$("#div1").load("table.php");
alert('User Successfully Added');
document.getElementById("form1").reset();
}
You can add these two line like this
success: function (data) {
/* These two lines*/
console.log(data);
return false;
//$("#div1").load("table.php");
alert('User Successfully Added');
document.getElementById("form1").reset();
}
So once you're done with your debugging you can remove those lines..

Die function doesn't stop javascript. It just stop PHP.
For exemple, if you add the die() function before inserting datas, datas will not be inserted but the success funciton will be executed and you will have alert.
If you want to execute the Error function, you have to add Throw exception or header 403 in the php file.

The jQuery success function just make sure the page is loaded. A die in PHP doesn't change that. You will have to check with returned data.
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: >The data returned from the server, formatted according to the dataType parameter; a string >describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery >1.5, the success setting can accept an array of functions. Each function will be called in >turn. This is an Ajax Event.

ajax request php file, die ('here') is equivalent to echo 'here', return value, that successful implementation

Related

Failed to load resource errors(405) when send Ajax data to php

I have error ->
"Failed to load resource: the server responded with a status of 405
(Method Not Allowed)"
when send Ajax data to PHP in larval.
(I made route)
Ajax code
function insertData()
{
var text = document.getElementById('humanText').value;
var user = document.getElementById('userName').innerText;
$.ajax({
type:"POST",
url: "insertContentData",
data:{text:text, user:user},
success: function(data){
alert(data);
}
});
document.getElementById('humanText').value = "";
};
insertData();
and my php code "insertContentData.php"
<?php
$data = $_POST['text'];
$user = $_POST['user'];
echo $data.", ".$user;
?>
why not work this?
Thanks for your help.
In the http world the "METHOD" normally used is "GET" which is simply pulling data from the server. When you want to send data from the user to the server you used "POST". These are the two most commonly used methods.
The errors says that the METHOD IS NOT ALLOWED. You are AJAX code shows that you are using the POST method.
In Laravel you need to define a route that allows for the POST method. So instead of Route::get($uri, $callback); it would be Route::post($uri, $callback); Some more information can be found in the Laravel Routing documentation. However I think you are missing some concepts based on the primitive PHP code you posted, that code should be inside a controller.
Try to run like this. I hope it works.
function insertData(){
var text = document.getElementById('humanText').value;
var user = document.getElementById('userName').innerText;
$.ajax({
type:"POST",
url: "insertContentData",
data:{text:text, user:user},
success: function(data){
alert(data);
}
});
document.getElementById('humanText').value = "";
};
window.onload = function(){
insertData();
}
<?php
$data = $_POST['text'];
$user = $_POST['user'];
echo $data.", ".$user;
?>

Ajax doesn't call server side function when jquery handler is fired

I'm building a simple forum on which I have a user details page with two text fields, one for the user's biography and another for his interests.
When the user clicks on the save icon, a handler on the jquery is suposed to call an ajax call to update the database with the new value of the biography/interests but the ajax call isn't being called at all and I can't figure it out since I don't find any problems with the code and would apreciate if someone could take a look at it.
this is the textarea:
<textarea rows="4" cols="50" id="biography" readonly><?php if($info['bio'] == "") echo "Não existe informação para mostrar";
else echo $info['bio']; ?></textarea>
Here is the icon the user clicks on:
<li style="display:inline;" class="infoOps-li"><img class="info-icons" id="save1" src="assets/icons/save.png" alt=""></li>
this is the jequery with the ajax call:
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php", //the page containing php script
type: "post", //request type,
dataType: 'json',
data: {functionName: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
}
});
$("#biography").prop("readonly","true");
});
I know that the jquery handler is being called correctly because the first alert is executed. The alert of the ajax success function isn't, so I assume that the ajax call isn't being processed.
On the php file I have this:
function updateBio($bio)
{
$user = $_SESSION['userId'];
$bd = new database("localhost","root","","ips-connected");
$connection = $bd->getConnection();
if($bio == "")
{
echo json_encode(array("abc"=>'empty'));
exit();
}
if($stmt = mysqli_prepare($connection,"UPDATE users SET biografia = ? WHERE user_id = ?"))
{
mysqli_stmt_bind_param($stmt,'si',$bio,$user);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
echo json_encode(array("abc"=>'successfuly updated'));
}
$bd->closeConnection();
}
if(isset($_POST['functionName']))
{
$function = $_POST['functionName'];
echo $function;
if(isset($_POST['info']))
$info = $_POST['info'];
if($function == "bio")
{
updateBio($info);
}
else if($function == "interest")
{
updateInterests($info);
}
}
Can anyone shed some light on why isn't the ajax call being called?
Thank you
EDIT: changed "function" to "functionName" in json data object as suggested.
A possible problem is dued to a wrong parsing of the PHP output (for example due to a PHP error). You are reading the output as JSON, so if the output is not a JSON, success callback will not be triggered.
$("#save1").click(function(){
var bio = $("#biography").val();
alert(bio); //this fires up
$.ajax({
url:"assets/phpScripts/userBioInterest.php",
type: "post", //request type,
dataType: 'json',
data: {function: "bio", info:bio},
success:function(result){
alert(result.abc); //this doesn't fire
},
error: function(result){
alert("An error has occurred, check the console!");
console.log(result);
},
});
$("#biography").prop("readonly","true");
});
Try with this code, and check if an error is printed to the console.
You can use complete too, check here: http://api.jquery.com/jquery.ajax/

jQuery Ajax sending empty data

I'm doing a code that send a data to a php file and send it back again and print it as a response however when i send the data it is sent as an empty data i did not know what is the problem this is the code that i tried:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi, "").split("\n");
function doRequest(index) {
// alert(resource[0]); The data here is ok and it is not empty whenever the data is sent the response is empty !
$.ajax({
url:'curl_check.php?email='+resource[0],
async:true,
success: function(data){
alert(data);
if (resource.length != 1) {
removeResourceLine();
doRequest(index+1);
}
}
});
}
doRequest(0);
since you're not sending the data using the data property of the ajax call object like so:
$.ajax({
...
data : { email : resource[0] }
...
});
you are sending it as part of the URL, so it should be picked up as a GET variable. in php, this looks like:
$email = isset($_GET['email']) ? $_GET['email'] : false;
that said, i'd suggest using the ajax data property and specifying the type property and setting it to GET or POST. you could also use $.ajaxSetup
Ok I am not sure what is wrong with what you are doing but I am going to give you code I use to send data to php and get a response. I am going to do it with json because it is awesome. I hope it helps:
var resource = $('#resource').val().replace(/[\n\r](?!\w)/gi,"").split("\n");
function doRequest(index) {
$.post("curl_check.php", {
email: resource[0]
}, function(data, result, xhr){
if(result == 'success') {
console.log(data.success);
} else {
console.log('post failed');
}
}, "json");
}
The php code:
$json = array();
$email = $_POST['email']; //Please escape any input you receive
//Do what you have to do
$json['success'] = 'YAY IT WORKED';
die(json_encode($json));

ajax wont execute php function

I'm trying to create a login form with ajax, but the php event handler never start, if i use the METHOD POST form, the function works without a problem.
I have debugg the function, and the ajax form is sending httprequest.
Any ideas?
this is my ajax.
$(document).ready(function() {
$('#login').click(function() {
var login_email = $('#login_email').val();
var login_password = $('#login_password').val();
$.ajax({
url: 'core/manageusers.php',
type: 'POST',
data: {
login:login_email,
login_email:login_email,
login_password:login_password
},
success: function() {
location.reload();
}
});
});
});
Eventhandler.
if(isset($_POST['login']))
{
include_once('core/class.users.php');
$email = $_POST['login_email'];
$password = $_POST['login_password'];
}
login:login_email,
login_email:login_email,
login_password:login_password ,
},
That wayward comma at the end of login_password:login_password will break it, but probably not your only problem
remove ',' from the end of 'login_password:login_password ,'
You have a syntax error in the creation of ajax request :
data: {
login:login_email,
login_email:login_email,
login_password:login_password **,**
},
remove this comma
Works as designed: If you are retrieving Data in PHP with $_POST, nothing will happen if you are accessing with a GET Request.
The AJAX actually sends POST as from your code above.

jQuery JSON PHP Request

I've been trying to figure out what I have done wrong but when I use my JavaScript Console it shows me this error : Cannot read property 'success' of null.
JavaScript
<script>
$(document).ready(function() {
$("#submitBtn").click(function() {
loginToWebsite();
})
});
</script>
<script type="text/javascript">
function loginToWebsite(){
var username = $("username").serialize();
var password = $("password").serialize();
$.ajax({
type: 'POST', url: 'secure/check_login.php', dataType: "json", data: { username: username, password: password, },
datatype:"json",
success: function(result) {
if (result.success != true){
alert("ERROR");
}
else
{
alert("SUCCESS");
}
}
});
}
</script>
PHP
$session_id = rand();
loginCheck($username,$password);
function loginCheck($username,$password)
{
$password = encryptPassword($password);
if (getUser($username,$password) == 1)
{
refreshUID($session_id);
$data = array("success" => true);
echo json_encode($data);
}
else
{
$data = array("success" => false);
echo json_encode($data);
}
}
function refreshUID($session_id)
{
#Update User Session To Database
session_start($session_id);
}
function encryptPassword($password)
{
$password = $encyPass = md5($password);
return $password;
}
function getUser($username,$password)
{
$sql="SELECT * FROM webManager WHERE username='".$username."' and password='".$password."'";
$result= mysql_query($sql) or die(mysql_error());
$count=mysql_num_rows($result) or die(mysql_error());
if ($count = 1)
{
return 1;
}
else
{
return 0;;
}
}
?>
I'm attempting to create a login form which will provide the user with information telling him if his username and password are correct or not.
There are several critical syntax problems in your code causing invalid data to be sent to server. This means your php may not be responding with JSON if the empty fields cause problems in your php functions.
No data returned would mean result.success doesn't exist...which is likely the error you see.
First the selectors: $("username") & $("password") are invalid so your data params will be undefined. Assuming these are element ID's you are missing # prefix. EDIT: turns out these are not the ID's but selectors are invalid regardless
You don't want to use serialize() if you are creating a data object to have jQuery parse into formData. Use one or the other.
to make it simple try using var username = $("#inputUsername").val(). You can fix ID for password field accordingly
dataType is in your options object twice, one with a typo. Remove datatype:"json", which is not camelCase
Learn how to inspect an AJAX request in your browser console. You would have realized that the data params had no values in very short time. At that point a little debugging in console would have lead you to some immediate points to troubleshoot.
Also inspecting request you would likely see no json was returned
EDIT: Also seems you will need to do some validation in your php as input data is obviously causing a failure to return any response data
Try to add this in back-end process:
header("Cache-Control: no-cache, must-revalidate");
header('Content-type: application/json');
header('Content-type: text/json');
hope this help !
i testet on your page. You have other problems. Your postvaribales in your ajax call are missing, because your selectors are wrong!
You are trying to select the input's name attribute via ID selector. The ID of your input['name'] is "inputUsername"
So you have to select it this way
$('#inputUsername').val();
// or
$('input[name="username"]').val();
I tried it again. You PHP script is responsing nothing. Just a 200.
$.ajax({
type: 'POST',
url: 'secure/check_login.php',
dataType: "json",
data: 'username='+$("#inputUsername").val()+'&password='+$("#inputPassword").val(),
success: function(result) {
if (result.success != true){
alert("ERROR");
} else {
alert("HEHEHE");
}
}
});
Try to add following code on the top of your PHP script.
header("Content-type: appliation/json");
echo '{"success":true}';
exit;
You need to convert the string returned by the PHP script, (see this question) for this you need to use the $.parseJSON() (see more in the jQuery API).

Categories