PHP json response not working - php

I am doing an ajax update. I just want a response of success or failure so I know how to handle some things in the front end. Problem is it isn't working. Brand new to all of this.
$('.delete-template-popup .confirm').on('click', function() {
var templateName = $('.loaded-template-name').html();
var templateArray = {};
templateArray.templateName = templateName;
var JSONObject = [templateArray];
var templateJson = JSON.stringify(JSONObject);
$.ajax({
url: 'http://localhost/ds-layouts/public/delete-template.php',
type: 'post',
data: {"templatePHP" : templateJson},
success: function(data) {
console.log(data)
if (data.status == "success") {
console.log(1)
}
// if (data.status == "success") {
// closePopup($('.delete-template-popup'));
// window.location.replace("http:////localhost/ds-layouts/public/manage-layouts.php");
// } else {
// $('.delete-template-popup .error').show().html('An error occurred processing your request. Please try again. If this error persists contact blah.');
// }
}
});
});
and the php
if ($flag) {
//mysqli_commit($connection);
if ($debug) {
echo "pass";
echo "\r\n";
}
//$_SESSION["message"] = "Template delete was successful.";
//header('Content-Type: application/json');
header('Content-Type: application/json; charset=UTF8');
echo json_encode(array('status' => 'success'));
} else {
if ($debug) {
echo "fail";
echo "\r\n";
}
//mysqli_rollback($connection);
// header('Content-Type: application/json');
// echo json_encode(array('status' => 'failure'));
}
So the deal is I am getting into the if block of the php statment fine. If I have the header part of the block I get all of my echo statements passed properly and I can read them in Chromes developer console. The moment I uncomment the header statement nothing works. This is for either one of $flag cases true or false.
I have this same type of script in another area and it works absolutely fine. Don't mind the comments. I was just commenting things out as a way to figure out where things were breaking. That is how I determened the header was causing it.

Maybe adding the dataType: "json", to your AJAX request object will help?

try this php
header('Content-Type: application/json'); //must be FIRST output.
if ($flag) {
//mysqli_commit($connection);
if ($debug) {
echo json_encode(array('debug' => 'pass'));
}
else
{
echo json_encode(array('status' => 'success'));
}
} else {
if ($debug) {
echo json_encode(array('debug' => 'fail'));
}
else
{
//mysqli_rollback($connection);
echo json_encode(array('status' => 'failure'));
}
}
I've changed the debug blocks to return json, since turning on debug will break the ajax anyway.

As the answer was posted as a comment I can't mark the answer as fixed. I am going to mark this answer as the what fixed the issue:
"The header must be before echo – user4035"
Thank you user4035 for letting me know about the header being before any echos aka before any printed form of html from the server...I should have known that.

Related

jquery ajax returning true but not display proper message in php

I have the following code writing in ajax which sent a request to the back-end
$.ajax({
type: "POST",
url: action,
data: str,
success: function(msg) {
//alert(msg);
if (msg == 'sent') {
alert("success");
$('#errormessage').html('<div class="alert alert-success">Email sent successfully.</div>');
$('.contactForm').find("input, textarea").val("");
}else if (msg == 'saved') {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html('<div class="alert alert-warning">Email couldn\'t be sent but not too worry we got it in our database. We will get back to you.</div>');
$('.contactForm').find("input, textarea").val("");
}
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
}
});
php code
$to_email = $set['Email'];
$headers = "From: ". $email;
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($email);
if ($secure_check == false) {
echo "Invalid input";
} else { //send email
$query = mysqli_query($mysqli,"INSERT INTO emails(name,email,subject,message)VALUES('$name','$email','$sub','$msg')");
$mail = mail($to_email,$sub,$msg,$headers);
if($query and $mail){
echo 'sent';
}else if($query and !$mail){
echo 'saved';
}else{
echo $mysqli->error;
}
}
If I send an email it successfully executed with the insertion. The issue I am facing is that ajax is not printing out the right message. It only execute the else part which displayed sent
This part of the code is not exected:
if (msg == 'sent') {
alert("success");
$('#errormessage').html('<div class="alert alert-success">Email sent successfully.
</div>');
$('.contactForm').find("input, textarea").val("");
}
instead, this is displayed with just sent message
else {
$("#sendmessage").removeClass("show");
$("#errormessage").addClass("show");
$('#errormessage').html(msg);
}
The issue is most likely because you're returning a text-based response and there is whitespace around the value so msg == 'sent' is never true.
To fix this you could simply call trim() to remove the whitespace:
if (msg.trim() == 'sent') {
// your code...
}
Alternatively you can change your PHP to return a serialised data structure, such as JSON or XML, to avoid this problem. I would suggest doing this.

PHP Script doesnt return variables to AJAX

The code is for simple login validation.
The PHP script doesnt seem to run when returning values to JavaScript but runs fine when there are not variables to return.
So is there anything wrong or do I need to add anything else to return the values from PHP.
<?php
header('Content-type: application/json; charset=utf-8');
include("config.php");
$formd=array();
//Fetching Values from URL
$username2=$_POST['username1'];
$password2=$_POST['password1'];
$query = mysqli_query($db,"SELECT username FROM login WHERE username = '$username2'");
$result=mysqli_fetch_assoc($query);
$sql=mysqli_query($db,"SELECT password FROM login WHERE username = '$username2'");
$resul=mysqli_fetch_assoc($sql);
$row = mysqli_fetch_array($query,MYSQLI_ASSOC);
$count = mysqli_num_rows($query);
$pass=$resul['password'];
if((password_verify($password2,$pass))and($count==1)) {
echo "ds";
} else {
echo "no";
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit();
?>
JavaScript
<script>
$(document).ready(function(){
$("#submit").click(function(){
var username = $("#username").val();
var password = $("#password").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'username1='+ username + '&password1='+ password;
if(username==''||password=='') {
alert("Please Fill All Fields");
} else {
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
dataType: "json",
data: dataString,
success: function(data){
alert(data.no);
}
});
}
return false;
});
});
</script>
your Php code has 2 echo statements
if((password_verify($password2,$pass))and($count==1))
{
echo "ds"; // first
}
else
{
echo "no"; // first
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd); // second
This way, your php script returns malformed JSON data and hence $.ajax() cannot handle it.
Also, as others pointed out, please use the developer console to verify your script returns the expected data.
The if else part of your php script has an echo statement and then outside the if else you echo the array $formd. This malforms the JSON response. Also, you should use exit(1) as there is no exception being raised in your code.
Here the snippet you should use to get the script working.
if((password_verify($password2,$pass))and($count==1))
{
echo "ds";
}
else
{
// echo "no"; this is not required
$formd['no']="Invalid password or username"
}
mysqli_close($db); // Connection Closed
echo json_encode($formd);
exit(1);

Saving variable value in a text file using PHP

by clicking on a button I am setting a variable in php using Ajax.
submitInfo(var1);
function submitInfo(var1)
{
$.ajax({
type: "POST",
url: "js/info.php",
data: {Info:var1},
success: function (result)
{
alert(result);
}
});
}
in my php code, How can I save "var1" in a text file? I have used this to save variable in a text file but it is not saving anything there:
<?php
if (isset($_POST['var1']))
{
echo $_POST['var1'];
}
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
?>
The first issue is that in your JQuery you actually assigning the var1 variable to 'Info'
so the $_POST array will contain this rather than var1.
You then only want to manage your attempts to write to the file in order to get nicer, more user friendly error messages which will give you something nicer to send back and help you if debug any other problems.
<?php
$var1 = "";
$filename = "js/test.txt";
// Get the correct $_POST object
if (isset($_POST['Info']) {
$var1 = $_POST['Info'];
}
// If the variable is not empty try to write your file
if (!empty($var1)) {
if(!$file = fopen($filename,"w")) {
$msg = "Cannot open file");
} else if (fwrite($file,$var1) === false) {
$msg = "Cannot write to file");
} else {
$msg => 'all was good'
}
fclose($file);
$result = array(
'error' => 'false',
'msg' => $msg
);
} else {
$result = array(
'error' => 'true',
'msg' => 'Info was empty'
);
}
// Send your message back
echo "{\"result\":".json_encode{$result)."}";
PS: Not tested this so fingers crossed there are no typos.
Try this:
<?php
if (isset($_REQUEST['Info'])){
$var1 = $_REQUEST['Info'];
$file = fopen("js/test.txt","w");
echo fwrite($file,$var1);
fclose($file);
}
?>

error handling during ajax file upload using jquery form plugin

i have a situation where i'm stuck at the idea of catching the appropriate error during file upload in the ajax response in jquery form-plugin.
i'l give an idea of what i want to achieve through some pseudocode.
My php is :
$file = strtolower($_FILES["myfile"]["name"]);
$extension = substr($file, strrpos($file, '.') + 1);
if($extension == 'jpg'){
// upload the file
if(move_uploaded_file($_FILES["myfile"]["tmp_name"], $folder . $finalFilename)){
// do something here like
echo "<div id='statusContainer'>
<table><tr><td>
<img src='uploads/".$finalFilename."'>
</td></tr>
<tr><td>".$finalts."</td></tr></table>
</div>";
}
} else {
$error = 1; // will give numbers to different errors like filetype error, size error etc..
}
now my JS code is :
(function() {
var status = $('#status');
$('form').ajaxForm({
complete: function(xhr) {
if(xhr.responseText == "// what do i get echoed here so i can run an array and show user appropriate error like size error, type error etc. // "){
// i want to open a dialog box with correct error message//
} else{
status.hide().html(xhr.responseText).fadeIn(1000);
}
}
});
})();
shall i get the error number echoed in the ajax response and run through an array to get the message? but then i'll have to put in a lot of if conditions in the ajax response with different error numbers.
Please anyone have a more logical idea??
you could make an array and pass error json_encode()'ing it and parse json response from ajaxForm, like
php part:
$responseArr = array();
if( file_is_uploaded ) {
$responseArr["error"] = "0";
$responseArr["message"] = "File uploaded success message";
}
else {
$responseArr["error"] = "1";
$responseArr["message"] = "Error message here";
}
echo json_encode($responseArr); //pass it as response
js part::
$('form').ajaxForm({
dataType: "json",
success: function(response) {
//parse json response and perform accordingly
console.log( response );
}
});
To cut down on traversing an array in JS, and matching error IDs to descriptions, could you associate the error description itself to be relayed in the ajax response? This would keep your JS lean and keep error handling serverside.
Example:
<tr><td>".$finalts."</td></tr></table>
</div>";
}
$error_descriptions = array("Filesize Error", "Extension Error");
} else {
$error = error_descriptions[1];
}

I need a help with this script ($.ajax())

Ajax:
$.ajax({
url: 'process.php',
type: 'post',
data: 'loginName=' + $("#loginName").val() + 'loginPass=' + $("#loginPass").val(),
dataType: 'json',
success: function(data){
if(data.success)
{
location.href = data.redirect;
}
else
{
alert(data.message);
}
}
});
And here is process.php code:
<?
$data = array();
if($_SERVER['REQUEST_METHOD'] == 'POST'){
if($_POST['loginName'] == "test" && $_POST['loginPass'] == "test")
{
$data['redirect'] = "home.php";
$data['success'] = true;
echo json_encode($data);
}
else
{
$data['message'] = "<div id=Message>Your info is wrong...</div>";
$data['success'] = false;
echo json_encode($data);
}
}
?>
Sorry, but I'm from the Czech Republic and I don't speak english :D
Your data: misses a & right before loginPass=, which would lead to a garbled request. But maybe you should give jQuery an data object there anyway (it takes care of proper url encoding):
type: 'POST',
data: {loginName: $("#loginName").val(), loginPass: $("#loginPass").val()},
A second problem might be the lack of content-type in the php script. Add following on top (just to be sure this isn't why the result goes ignored):
<?php
header("Content-Type: application/json");
Another thing: You need more braces in the if statement, because && has higher precedence than the == comparison:
if(($_POST['loginName'] == "test") && ($_POST['loginPass'] == "test")) {
Since it is seemingly a PHP error, you must turn on error_reporting(E_ALL) and display_errors in the php.ini; If you still get no content returned from your URL, then add a print 'test123'; on top. And/or remove the test for REQUEST_METHOD (this adds no security anyway).

Categories