use parts of ajax results after form submit - php

I have a simple upload form that sends the request via ajax post. The result (data) is shown in a bootstrap modal - works like intended.
Parts of the upload.php are reading exif data from the uploaded image and I'd like to use these information on my start form (updating placeholders with exif info).
$(document).on('submit', '#uploadForm', function(e) {
e.preventDefault();
$.ajax({
url: './includes/upload.php',
type: 'POST',
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
$('#modal .modal-body').html(data);
$('#modal').modal('show');
}
});
});
html result:
<img src="<?php echo $imgpPath; ?>" />
<div class='fp_upload'>
<div class="alert alert-success">
<?php
echo '<p class="body">'.$img_body.'</p>';
echo '<p class="lens">'.$img_lens.'</p>';
echo '<p class="iso">'.$img_iso.'</p>';
echo '<p class="aperture">'.$img_aperture.'</p>';
echo '<p class="exposure">'.$img_exposure.'</p>';
?>
</div>
</div>
What would be a good way to get the desired infos somewhere in data?
Greeings Fabio

I know, with JSON it would get easier, but I found a way to find specific values in my data and place them in inputs.
My submit code is untouched, inside the success I added.
var img_name = $(data).find('#img_name').attr('data-placeholder');
$('#input_name').val(img_name);
Greetings Fabio

Related

Reload data continuously with Ajax

I have a page with some bootstrap cards. Information showing inside the card is retrieved from MySQL database.
What I need
I need these cards to be updated every 3 seconds without reloading the page. I know that Ajax is the way to do this (Update content without refreshing page). I am not familiar with Ajax. However, I tried as below
<script>
setInterval(
(function x() {
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
return x;
})(), 3000);
</script>
Also I gave the following div with id inputFieldDisplay as below
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
My Issue
When I redirect to the mentioned page vTagInfoCall.php with all my php codes and contents, it is not loading anything to the div with id inputFieldDisplay. Did anyone know what am I doing wrong here?
Edit 1
Following is my vTagInfoCall.php file contents
<?php ob_start();?>
<?php include "db.php"; ?>
<?php
$tagQuery = "SELECT * FROM vtagdetails WHERE status = 0";
$tagQueryExecute = mysqli_query($conn, $tagQuery);
$openItems = mysqli_num_rows($tagQueryExecute);
while($tagQueryRows = mysqli_fetch_array($tagQueryExecute)){
$srNumber = $tagQueryRows['srNumber'];
$Name = $tagQueryRows['Name'];
$Code = $tagQueryRows['Code'];
$customerName = $tagQueryRows['customers'];
$Type = $tagQueryRows['Type'];
session_start();
echo '<form method="post"> <div class="card cardBodyStyle">
<div class="card-body" >
<div class="row">
<input type="text" name= "srNum" value = "'.$srNumber.'" hidden>
<input type="text" name= "tpCode" value = "'.$Code.'" hidden>
<div class="col-sm"><i class="fab fa-500px"></i> '.$Name.'</div>
<div class="col-sm"><i class="fas fa-atom"></i> '.$Type.'</div>
<div class="col-sm"><i class="fas fa-globe fa-spin"></i> '.$customerName.'</div>
</div>
</div></div></form><br>';
}
?>
Edit 2
It is showing the following error in console. Can someone help why is the error?
I found two issues in code:
First in your script, please use below code:
<script>
setInterval(x, 3000);
function x() {
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
})
}
</script>
Second one is remove # from your id of div because # is just use to indicate id of element in jquery and .(dot) for class name of element. Please update your code with below code:
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
You can use directly in setInterval function
setInterval(function()
{
$.ajax({
type: "POST",
url: "vTagInfoCall.php",
processData: false,
contentType: false,
data: "",
success: function(result) {
$("#inputFieldDisplay").html(result);
}
});
}, 3000);//time in milliseconds
And the problem is in Html div also as showed by madhuri and haisen.
Whenever you used attributes(name,id,class whatever) you dont need to put dot,# or other symbols in the div or input.
So please fix it. I think it will work definitely.
<div id="#inputFieldDisplay"></div> // Wrong because of #
<div id="inputFieldDisplay"></div> //Right
you html code with some incorrect in id="#inputFieldDisplay"
<div class="container-fluid">
<div id="inputFieldDisplay"></div>
</div>
After many trials and methods, found out that I was using CDN of slim version of jQuery which caused this problem. Somehow there is some issue with Ajax in the slim version
I solved it by using the uncompressed version of jQuery CDN from here and that is it!!

Uploading File Images with AJAX and PHP

I am attempting to create an upload document which will upload a profile picture. I am having trouble capturing the data from the changePicture form which only has an input for the images and a submit. I have never used the FormData object to date, so I am still learning around this. Any guidance would be useful.
See my HTML
<form id="changePicture" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Update Your Profile Picture</label>
<input type="file" id="profilePic" class="form-control" name="profilePic">
<input type="hidden" value="<?php echo $id; ?>" name="id">
</div>
<button type="submit" id="updateProfileBtn" class="btn btn-success float-right">Upload Image</button>
</form>
Here is my AJAX code:
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(this),
cache: false,
contentType: false,
processData: false,
success: function(result){
$("#spinner").hide();
$("#changePicture").append(result);
setTimeout(function(){
$("#changePicture").slideDown();
}, 1500);
}
});
}, 3000);
});
}
The PHP file at this moment only echos out "Working" to see it accesses the page alright, which it does. However, when I attempt to locate the file through a variable nothing has been sent and returns undefined index.
this will be undefined because it's inside ajax's scope
Try:
me = this;
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: new FormData(me),
...
As, for me, when using ajax I always prefer to base64encode the image and pass it as a JSON to PHP but i guess that's a personal preference...
Why are you wrapping your AJAX call in a
setTimeout(function() {..})
?
By doing this, you cannot simply write new FormData(this), because the this context does not refer to the form that you are looking for.
Try executing the code without the timeout, or try storing the form data in a global variable
Edit: Example added:
var myFormData;
function updateProfilePic(){
$("#changePicture").on("submit", function(e) {
e.preventDefault();
$("#spinner").show();
myFormData = new FormData(this);
setTimeout(function(){
$.ajax({
url: "../ajax/admin/updateProfilePic.php",
type: "POST",
data: myFormData,
....

How to reset div data which I am appending on click?

Here I want to reset the appended data on click. So I can get the fresh data by removing the old data. Now actually data is coming, but the new data is getting appended with the old data which I need to remove.
$("#button").click(function(){
etc=$("#etc").val();
$.ajax({
url: 'db4.php',
type: 'POST',
data: {
etc: etc
},
error: function() {
$('#div1').html('<p>An error has occurred</p>');
},
success: function(data) {
var result = $.parseJSON((data));
$.each(result,function(i,field){
document.getElementById("div1").innerHTML=field.name;
$('body').append(document.getElementById("subasish123").innerHTML);
$('#subasish123').slice(0).hide();
});
}
});
});
<form>
<input id="etc" type="text" name="etc">
<label id="button">Click</label>
</form>
<div id="subasish123">
<div id="div1"></div>
</div>
Try redirecting your output to some other element instead of body.
Emptying the body of your HTML wouldn't be desirable.
Look at this fiddle for example:
jsfiddle.net

Jquery Post ajax variables wont enter PHP

I have the following code:
$(document).on('submit', function (event) {
event.preventDefault();
console.log('submitting');
hostingURL = '/<?echo $this->CI->uri->uri_string();?>';
$('form').attr('action', hostingURL);
var form = $(this);
$.ajax({
type: "POST",
url: hostingURL,
data: form.serialize()
}).done(function (data) {
$(document).unbind("submit");
$("#maincenter").html(data);
console.log('posted');
}).fail(function (data) {
alert('failed');
});
});
this is getting the requested url, and change the form to the action needed, then posting it to the server, and returning data.
server sided i have:
echo print_r($_POST);
echo "<br> type: ".$_SERVER['REQUEST_METHOD']." <br>";
It seems like whatever i do in my form wont acually submit it. The data back is correct, but from the server side code response i do get: Array ( ) 1 type: GET no matter what im doing.
So my question is: How can i acually make the form submit the post data?
The jquery function will be used on all my forms, so i need to get every field in the form to be submitted to.
Below is one example form.
example form:
<form method="POST">
<textarea class="textarea col-12" style="height:150px;" id="messageholder" name="profiltekst" placeholder="Profiltekst">
<? echo $userprofile->profiletext ?>
</textarea>
<div class="bottomform">
<input type="submit" class="makecenter" name="updateprofile" value="Endre profiltekst">
</div>
</form>

issue sending and retrieving value using ajax

This is a cleaner code of my preview problem, the idea is to send and retrieve a value using ajax, but the value is not being sent nor ajax seems to work. I updated this code because this way it could be easily tested on any machine. First time using ajax. Here is the code:
Javascript
<script>
jQuery(document).ready(function() {
jQuery('#centro').click( function() {
$.ajax({
url: 'request.php',
type:'POST',
data: $("#form").serialize(),
dataType: 'json',
success: function(output_string){
alert(output_string);
$('#cuentas').html(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
}
});
</script>
HTML:
<?php
$result = 'works';
?>
<form id="form">
<div id="centro">
Click here
<br>
<input type="hidden" name="centro" value="<?php echo $result; ?>">
</form>
<div id="cuentas">
</div>
PHP file, request.php
<?php
$centro = $_POST['centro'];
$output_string = ''.$centro;
echo json_encode($output_string);
?>
Looks like you never tell AJAX that the POST name is 'centro', try to change this:
data: $("#form_"+i).serialize(),
for this
data: { 'centro' : $("#form_"+i).serialize()},
I've run into the same problem with my ajax calls that I call via the POST method. My data was actually getting passed in the message body. I had to access it through the following method:
php://input
This is a read only wrapper stream that allows you to read raw data from the message body.
For more information on this wrapper visit this link.
Tray adding the following to your PHP file:
$centro = file_get_contents("php://input");
// Depending on how you pass the data you may also need to json_decode($centro)
echo json_encode($centro);
// See if you get back what you pass in
This read the message body (with my posted data) and I was able to access the value there.
Hope this helps.
try to using this code in your ajax post :
jQuery('#centro_'+i).click( function() {
$.ajax({
data: $("#centro_"+i).closest("form").serialize(),
dataType:"html",
success:function (data, textStatus) {
$('#cuentas').html(data);
alert(data);},
type:"post",
url:"load_cuentas.php"
});
});
Try this:
HTML
<?php
$i=0;
$f=0;
$consulta = $db->consulta("SELECT * FROM centro");
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){ ?>
<form id="form_<?php echo $f++; ?>"> //begin form with its id
<div class="centro" id="centro_<?php echo $i++; ?>">
<?php echo $resultados1['nombre_centro']; ?>
<br>
<input type="hidden" name="centro" value="<?php echo $resultados1['id_centro']; ?>">
<!--this is the data that is going to be sent. I set up a hidden input to do it.-->
</div>
</form>
<div id="cuentas" class="cuentas">
<!--where data is going to be displayed-->
</div>
<br>
<?php
}
}
?>
Javascript:
<script>
jQuery(document).ready(function() {
jQuery('.centro').on('click',function() {
var formElem=jQuery(this).closest('form');
jQuery.ajax({
url: 'load_cuentas.php',
cache: true ,
type:'POST',
dataType: 'json',
data: $(formElem).serialize(),
success: function(output_string){
jQuery(formElem).next('div.cuentas').html(output_string);
alert(output_string);
} // End of success function of ajax form
}); // End of ajax call
});
});
</script>
Server page:
<?php
include ('mysql.php');
$db = new mysql();
$centro = $_POST['centro']; //this is not getting any data. the whole ajax thing
$consulta = $db->consulta("SELECT * FROM cuenta WHERE id_center = '$centro'");
$output_string=array();
if($db->num_rows($consulta)>0){
while ($resultados1 = $db->fetch_array($consulta)){
$output_string []= 'test text';
}
}
mysql_close();
echo json_encode($output_string);
?>

Categories