I have some difficulties to call PHP script with:
$("#tata").click(function(){
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
});
});
But my alert is empty... I am sure that the URL is correct, because if I add in my PHP file HTML code it appear on my alert!
I am sure that my PHP code works
PHP file:
echo "lalalala";
$getData = new mod_visitor();
$writeData = new writeData();
$urlPart1 = $_SERVER['HTTP_HOST'];
$urlPart2 = $_SERVER['REQUEST_URI'];
$pageEnCours = $urlPart1 .= $urlPart2;
$getData->get_ip();
$getData->LookupIP($GLOBALS['domain']);
$getData->ValidateIP($GLOBALS['domain']);
if ($GLOBALS['domain'] && $pageEnCours != preg_match("#localhost/joomla/$#", $pageEnCours)) {
$GLOBALS['domain'] = trim($GLOBALS['domain']);
if ($getData->ValidateIP($GLOBALS['domain'])) {
echo "cc";
$result = $getData->LookupIP($GLOBALS['domain']);
$writeData->write_domain($result);
} else {
echo "erreur";
$writeData->write_error();
};
} else {
echo "je ne rentre pas dans la boucle";
};
echo $pageEnCours;
echo $GLOBALS['domain'];
Parse the dataType to 'json'
Add dataType: 'json' to the javascript
$.ajax({
url : 'http://localhost/joomla/modules/mod_visitor/helper.php' ,
type : 'GET' ,
dataType: 'json',
success: function(data) {
alert(data);
},
error : function(resultat, statut, erreur){
console.log("no")
}
And echo back as JSON in your php
<?php
echo json_encode('lalala');
?>
If you want to return multiple items, you can return them as an array
<?php
$return = array(
'pageEnCours' => $urlPart1 . $urlPart2,
'domain' => $GLOBALS['domain']
);
echo json_encode($return);
?>
And get the items client-side
success: function(data) {
console.log(data.pageEnCours, data.domain);
}
Related
I am working with CodeIgniter and jQuery ajax. I want to upload image using ajax. But it shows an error like You did not select a file to upload.
Here,I have write jQuery :
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = jQuery(this).serialize();
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
<form id="signup_form" method="post" enctype="multipart/form-data">
<div class="row">
<div class="col-md-3">Upload Photo</div>
<div class="col-md-4">
<input type="file" name="pic" accept="image/*">
</div>
</div>
<div class="row">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</form>
And My function looks like this :
function ajax_register()
{
if($this->input->post())
{
$this->form_validation->set_rules('pass', 'Password', 'required|matches[cpass]');
$this->form_validation->set_rules('cpass', 'Password Confirmation', 'required');
if($this->form_validation->run() == true)
{
$img = "";
$config['upload_path'] = './uploads/user/';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('pic'))
{
$data['error'] = array('error' => $this->upload->display_errors());
print_r($data['error']);exit;
$data['flash_message'] = "Record is not inserted";
}
else
{
$upload = $this->upload->data();
//print_r($upload);exit;
$data = array(
'ip_address' =>$this->input->ip_address(),
'first_name' =>$this->input->post('firstname'),
'last_name' =>$this->input->post('lastname'),
'phone' =>$this->input->post('phone'),
'email' =>$this->input->post('email'),
'group_id' =>$this->input->post('role'),
'password' =>$this->input->post('password'),
'image' =>$upload['file_name'],
'date_of_registration' =>date('Y-m-d')
);
print_r($data);exit;
$user_id = $this->admin_model->insert_user($data);
$user_group = array(
'user_id' => $user_id,
'group_id' => $this->input->post('role')
);
$this->admin_model->insert_group_user($user_group);
echo "<p style='color:red;'>You are successfully registerd.</p>";
}
}
else
{
echo "<p style='color:red;'>".validation_errors()."</p>";
}
}
}
So how to resolve this issue?What should I have to change in my code?
As I said, the problem is probably in the data you send to backend. If you want to submit AJAX with input file, use FormData.
Try this:
jQuery(document).on('submit', '#signup_form', function()
{
//debugger;
var data = new FormData($('#signup_form')[0]);
jQuery.ajax({
type : 'POST',
url : '<?php echo base_url()."front/ajax_register"; ?>',
data : data,
processData: false,
contentType: false,
success : function(data)
{
jQuery(".result").html(data);
}
});
return false;
});
Try this:
$('#upload').on('click', function() {
var file_data = $('#pic').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url : 'upload.php', // point to server-side PHP script
dataType : 'text', // what to expect back from the PHP script, if anything
cache : false,
contentType : false,
processData : false,
data : form_data,
type : 'post',
success : function(output){
alert(output); // display response from the PHP script, if any
}
});
$('#pic').val(''); /* Clear the file container */
});
Php :
<?php
if ( $_FILES['file']['error'] > 0 ){
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else {
if(move_uploaded_file($_FILES['file']['tmp_name'], 'uploads/' . $_FILES['file']['name']))
{
echo "File Uploaded Successfully";
}
}
?>
This will upload the file.
P.S.: Change the code as per CI method.
var data = jQuery(this).serialize();
this refers to document
i have this ajax form validation code igniter. my view is something like this
<?php
echo form_open('Provinces/create',array('id' => 'form-user'));
?>
<label for="PROVINCE" class="col-sm-2 control-label col-sm-offset-2">Province Name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="PROVINCE" name="PROVINCE" value = "<?= set_value("PROVINCE"); ?>">
</div>
<button class="btn btn-info fa fa-save" type="submit">  Save</button>
<a href = '<?php echo base_url().'Provinces/index'; ?>' class = 'btn btn-danger fa fa-times-circle'>  Cancel</a>
<?php
echo form_close();
?>
and i have this javascript
<script>
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
url = "<?php echo site_url('Provinces/ajax_add')?>";
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
alert('success');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
</script>
i have found this code on google and just customized it. but the problem is, i am not that familiar with ajax, the part where the form validation fails, work perfectly fine, but when it is succes, even though it shows alert('success'); it doesnt add the value in the database. i need to finish this projects in a few weeks. please help.
here is where i get the validations,
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
also here is my ajax_add
public function ajax_add()
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}
and here is my model,
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
i have solved it. just did put
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
into my controller, which makes my controller
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
and my javascript
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
$('.alert-success').delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
})
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
You dont't need to use uppercase when accessing your controller
just use
url = "<?php echo site_url('provinces/ajax_add')?>";
Validation the request data before inserting
try
public function ajax_add()
{
$response = array(
'success' => false
) ;
$this->load->library('form_validation');
// add your validation
$this->form_validation->set_rules('PROVINCE', 'PROVINCE', 'required');
if ($this->form_validation->run() == FALSE)
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE')
);
$insert = $this->Provinces_Model->save($data);
if($insert){
$response['success'] = TRUE ;
$response['message'] = 'Record created successfully' ;
}
else{
$response['message'] = 'Unable to create record' ;
}
}
else
{
$response['message'] = 'Invalid data' ;
}
echo json_encode($response);
}
Then check for the 'message' index in your ajax response in the javascript code
This will give an idea of where there is problem, whether its from the
view or
controller or'
Model
I am calling a php function from javascript by passing three arguments, on the other side php function inside the php file gets two values from database and prints all the value. for that I have written this code but this is not working, means this code prints nothing in the output so kindly help.
javascript code
jQuery.ajax(
{
type: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:["className", "student_id", "isPresent"]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});
php code
<?php
header('Content-Type: application/json');
if( $_POST['functionname'] == 'saveUser' ) {
include_once("dbConnection.inc");
$db = db_connect();
$newSql = "SELECT class_id, date FROM class_session WHERE class_id = (select max(class_id) from class_session)";
$result = mysql_query($newSql, $db);
$row = mysql_fetch_array($result);
$class_id = $row["calass_id"];
$date = $row["date"];
echo json_encode(Array(
'result' => $_POST['arguments'][0] .' '. $_POST['arguments'][1] .' '. $_POST['arguments'][2] .' '. $class_id .' '. $date
));
}
?>
The right property is method not type, see jQuery.ajax()
jQuery.ajax({
method: "POST",
url: 'save.php',
dataType: 'json',
data: {functionname:'saveUser', arguments:["className", "student_id", "isPresent"]},
success: function (obj, textstatus) {
if( !('error' in obj) ) {
alert(obj.result);
}
else {
console.log(obj.error);
}
}
});
I'm trying to send a message from php to ajax. I'm using echo json_encode to do it. When I do that, the website displays the arrays message. ({"foo":"content of foo"}). How can I get it to not display the message?
Also, the alerts from ajax don't get called.
Here's the code:
<?php
$myString = $_POST['data'];
if ($myString == "") {
echo json_encode(
array()
);
} else if ($myString == "foo" {
echo json_encode(
array(
'foo2' => 'this is the contents of foo'
)
);
} else if ($myString == "foo2") {
echo json_encode(
array(
'foo2' => 'this is the contents of foo2'
)
);
}
?>
<script>
var formData = new FormData($(this)[0]);
$.ajax({
url: $(this).attr("action"),
context: document.body,
data: formData,
type: "POST",
contentType: false,
processData: false,
success: function(response) {
if (response.length == 0) {
alert("empty");
} else if (response.foo) {
alert("foo");
} else if (respons.foo2) {
alert("foo2");
}
}
});
</script>
How can I get the array to not display on the website? And why are the ajax if statements not getting called?
You need to set the HTTP header at the top of the script so you can return son:
header('Content-type: application/json');
Your script is a little confusing. You can't return json AND html/javascript.
It's one or the other.
I am making a login form on HTML using JSON and PHP but all of the if statements on success are not working but the beforeSend and error is working. Can you help me check my mistakes?
I dont know know what is wrong with the function on success. The alerts are not popping up. For example response.success == true is supposed to pop up ' You are successfully logged in... '
<script>
$(document).ready(function(){
$('#loginForm').on('submit',function(e){
var myForm = new FormData($(this)[0]);
$.ajax({
type:'POST',
url: 'connections/login.php',
data : new FormData($(this)[0]),
cache: false,
contentType:false,
processData: false,
beforeSend: function(){
$("div#divLoading").show();
},
success: function(response){
$("div#divLoading").hide();
console.log(response);
if(response.success == true)
{
alert(' You are successfully logged in... ')
}
else if( response.success == false ){
alert('please enter a correct email & password');
}
else{
if(response.matric){
alert('email is wrong');
}
if(response.password){
alert('password is wrong');
}
}
},
error: function(data){
alert('error');
$("div#divLoading").hide();
}
});
return false;
});
});
</script>
Here is my PHP:
<?php
require_once('connect.php');
session_start();
header('Content-Type: application/json');
if (!empty($_POST['matric']))
{
$matric=$_POST['matric'];
$password=$_POST['password'];
$pass= $dbh->prepare("SELECT * FROM users WHERE matric=:matric AND password=:password");
$pass->bindParam(':matric', $matric);
$pass->bindParam(':password', $password);
$pass->execute();
if($pass->fetch(PDO::FETCH_NUM) > 0)
{
$_SESSION['matric']=$matric;
$response = array(
'success' => true,
'message' => 'Login successful');
}
else
{
$response = array(
'success' => false,
'message' => 'Login fail');
}
}
echo json_encode($response);
echo json_encode($_POST);
?>
You have
echo json_encode($response);
echo json_encode($_POST);
which is going to issue corrupted JSON. e.g. your output is going to be
{"success":true,"message":"Login successful"}Array
^^^^^^---corruption
Since your JSON is corrupted, it won't decode properly, and response WON'T be what you think it is.
Remove this line:
echo json_encode($_POST);