not receiving data in php codeigniter when sending ajax post - php

I'm trying to send data by post using ajax (with codeigniter) and I don't know why but I don't receive anything...
This is how I send it:
var sendData = $('#formContact').serialize();
$.ajax({
type: 'POST',
url: '<?php echo base_url()?>/intranet/update/updateProfile',
data: sendData,
dataType: 'json',
success: function (data)
{
console.log(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
and this is an example of my form:
<form id="formContact" action="update" method="POST">
<input class="headInput" type="text" name="userName" value="Tito"/>
<input class="headInput" type="text" name="userLastName" value="Lancreo"/>
<input class="headInput" type="text" name="phone[]" value="666666"/>
<input class="headInput" type="text" name="phone[]" value="111111"/>
<input class="headInput" type="text" name="phone[]" value="222222"/>
</form>
And when I debug it, I always get 0...
[false, false, Array[0], false, null]
My controller:
$this->load->helper('form');
$this->load->library('form_validation');
//1 way
$ret=$this->input->post();
//2 way
$return=$this->input->post(NULL, TRUE);
//3 way
$all=$_POST;
json_encode($all);
//4 way
$contact=$this->input->post("userName");
//return everything...
$var[0]=$return;
$var[1]=$contact;
$var[2]=$all;
$var[3]=$ret;
$var[4]=$data;
echo json_encode($var);
How can I fix it??

SOLVED!
The problem was not to replace with:
serialize().replace(/%5B%5D/g, '[]');
But I think it's usefull...
My problem was that I'm using a library for internationalization (https://github.com/bcit-ci/CodeIgniter/wiki/CodeIgniter-2.1-internationalization-i18n) and I must add language to my url, even if I change my routes.php
url: '<?php echo base_url()?>en/intranet/update/updateProfile'
Thanks a lot!

The issue, as it seems, Is the serialize itself.
As can be seen here :
How to send serialize form data using JQuery if the input element is an array
Serialize has an issue with an array in the input fields, It replaces the square barckets :
The fiddle :
http://jsfiddle.net/3vr0dtgn/
from my fiddle:
data = $('form').serialize();
$('div').append(data);
Using the stackoverflow I supplied above gives the solution(regex replacing certain elements)

Related

i am getting error in php while uploading image to databse using jquery, the data in variables arent passing maybe

My code is a form where it picks a file from the user, then send the data using jQuery to a PHP file where it gets the image content and displays it and in a success function: it alerts the data received from the PHP file. For example, the image received from the HTML page.
Actually, the code inserts the image into the database, but I plucked the code out and inserted a direct view of image in PHP file without inserting in the database because I wanted to make it short(database insertion code has no error: it inserts other variables provided with image and image stays blank)
Also am using my script on XAMPP localhost. So do not worry about that i am running it like file://... . All is that i can't figure out why the data aren't being passed to php file.
HTML:
<input style="border:none" type="file" id="photo" /> <br>
JavaScript:
$("#submit-form").click(function() {
var formadata = {
"photo": $("#photo").val(),
};
$.ajax({
url: './enter-registration-form.php',
data: formadata,
cache: false,
contentType: false,
processData: false,
method: 'POST',
success: function(val) {
if (val == "done") {
alert("Data Accepted");
} else {
alert(val);
}
}
});
});
PHP:
$i = $_FILES['photo']['name'];
//get the content of the image and then add slashes to it
$imagetmp=addslashes (file_get_contents($_FILES['photo']['tmp_name']));
echo '<img src="data:image/jpeg;base64,'.base64_encode($imagetmp).'" style="width:100px;height:autoborder:none">';
Now I am getting this error message:
Notice: Undefined index: photo in
/opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 5
Notice: Undefined index: photo in
/opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 8
Warning: file_get_contents(): Filename cannot be empty in
/opt/lampp/htdocs/SSNC/exam/enter-registration-form.php on line 8
I can't figure out why this error is thrown.
Approach
You need to use new FormData() object.
The FormData interface provides a way to easily construct a set of
key/value pairs representing form fields and their values, which can
then be easily sent using the XMLHttpRequest.send() method. It uses
the same format a form would use if the encoding type were set to
"multipart/form-data".
So you don't actually have to declare a form tag and add inputs inside, yes it makes it easier if you have let us make a call assuming that you do not have a form tag.
Problem
The problem in your script is that your formdata is a json rather than a FormData() interface object, which uses formdataObject.append() which appends a new value onto an existing key inside a FormData object, or adds the key if it does not already exist.
See code below which posts email, file label and a file to a PHP page without using form tag for the inputs.
Without <form> tag
Assuming that your html looks like below without a form
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="button" name="submit" value="Stash the file!" />
Your javascript code will look like below
$(document).ready(function () {
$("input[name='submit']").on('click', function (event) {
event.preventDefault();
//START Append form data
var data = new FormData();
data.append(
'userid', $("input[name='userid']").val());
data.append(
'label', $("input[name='filelabel']").val()
);
data.append('file', $("input[name='file']")[0].files[0], 'somename.jpg');
//END append form data
$.ajax({
type: "POST",
url: "file.php",
data: data,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
});
});
And your file.php will look like below
<?php
print_r($_POST);
print_r($_FILES);
This should show you the file inputs and file both of them in the console when you hit the stash file button.
With <form> tag
If you have the inputs wrapped inside the form tag then your code will be changed on the following sections
Change binding of click event to form submit event.
Change button type to submit in the HTML.
Get the form object.
Use form object to initialize the FormData().
See below How your HTML will look like
<form enctype="multipart/form-data" method="post" name="fileinfo">
<label>Your email address:</label>
<input type="email" autocomplete="on" autofocus name="userid" placeholder="email" required size="32" maxlength="64" />
<br />
<label>Custom file label:</label>
<input type="text" name="filelabel" size="12" maxlength="32" />
<br />
<label>File to stash:</label>
<input type="file" name="file" required />
<input type="submit" value="Stash the file!" />
</form>
And your javascript will look like below
$(document).ready(function () {
$("form").on('submit', function (event) {
event.preventDefault();
var form = this;
var data = new FormData(form);
$.ajax({
type: "POST",
url: "file.php",
data: data,
processData: false,
contentType: false,
success: function (data) {
console.log("SUCCESS : ", data);
},
error: function (e) {
console.log("ERROR : ", e);
}
});
});
});
This should work!
HTML:
<form id="my-upload-form" method="post" enctype="multipart/form-data">
<input type="file" name="required-image" />
<button> Upload </button>
</form>
JS:
$("button").click(function(e) {
/* prevent default form action */
e.preventDefault();
/* get form element */
var formElement = document.getElementById("my-upload-form");
/* collect all form data from Form element */
var formData = new FormData(formElement);
$.ajax({
url: '/path-to-form-handler.php',
data: formData,
cache: false,
contentType: false,
processData: false,
method: 'POST',
success: function(response) {
console.log(response);
}
});
});
PHP:
<?php
/* for this example, $_FILES["required-image"] would be an array having image details */
echo $_FILES["required-image"]["name"];
echo $_FILES["required-image"]["type"];
echo $_FILES["required-image"]["tmp_name"];
echo $_FILES["required-image"]["size"];
?>
First of all insert your input file tag in a form and use enctype="multipart/formdata"
to send an image otherwise you will not able to send image

Jquery-confirm and passing POST variables to an externally loaded form

Is there a way to send POST variables to an external PHP form?
I'd like to pass, in this example, XXX and YYY using POST (not GET).
I'm using this plugin: https://github.com/craftpip/jquery-confirm
<a id="btn" data-value1="XXX" data-value2="YYY">CLICK ME</a>
<script>
$('#btn').on('click', function (e) {
e.preventDefault();
$.confirm({
title: 'Title',
content: 'url:form.php',
buttons: {
......
}
});
});
form.php:
<?php
$value1 = $_POST['value1'];
$value2 = $_POST['value2'];
?>
<div class="form-group">
<label class="control-label">Default values from parent page:</label>
<input type="text" id="value1" class="form-control" value="<?php echo $value1; ?>">
<input type="text" id="value2" class="form-control" value="<?php echo $value2; ?>">
</div>
UPDATE: tried this also, without success. Form doesn't load in modal:
content: function() {
var self = this;
return $.ajax({
url: 'form.php',
dataType: 'json',
async: false,
method: 'post',
data: { 'value1': 'XXX', 'value2': 'YYY' }
}).done(function (response) {
self.setContent(response);
});
}
You simply need to specify
dataType: 'html'
instead of
dataType: 'json'
This is because form.php returns a HTML string, not a JSON object. You likely have an error in your console complaining that jQuery cannot parse the response as JSON, because it isn't JSON. If you tell jQuery to expect HTML instead, it will pass the reponse through as a string instead which you can directly display on screen, without trying to turn it into an object.

I can't get to the success block of my jquery function

I am a little stuck on my jquery function below.
Here is the situation:
1) My php returns valid JSON - I can test this when I change the $_POST into $_GET and manually pass through data with the url.
2) The function below works correctly right up to the $.ajax part.
3) The function always returns ready state 0
Let me know if you need anymore data. Days of going over Stack Overflow and other forums has helped with insight, but I can not seem to fix in my instance.
//HTML
<form class="login-form" method="POST">
<input type="text" id="name" name="name" value="" placeholder="Username" required="yes">
<input type="password" id="pwd" name="pwd" value="" placeholder="Password" required="yes">
<input type="submit" id="login" name="login" value="Login" class="loginbutton" >
</form>
//JavaScript
$('#login').click(function(event)
{
//event.preventDefault();
var u = $('#name').val();
var p = $('#pwd').val();
console.log(u, p);
console.log("I am seeing this function?");
$.ajax({
contentType: "application/json; charset=utf-8",
cache: false,
type: "POST",
url: "functions/login.php",
data: {name:u, pwd:p},
datatype: "json",
error: function(msg)
{
console.log("RS - "+msg.readyState);
console.log(msg);
},
success: function(msg)
{
console.log("RS - "+msg.readyState);
console.log(msg);
$.each( msg, function( i, val ) {
console.log(val[0].session); //session is a variable in the json string
});
console.log("Success block");
}
});
});
datatype -> dataType problem, and if it does not help try out the 'text' type.
Maybe the php server send out other lines that messes up things.
event.preventDefault() or return false is missing at the end of your event handler for the click. Citation from w3schools
The event.preventDefault() method stops the default action of an element from happening.
so in our case it prevents form from sending.
These two technics prevent an event from bubbling upper. Without them, the form is sent to itself (address of your script) which results into page refresh and stop executing the script.
You can see the result (readyState) from $.ajax() function because it is faster than page reload.

Send form data as GET parameters with jsonp and ajax

Hi Guys I'm new to jsonp. All I'm trying to do is simply send simple form data. I understand you cannot POST using jsonp as it is a standard script GET request. Below I've tried both serialize() or serializeArray() the form data but nothing is included in the GET request, please let me know where I'm going wrong?
HTML:
<form class="qd-bd-frm" name="qd-bd-frm" id="qd-bd-frm">
<input type="hidden" value="9614d609b2b7987d734" name="uid" />
<p>
<textarea class="qd-input" placeholder="Your Message" name="msg"></textarea>
</p>
<p>
<input type="button" class="qd-btn" value="Send" />
</p>
</form>
Jquery:
$.ajax({
url: "http://www.cross-domain.com/send",
dataType: "jsonp",
data: $("#qd-bd-frm").serializeArray(),
jsonpCallback: "sent",
success: function (result)
{
alert(JSON.stringify(result));
},
complete: function (xhr, status)
{
alert(status);
},
error: function ()
{
}
});
PHP:
public function send()
{
header( "Content-Type: application/json" );
echo "sent(".json_encode( $_GET ).");";
die();
// example response: sent({"callback":"sent","_":"1425338880075"});
}
If you see above, I'm just echoing the response back and in my success function above, none of my form inputs were included. I can also see this if I check the scripts tab in firebug that only 2 parameters were sent to the server. Any ideas what I'm actually missing here?

jQuery Ajax post file

I try to post an uploaded file via ajax to php.
HTML:
<form id="uploadForm" name="uploadForm" action="#" enctype="multipart/form-data">
<input id="name" name="name" class="form-control" type="text" />
<input id="csv" name="csv" type="file" />
<input id="CSVUpload" type="submit" class="btn btn-default" name="Submit" value="Hochladen" />
JS
$("#uploadForm").submit(function () {
var formData = new FormData();
formData.append( 'csv', $( '#csv' )[0].files[0] );
formData.append( 'name', $( '#name'));
jQuery.ajax({
url: "../lib/import.php",
data: formData,
type: "POST",
success: alert('erfolgreich'),
error: alert('Fehler'),
cache: false,
contentType: false,
mimeType: 'multipart/form-data',
processData: false
});
});
and then i try to get the form data in PHP:
$_FILES['csv']
$_POST['name']
But the Ajax call completes with success and error... I'm confused...
The PHP file will not executed correctly...
Thanks for your help!
You aren't assigning functions to success or error.
You are calling the alert function immediately and then assigning its return value.
You need to create new functions to assign to success and error.
success: function () { alert('erfolgreich') },
error: function () { alert('Fehler') },
You are also calling the function as a submit handler, but aren't preventing the normal form submission. Consequently, the browser will load a new page before processing the response to the Ajax request.
$("#uploadForm").submit(function (event) {
event.preventDefault();
Try restructuring your AJAX call with your success and failure code like this:
$.post('../lib/import.php', formData).done(function() {
console.log('done');
}).fail(function() {
console.log('error');
});
See http://api.jquery.com/jquery.post/ for more examples.

Categories