AJAX response returns html content - javascript

I have an AJAX call in my codeigniter project. Here is my code:
in view :
$('#forgotPassword').click(function() {
var base_url = '<?php echo base_url()?>';
$('#forgotPasswordEmailError').text('');
var email = $('#forgotPasswordEmail').val();
console.log(email);
if(email == ''){
$('#forgotPasswordEmailError').text('Email is required');
}else{
$.ajax({
url : base_url + 'Home/forgotPassword',
type : 'POST',
data : {email : email},
success: function(data) {
console.log(data);
//location.reload();
}
});
}
});
and controller :
public function forgotPassword() {
$email = $this->input->post('email');
echo $email;
}
but the response contains only the html content from my view. I couldn't identify what is happening.

change your jquery code to
$('#forgotPassword').click(function() {
var base_url = '<?php echo base_url()?>';
$('#forgotPasswordEmailError').text('');
var email = $('#forgotPasswordEmail').val();
console.log(email);
if(email == ''){
$('#forgotPasswordEmailError').text('Email is required');
}else{
$.ajax({
url : base_url + 'Home/forgotPassword',
type : 'POST',
data : {email : email},
dataType:'json',
success: function(data) {
console.log(data);
//location.reload();
}
});
}
});
change your controller code like
public function forgotPassword() {
$email = $this->input->post('email');
$response = ["email" => $email];
echo json_encode($response);
}

Instead of
echo $email;
use:
$response = ["email" => $email];
return json_encode($response);
And parse JSON, on client side, using JSON.parse.

hi maybe i can help someone, i had the same problem, in my case the error was here "url : base_url + 'Home/forgotPassword'"
in this example i have to pass all way like this url : /anotherdirectory/Home/forgotPassword.php',
take a look in your "url"
$.ajax({
url : "change here fo works"',
type : 'POST',
data : {email : email},
dataType:'json',
success: function(data) {
console.log(data);
//location.reload();
}

Related

How to upload an image to server directory using ajax?

I have this ajax post to the server to send some data to an SQL db :
$.ajax({
method: "POST",
url: "https://www.example.com/main/public/actions.php",
data: {
name: person.name,
age: person.age,
height: person.height,
weight: person.weight
},
success: function (response) {
console.log(response)
}
})
in the server i get this data with php like this :
<?php
include "config.php";
if(isset ( $_REQUEST["name"] ) ) {
$name = $_REQUEST["name"];
$age = $_REQUEST["age"];
$height = $_REQUEST["height"];
$weight = $_REQUEST["weight"];
$sql = "INSERT INTO persons ( name, age, height, weight )
VALUES ( '$name', '$age', '$height', '$weight' )";
if ($conn->query($sql) === TRUE) {
echo "New person stored succesfully !";
exit;
}else {
echo "Error: " . $sql . "<br>" . $conn->error;
exit;
}
};
?>
I also have this input :
<input id="myFileInput" type="file" accept="image/*">
and in the same directory as actions.php i have the folder /images
How can i include an image ( from #myFileInput ) in this ajax post and save it to the server using the same query in php ?
I have searched solutions in SO but most of them are >10 years old,i was wondering if there is a simple and modern method to do it,i'm open to learn and use the fetch api if its the best practice.
You should use the formData API to send your file (https://developer.mozilla.org/fr/docs/Web/API/FormData/FormData)
I think what you are looking for is something like that:
var file_data = $('#myFileInput').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'https://www.example.com/main/public/actions.php',
contentType: false,
processData: false, // Important to keep file as is
data: form_data,
type: 'POST',
success: function(php_script_response){
console.log(response);
}
});
jQuery ajax wrapper has a parameter to avoid content processing which is important for file upload.
On the server side, a vrey simple handler for files could look like this:
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'];
}
else {
move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']);
}
?>
via ajax FormData you can send it . refer here . Note : data: new FormData(this) - This sends the entire form data (incldues file and input box data)
URL : https://www.cloudways.com/blog/the-basics-of-file-upload-in-php/
$(document).ready(function(e) {
$("#form").on('submit', (function(e) {
e.preventDefault();
$.ajax({
url: "ajaxupload.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
beforeSend: function() {
//$("#preview").fadeOut();
$("#err").fadeOut();
},
success: function(data) {
if (data == 'invalid') {
// invalid file format.
$("#err").html("Invalid File !").fadeIn();
} else {
// view uploaded file.
$("#preview").html(data).fadeIn();
$("#form")[0].reset();
}
},
error: function(e) {
$("#err").html(e).fadeIn();
}
});
}));
});
If you are not averse to using the fetch api then you might be able to send the textual data and your file like this:
let file=document.querySelector('#myFileInput').files[0];
let fd=new FormData();
fd.set('name',person.name);
fd.set('age',person.age);
fd.set('height',person.height);
fd.set('weight',person.weight);
fd.set('file', file, file.name );
let args={// edit as appropriate for domain and whether to send cookies
body:fd,
mode:'same-origin',
method:'post',
credentials:'same-origin'
};
let url='https://www.example.com/main/public/actions.php';
let oReq=new Request( url, args );
fetch( oReq )
.then( r=>r.text() )
.then( text=>{
console.log(text)
});
And on the PHP side you should use a prepared statement to mitigate SQL injection and should be able to access the uploaded file like so:
<?php
if( isset(
$_POST['name'],
$_POST['age'],
$_POST['height'],
$_POST['weight'],
$_FILES['file']
)) {
include 'config.php';
$name = $_POST['name'];
$age = $_POST['age'];
$height = $_POST['height'];
$weight = $_POST['weight'];
$obj=(object)$_FILES['file'];
$name=$obj->name;
$tmp=$obj->tmp_name;
move_uploaded_file($tmp,'/path/to/folder/'.$name );
#add file name to db????
$sql = 'INSERT INTO `persons` ( `name`, `age`, `height`, `weight` ) VALUES ( ?,?,?,? )';
$stmt=$conn->prepare($sql);
$stmt->bind_param('ssss',$name,$age,$height,$weight);
$stmt->execute();
$rows=$stmt->affected_rows;
$stmt->close();
$conn->close();
exit( $rows ? 'New person stored succesfully!' : 'Bogus...');
};
?>

ajax jquery always running Error;

Ajax jquery always running error function, althought success function run and i can get session value,i can't run window.location="profile.php";
$(document).ready(function(){
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
type: "POST",
url: "model/user.php",
data: {
user_log : username,
password : password
},
dataType: 'json',
error: function (xhr,textStatus,errorThrown) {
$("#error").html("<span style='color:#cc0000'>Error:</span> Invalid username and password. ");
},
success: function(json){
window.location="profile.php";
},
beforeSend:function()
{
$("#error").html("<img src='http://www.chinesecio.com/templates/base/images/loading.gif' /> Loading...")
}
});
return false;
});
});
user.php
<?php
ob_start();
session_start();
error_reporting(E_ALL & ~E_NOTICE & ~E_DEPRECATED);
require_once(dirname(__FILE__).'/../model/connect.php');
?>
<?php
global $pdo;
if(isset($_POST['user_log'])) {
// username and password sent from Form
$username=$_POST['user_log'];
$password=$_POST['password'];
$qr= "SELECT * FROM user where username='$username' AND password='$password'" ;
$stmt= $pdo->query($qr);
$row= $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$_SESSION['id']=$row['id'];
$_SESSION['name_mem']=$row['username'];
$_SESSION['level_mem']=$row['level'];
}
header("location:../../../../index.php");
}
?>
Remove this line :
header("location:../../../../index.php");
If above doesn't work, omit this from ajax properties :
dataType: 'json',
you can use ajax like this,
<script>
$("#login").click(function(){
var username=$("#usern").val();
var password=$("#user").val();
$.ajax({
xhr: function() {
var xhr = new window.XMLHttpRequest();
//progress
xhr.upload.addEventListener("progress", function(e) {
//progress value : you can load progress bar in here
}, false);
return xhr;
},
type: "POST",
url: "model/user.php",
data: {'username' : username, 'password' : password},
dataType:json,
success: function(msg) {
//when success //200 ok
if(msg.status=="done"){
window.location="profile.php";
}else{
$("#error").html("<span style='color:#cc0000'>Error:</span> "+msg.massage);
}
},
error: function(jqXHR, textStatus, errorThrown) {
//when error: this statement will execute when fail ajax
}
});
});
</script>
server side code like this(inside user.php),
$username=$_POST['username'];
$password=$_POST['password'];
...........
//$status="fail" or "done"
//success must be always success
//$massage= "password or username not match"
$respond=array("success"=>"success","status"=>$status,"massage"=>$massage);
echo json_encode($respond);
exit;
I hope you useful this.

Load Json data with AJAX and PHP

I'm triing to load a json data with ajax, but it doesn't work. Everytime ajax call the error function and doesn't call the success function.
my AJAX call :
$(document).on("click", "#myMovies .btn-update", function() {
var id = $(this).parent().data("id");
$.ajax({
url : 'index.php',
type : 'POST',
dataType: 'json',
data : 'id=' + id + '&action=update',
success : function(data){
$('#updateMovie')
.find('[name="title"]').val(data.title).end()
.find('[name="list"]').val(data.list).end();
},
error : function(jqXHR, textStatus, errorThrown){
console.log("error");
alert(textStatus);
alert(errorThrown);
}
});
});
The interessing part of index.php :
else if($_POST['action'] == "update") {
/*getSpecificMovie($_POST['id']);
$movies = getSpecificMovie();
$results = Utils::secureMoviesJSON($movies);
echo $results;*/
header("Content-Type: application/json", true);
$array = array(
'title' => 'test',
'list' => 'test');
echo json_encode( $array, JSON_FORCE_OBJECT );
}
Anyone know where is my mistake ?
Thank you for your answer.
I think the problem is at the 'JSON_FORCE_OBJECT' option. The data type the request expected is a json string. When adding JSON_FORCE_OBJECT to the json_encode function, the json string is not valid for the request.
else if($_POST['action'] == "update") {
/*getSpecificMovie($_POST['id']);
$movies = getSpecificMovie();
$results = Utils::secureMoviesJSON($movies);
echo $results;*/
header("Content-Type: application/json", true);
$array = array(
'title' => 'test',
'list' => 'test');
echo json_encode( $array);
die();
}
Also add a parser for the json to your javascript (parseJSON):
success : function(data){
data = $.parseJSON(data);
$('#updateMovie')
.find('[name="title"]').val(data.title).end()
.find('[name="list"]').val(data.list).end();
},

Send Array of Json from Ajax to PHP

I try to send an array of json objects from the javascript to a Php code. Unable to get a response from the php file.
function getData() {
var jsonObject = [];
var genderMenu = document.getElementById("gender");
var levelMenu = document.getElementById("level");
jsonObject[0] = {
psid: document.getElementById("psid").value,
fName: document.getElementById("fname").value,
lName: document.getElementById("lname").value,
gender: genderMenu.options[genderMenu.selectedIndex].value,
};
for(var i = 1; i <= varCount; i++) {
if(document.getElementById("fName"+(i))) {
jsonObject[i] = {fName : document.getElementById("fName"+(i)).value,
lName: document.getElementById("lName"+(i)).value,
};
}
}
var jsonObjectString = JSON.stringify(jsonObject);
var result = "";
$.ajax({
type: 'POST',
url: '/inviteProcessing.php',
data: {myData: jsonObject},
success: function(response) {
if(response.success)
alert(response.message);
else
alert(response.message);
}
});
alert(jsonObject);
}
Php File has the following code
<?php
$input = $_POST['myData'];
$input_string = json_decode($input, true);
echo json_encode( array('success' => true, 'message' => $input_string) );
?>
Do u see any problem?
Prior to echoing your output, try...
header('Content-type: application/json');
echo $encodedjsonstring;
exit;
Please try below points.
First check if path of the php file is correct.
Then add below line in ajax call.
type: 'POST',
dataType: "json", //add dataType
url: '/inviteProcessing.php',
data: {myData: jsonObject},
try to put exit or die() at the end of php file

JSON ajax and jquery, cannot get to work?

I have the following script in my javascript...
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
data: {email: val},
success: function(response) {
alert(response);
}
});
And my php file looks like this...
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
}
else {
echo json_encode(error = true);
}
}
I cannot get either the variable error of true or false out of the ajax call?
Does it matter how I put the data into the ajax call?
At the minute it is as above, where email is the name of the request, and val is a javascript variable of user input in a form.
Try this instead. Your current code should give you a syntax error.
if (!$q -> rowCount()) {
echo json_encode(array('error' => false));
}
else {
echo json_encode(array( 'error' => true ))
}
In your code, the return parameter is json
$.ajax({
type: 'POST',
url: 'http://www.example.com/ajax',
dataType: 'json',
data: {email: val},
success: function(response) {
alert(response);
}
});
PHP FILES
if ($_REQUEST['email']) {
$q = $dbc -> prepare("SELECT email FROM accounts WHERE email = ?");
$q -> execute(array($_REQUEST['email']));
if (!$q -> rowCount()) {
echo json_encode(error = false);
return json_encode(error = false);
} else {
echo json_encode(error = true);
return json_encode(error = true);
}
}

Categories

Resources