First of all, sorry if this is a duplicate. I've looked and seen some solutions but none worked. I've been trying to do this simple thing for like 3 hours with no result.
I'd have this html:
<form method="post" action="?c=Logo&action=save" id="form">
<!-- some inputs -->
<img src="" data-filename="new-logo.png">
<input type="submit" value="submit">
</form>
Here I'd like to modify the form so my php file will recognise $_POST['new-logo'].
// $_POST['new-logo'] = $('img').data('filename')
$logo = new Logo($_POST['new-logo']);
$logo->save();
I guess I should use the jQuery function $.post() but somehow I can't manage. Thank you all for your help :-)
SOLUTION
Finally since I found a very simple solution. Since I want my data to be processed in my php file, I simply added an <input type="hidden"> and modified its value with JS :-)
You could also make the data array from scratch like this:
$('#form').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: {key1:"value", key2:"value2"},
dataType: "json",
success: function(data) {
//do success stuff here
},
error: function() {
//do error stuff here.
}
});
});
You can add it as a hidden input.
$("#form").submit(function() {
$(this).append($("<input>", {
type: "hidden",
name: "new-logo",
value: $(this).find("img").data("filename")
});
});
you can add this to you're post request like this :
$('#form').on('submit', function(e){
e.preventDefault();
var $form = $(this);
var datastring = $form.serializeArray();
datastring.push({name:'new-logo', value:$form.find('img').data('filename')});
$.ajax({
type: "POST",
url: $form.attr('action'),
data: datastring,
dataType: "json",
success: function(data) {
//var obj = jQuery.parseJSON(data); if the dataType is not specified as json uncomment this
// do what ever you want with the server response
},
error: function() {
alert('error handing here');
}
});
});
$logo = new Logo($_POST['new-logo']);
Is "new Logo" a function or something? Pretty sure that can't have a space.
Related
I am relatively new to jQuery and Ajax functions, but have been working with Ajax forms over the past few days. I have come to a problem with file uploads however when trying to upload images. Whilst looking for resources, I couldn't find anything useful because they seem to be over-complicated with pointless extras or have no explanation whatsoever, which doesn't help me to learn any further.
I have wrote this code to handle the image upload in Ajax:
$(function() {
$('.input_photo').on("change",function() {
var formData = new FormData($('form.upload-form'));
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
success: function (msg) {
alert(msg)
}
});
});
});
This sends a request to the upload.php file, however no data is sent, basically my form is literally this:
<form class="upload-form">
<input type="file" name="input_photo" class="input_photo" />
</form>
No data seems to be passed in the headers whatsoever and I assume I would access it through PHP with $_POST['data'] array or $_FILES? Someone with better knowledge please help to explain this, it'd be great to understand this further.
Thanks.
This will work for one or multiple files.
$('input:file').on('change', function () {
var data = new FormData();
//Append files infos
jQuery.each($(this)[0].files, function(i, file) {
data.append('file-'+i, file);
});
$.ajax({
url: "my_path",
type: "POST",
data: data,
cache: false,
processData: false,
contentType: false,
context: this,
success: function (msg) {
alert(msg);
}
});
});
Then
$_FILES['file-0']
$_FILES['file-1']
[...]
But be careful that using FormData doesn't work on IE before IE10
You need to set processData and contentType in your ajax call ( also added id to your input element in order to fetch the file contents).
HTML
<form class="upload-form">
<input type="file" id="photo" name="input_photo" class="input_photo" />
</form>
JS
$(function() {
$('.input_photo').on("change",function() {
var file = document.getElementById("photo").files[0]; //fetch file
var formData = new FormData();
formData.append('file', file); //append file to formData object
$.ajax({
url: "upload.php",
type: "POST",
data: formData,
processData: false, //prevent jQuery from converting your FormData into a string
contentType: false, //jQuery does not add a Content-Type header for you
success: function (msg) {
alert(msg)
}
});
});
});
Try with this:
var formData = $('form.upload-form').serialize();
Any idea why this doesn't work? I have tried to see if the button clicked actually works with alerts, had alerts as well as before and after the ajax code and they both worked.
var selectedCheckboxes = "12421";
jQuery(document).ready(function($){
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: { selectedCheckboxes: "selectedCheckboxes" },
success: function(response){
//do action
},
error: function(){
// do action
}
});
});
});
the link:
Edit
test.php
<?php
echo $_POST["selectedCheckboxes"];
?>
Try this instead:
Edit
If you want the output of the php in your page you have to do something like this in your javascsript
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: { selectedCheckboxes: selectedCheckboxes },
success: function(response){
$("body").html(response);
},
error: function(){
// do action
}
});
});
You may need to change the "body" tag.. or not
depends on what the teste.php returns
Well, if you don't want the output to be placed inside your current page html, maybe a different aproach would be better.
Maybe there are better answers but you could try something like:
<form method="post" action="test.php" onsubmit="javascript:$('#selectedCheckboxes').val(selectedCheckboxes);">
<input type="hidden" value="" name="selectedCheckboxes" id="selectedCheckboxes">
<input type="submit" value="Edit">
</form>
You would have to style the submit input
Does the idea help? No ajax though.
The reason you're not seeing the AJAX reqeust go through is because when the you click on the anchor tag, the browser is performing the default action of navigating to 'test.php', which cancels the AJAX call. Since you are simply GET'ing that page, and not POST'ing to it, there is nothing in $_POST. In order to prevent this default action, either use a span instead of an a tag (recommended), or prevent the default action, doing something like this:
Edit
If I get you right, you want to pass selectedCheckboxes as JSON to the Server. In this case you need to actually pass your selectedCheckboxes variable to the Server.
Like this:
$.ajax({
url: "test.php",
type: "POST",
data: selectedCheckboxes,
success: function(response){
//do action
},
error: function(){
// do action
}
});
The problem with your code is that you passed a new JSONObject containing a String that contains "selectedCheckboxes". You did not pass the actual variable.
Put a return false; after ajax call
You try to pass a variable selectedCheckboxes but unfortunately with double ("") quotes you passing a string as selectedCheckboxes
Use below code
var selectedCheckboxes = "12421";
var dataObject = {};
data[selectedCheckboxes] = 1;
jQuery(document).ready(function($){
$(".editArticle").on("click",function(){
$.ajax({
url: "test.php",
type: "POST",
data: dataObject ,
success: function(response){
//do action
},
error: function(){
// do action
}
});
});
});
Hope this helps...
I am creating a chat system. I am sending a form data through ajax method in jquery. My first problem is ajax method is not sending data to proccess.php and page goes to redirect to its self.
<div id="chatOutput"></div>
<form id="myform">
<textarea id="chatInput" name="chatInput"></textarea>
<input type="submit" id="send" name="send" value="send" />
</form>
and script is :
$('#send').click(function () {
$('#myform').submit();
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data: $('#myform').serialize(),
success: function () {
alert("Submitted!"); // for testing
}
});
return false;
});
but script is not working and page goes to refresh and i see the variables and its values in the address bar like get method.
if this problem goes to solve, process.php will create a chat.txt and append data from #chatInput into it. and then will append chat.txt 's data to #chatOutput.
After appending data, div#chatOutput 's size goes to change. I want to fixed/specified width and height of this div. After the fixing size, how to scroll to bottom to see the last chatting?
The problem is here:
$('#myform').submit();
The simulates the "Submit" button click event
You can just do :
$('#myform').submit(function() {
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data: $('#myform').serialize(),
success: function() {
alert("Submitted!"); // for testing
}
});
return false;
});
You used $('#myform').submit(); which just submits the form in the normal way and thus ignoring the ajax etc after that.
Also, put this code either after the form itself or within $(function(){ ... });
EDIT
You had a syntax error. Make sure u have e.preventDefault(); as the first thing in your event click function. Then the default action will be prevented even when an error occurs later on.
$('#send').click( function(e) {
e.preventDefault(); //disable default action
$('#myform').submit();
$.ajax({
url: 'process.php',
type: 'post',
dataType: 'json',
data: $('#myform').serialize(),
success: function() {
alert("Submitted!"); // for testing
}
});
});
return false; //return something
});
Remove the line:
$('#myform').submit();
It is submitting the form before your ajax call is made.
First, I'm using the codeigniter framework and I'm a beginner in JS and AJAX, so please bear with me.
I read this question, so I tried to follow the answers.
This is the script (UPDATED):
$(function() {
$( "#datepicker").datepicker().click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
return false;
});
});
And this is my datepicker HTML code:
<input type="text" id="datepicker" name="datepicker"
value="<?php echo isset($umat['tanggal_lahir'])?$umat['tanggal_lahir']:""?>"/>
My questions are (UPDATED):
Is the URL I provided in AJAX above correct?
How should I pass the data from AJAX to PHP (url: "<?php echo base_url(); ?>backend/umat/add")?
Thanks for your help :D
What you have missed here:
your click event is outside of the doc ready handler, that should be inside doc ready so that when page gets ready the element should be available to click.
You have missed a closing }); tag of the click event.(does not matter though)
so try this:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").click(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: {frmData : $('#form_daftar').serialize()}, // <----send this way
success: function(data) {
console.log(data.date);
// here data is the returned data from the specified url and make sure
// that url is generating a proper json structrue.
// suppose there is a key named date which holds the submitted date so
// data.date will get you the date.
}
});
}); //<----you missed this closing of click function.
}); //<----------put everything before this closing of doc ready handler.
Although you can chain it too like this:
$(function(){
$( "#datepicker").datepicker().click(function() {
//......ajax function in click here
});
});
See a demo here
Another approach would be to use the datepicker inbuilt methods to trigger ajax request like
$('#datepicker').datepick({
dateFormat:"yyyy-mm-dd",
onSelect:function(){
$.ajax({
type: 'POST',
url: "<?php echo site_url('backend/umat/add'); ?>",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
}
});
Check the manual or inbuild functions and callbacks with your datepicker js.
try it:
$(function() {
$( "#datepicker").datepicker();
$("#datepicker").change(function() {
$.ajax({
type: 'POST',
url: "<?php echo base_url(); ?>backend/umat/add",
dataType: "json",
data: $('#form_daftar').serialize(),
success: function(data) {
console.log("Done");
}
});
});
php get data form ajax:
<?php
$date = $_POST["datepicker"];
?>
I am new to jquery and php, I have two input fields, zip and city, the city shall output a value based from the zip that the user input. The jquery script shall call a URL: http://domain.com/city?zip.php="zip; so that zip.php will return an echo value that will output to the city input field.
I tried using ajax getXMLHTTP. some times it works but sometimes not
Please Refer to the following code snippet below:
<input type="text" id="zip_code" name="zip_code" />
<input type="text" id="city" name="city" />
<script type="text/javascript">
// Some Jquery code here for ajax get request to http://domain.com/city?zip.php
</script>
if you are using jquery the use $.ajax option instead of getXMLHTTP
function passzipvalue(zip)
$.ajax({
type: "GET",
url : 'http://domain.com/city.php='
data:"zip="+zip,
success: function(msg){
$("#formsData").html(msg);
}
});
}
something like this or
$.get('http://domain.com/city.php?zip='+zip,function (msg){
$('#formsData').html(msg);
});
if you want to populate it in some input fields use .val instead of .html
Use jQuery.get, documented here. In the success handler, use the data argument to populate the city input.
Sample:
$.get('http://domain.com/city.php?zip='+$('#IdOfZipInput').val(), function (data){
$('#IdOfCityInput').val(data);
});
Use jQuery AJAX. For example:
var zip = $('#zip').val();
$.get('http://domain.com/city.php?zip='+zip,function (data){
$('#city').val(data);
});
$.ajax({
url: 'http://domain.com/city.php?zip='+zip,
type: get,
success: function(data){
$("div").html(data);
}
});
use this data will be displayed
If its a constantly updating element then use jquery.post as ie caches the "get" results.
jQuery.post('call.php',{ action: "get"}, function (data) {
jQuery('#content').append(data);
});
FInd the tutorial here http://vavumi.com/?p=257
try to use the jquery ajax
$.ajax({
type: "POST",
url: 'sample/test.php',//your url
data: data,//data to be post
cache: false,
success: function(html) {
alert(html);//response from the server
}
});
$.ajax({
url: 'url',
beforeSend: function (xhr) {
//show loading
}
}).done(function (data, xhr) {
//hide loading
//success
}).fail(function (xhr) {
//hide loading
//error
});