post binary code not working from Jquery ajax - javascript

I made this code to make image upload function but the variable is not getting posted by ajax please help me !!
Jquery()
<script type="text/JavaScript">
$(document).ready(function() {
$("#btn").click(function() {
$.get("i.png", function(response) {
var img = response;
});
$.ajax({
type: "POST",
url: 'lol.php',
data: {r: img},
success: function(data){
$("#ol").html(data)
}
});
return false;
});
});
</script>
PHP Code
<?php
$conn = mysqli_connect("localhost","root","","image");
$r = $_POST['r'];
echo $r;
?>

If you only want to make an image upload (and not exactly match "binary upload")
I suggest you to use the proper functional and native input type file.
In a html form, put an :
<input type="file" id="upload">
<img src="blank.png" title="upload-preview">
and in you javascript:
this will load the preview thumbnail selected
fileInput.addEventListener("change", function(event)
{
var file = $("#upload")[0].files[0];
$(".upload-preview").attr('src', window.URL.createObjectURL(file));
});
and when you click the button, that will send the image
with a "multipart/form-data" Content-Type
$("#btn").on("click", function()
{
var inputs = new FormData();
inputs.append("upload", $("#upload")[0].files[0]);
$.ajax
({
url:"your.php",
type:"POST",
data: inputs,
cache: false, // don't cache the image
processData: false, // Don't process the files
contentType: false,
success: function(response)
{
// next instructions
}
});
});

Related

How can I combine two ajax functions in one function?

I have ajax code which can post name and I have another ajax which can post image I need to combine those two functions in order to have one function which can post both name and image
Below codes used to post image
<script>
$(document).ready(function(){
$("#but_upload").click(function(){
var fd = new FormData();
var files = $('#file')[0].files;
// Check file selected or not
if(files.length > 0 ){
fd.append('file',files[0]);
$.ajax({
url: 'upload.php',
type: 'post',
data: fd,
contentType: false,
processData: false,
success: function(response){
if(response != 0){
$("#img").attr("src",response);
$(".preview img").show(); // Display image element
}else{
alert('file not uploaded');
}
},
});
}else{
alert("Please select a file.");
}
});
});
</script>
And below codes used to post name
<script type="text/javascript">
function clickButton(){
var name=document.getElementById('name').value;
$.ajax({
type:"post",
url:"upload.php",
data:
{
'name' :name
},
cache:false,
success: function (html)
{
alert('Data Send');
$('#msg').html(html);
}
});
return false;
}
</script>
How can I combine above codes in order to use only one url "upload.php", this means upload.php will insert name in database and save image in folder while click save button, that's why I need to combine the codes
Please anyone can help me
You literally combine them.
You can use your first function and do the following:
var fd = new FormData();
var files = $('#file')[0].files;
fd.append('name', $("#name").val();
that is it. And on the other side (backend) you just ask for this name:
$name = $_POST['name'];

$.ajax not uploading files using data: object array method

Ive searched on Stack overflow all over the place and could not find a solution or a post that is close to my problem.
So if this has been posted before I do apologies.
I am posting some information using a different method rather than posting a form which I will explain after I show you the code :)
Jquery:
$("#submit-add-cpos").on('click',function(){
var checkHowManyInstallments = $('#installment-ammount').val();
var checkCpoNumber = $('#addcponumber').val();
var checkCpoTotalPrice = $('#addcpoprice').val();
var checkCpoContactName = $('#addcpocontactname').val();
var form_data = new FormData();
form_data.append("type", 'addcpo');
form_data.append("quoteid", '<?php echo $_GET['id']; ?>');
form_data.append("installmentamount", checkHowManyInstallments);
form_data.append("cponumber", checkCpoNumber);
form_data.append("costcode", '<?php echo $quotecostcode; ?>');
form_data.append("cpocontactname", checkCpoContactName);
form_data.append("cpotitle", '<?php echo $quotetitle; ?>');
var checkDynamicValues = '';
var checkDynamicValue1 = '';
var checkDynamicValue2 = '';
var checkmakename1 = '';
var checkmakename2 = '';
if(checkHowManyInstallments != 'undefined' && checkHowManyInstallments != '' && checkHowManyInstallments != 0){
for(var makingi = 1; makingi <= checkHowManyInstallments; makingi++){
checkDynamicValue1 = $('#cpo-adddate-' + makingi).val();
checkDynamicValue2 = $('#cpo-addprice-' + makingi).val();
form_data.append('cposadddate' + makingi, checkDynamicValue1);
form_data.append('cposaddvalue' + makingi, checkDynamicValue2);
}
}
$.ajax({
url: '/Applications/Controllers/Quotes/ajax-add-sin.php',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
$('body').html(data);
}
});
});
So from this script I get all the fields from within the form, including some dynamic ones.
The reason why I am doing it like this instead of the easier way of:
$("#formname").on('submit',function(){
$.ajax({
url: "xxxxxxxxxx/xxxxx/xxxx/xxxx.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
});
Is because for some reason it will not find the posted information no matter what I tried, so the only way I could do it is to find each id and get the value from it.
Now the issue is, uploading a file, you can not simply upload a file this way because nothing is posted.
How would I go about uploading a file if not posting a form?
Thanks
The reason why it was not posting the file is simply because I did not give it a file to post...
18 hours straight of work has not agreed with me here.
Basically I need to add the following code
var checkCpoFiles = $("#addcpofile").prop("files")[0];
form_data.append("cpofile", checkCpoFiles);
Now all works
:)
Please go through this page Ajax Upload image
Here's sample code, it might help
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<form enctype="multipart/form-data" action="uploadfile.php" method="POST" id="imageUploadForm">
<input type="file" name="upload" />
<input type="submit"/>
</form>
</body>
<script>
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
});
</script>
uploadfile.php
<?php
if(move_uploaded_file($_FILES['upload']['tmp_name'],$_FILES['upload']['name'])) {
echo "File uploaded successfully";
} else {
echo "Unable to upload the file";
}
?>
Hope it helps! All the best!

Including JS file in html page errors

I have this JavaScript code inside an html and PHP page. But I've been told that it will works only if I had an internet connection, so the solution was to make a .JS file and include this file inside the page like that:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="/clinic form/appoint/dropscript.js">
</script>
Now I got an error while testing the page offline.
The JS file is taken from this link:
multiple java script in one page error
And the final code is:
$(document).ready(function(){
$("#Date").change(function(){
var seldate =$(this).val();
display_data(seldate);
});
// This is the function...
function display_data(seldate) {
$("#scheduleDate").html(seldate);
var dataString = 'seldate='+ seldate;
$.ajax({
type: "POST",
url: "getdata.php",
data: dataString,
cache: false,
success: function(data) {
$("#Schedule").html(data);
}
});
}
// Now here is the real code for retaining your Date...
/*<?php
if (!empty($_GET['date'])) {
?>
display_data('<?php echo $_GET["date"]; ?>')
<?php
}
?>*/
document.getElementById('Date').value = '<?php echo #$_GET["date"]; ?>';
});
$(document).ready(function(){
$("#Name").change(function(){
var selname =$(this).val();
display_name(selname);
});
// This is the function...
function display_name(selname) {
$("#scheduleName").html(selname);
var dataString = 'selname='+ selname;
$.ajax({
type: "POST",
url: "getdatabyname.php",
data: dataString,
cache: false,
success: function(data) {
$("#Schedule").html(data);
}
});
}
});// JavaScript Document
P.S. I am totally new to JS and I am experimenting.
Go to https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js, hit CTRL+S, move saved file to your project's directory and then include it as you did with dropscript.js.
Also do the same with the font if you need it. Include it into your CSS file using #font-face. More information: https://developer.mozilla.org/en-US/docs/Web/CSS/#font-face

Ajax call (before/success) doesn't work inside php file

I have a form that when clicked the submit button makes a call via ajax. This ajax is inside a php file because I need to fill in some variables with data from the database. But I can not use the calls before / success. They just do not work, I've done tests trying to return some data, using alert, console.log and nothing happens. Interestingly, if the ajax is isolated within a file js they work. Some can help me please?
File:
<?php
$var = 'abc';
?>
<script type="text/javascript">
$(document).ready(function() {
$('#buy-button').click(function (e){
var abc = '<?php echo $var; ?>';
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
before: function(data){
console.log('ok');
},
success: function(data){
},
});
});
});
</script>
HTML:
<form id="buy-form">
<div class="regular large gray">
<div class="content buy-form">
/* some code here */
<div class="item div-button">
<button id="buy-button" class="button anim" type="submit">Comprar</button>
</div>
</div>
</div>
</form>
----
EDIT
----
Problem solved! The error was in the before ajax. The correct term is beforeSend and not before. Thank you all for help.
You said it was a submit button and you do not cancel the default action so it will submit the form back. You need to stop that from happening.
$('#buy-button').click(function (e){
e.preventDefault();
/* rest of code */
Now to figure out why it is not calling success
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
before: function(data){
console.log('ok');
},
success: function(data){
},
error : function() { console.log(arguments); } /* debug why */
});
});
My guess is what you are returning from the server is not valid JSON and it is throwing a parse error.
Try this
<script type="text/javascript">
$(document).ready(function() {
$('#buy-button').click(function (e){
e.preventDefault();
var abc = '<?php echo $var; ?>';
$.ajax({
type: 'POST',
data: $('#buy-form').serialize(),
url: './ajax/buy_form.php',
dataType: 'json',
beforeSend: function(data){
console.log('ok');
},
success:function(data){
}
});
});
});
And make sure that your php file return response

Pass PHP array to external jQuery $.ajax

Basically what I want to do is get an array that has t.php, and alert it with JavaScript with the response of t.php.
The problem is that the variable doesn't exist in this file...
So, how you can pass this variable to JS?
I tried with 'return':
return $sqlData = $q->query_array_assoc();
But doesn't work.
Here is my $.ajax code:
<script type="text/javascript">
$(document).ready(function(){
$('#brand').change(function(e){
console.log(e);
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value }
})
.done(function(msg){
$('#debug').html(msg);
var pArray = <?php echo json_encode($sqlData);?>
for (var i = 0; i < pArray.length; i++) {
alert(pArray[i]);
};
});
});
</script>
Note: I sent
data: { type: 1, brand: this.value }
To validate a switch statement in the .php file, but there isn't problem with that. I get the data from the database and fetch in the variable $sqlData;
So the array has data, the problem is get it with $.ajax
in your php file, you need to echo instead of return
echo json_encode($q->query_array_assoc());
in javascript code:
$.ajax({
method: "GET",
url: "t.php",
data: { type: 1, brand: this.value },
success: function(data) {
$('#debug').html(data);
// if you want to use it as array
var json_data = JSON.parse(data);
}
});
Make 2 files please, a "t.php" file and a "t.html" file and add my code there. Run the code and see response. You just have to work with the response to get the values se perated by comma "," !!!
/******************** UPDATED ***********************/
//t.php
<?php
$a = array();
$a[]=1;
$a[]=2;
$a[]=3;
echo "$a[0],$a[1],$a[2]";
?>
//t.html
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script type="text/javascript">
function fun(){
$.ajax({
method: "GET",
url: "t.php",
data: { },
dataType: "html", //expect html to be returned
success: function(response){
//$("#debug").html(response); //Outputs the html of php file into #dialog div
alert(response);
document.getElementById("debug").innerHTML = (response); //Outputs the html of php file into #dialog div
}
})
}
</script>
<button onclick="fun()">Call Ajax Fun</button>
<div id="debug"></div>
Did this help?

Categories

Resources