<script>
$(document).ready(function(){
$(".submit_modal1").click(function(e){
e.preventDefault();
id = this.id;
name = $("#fname_"+id).val();
email = $("#email_"+id).val();
phone = $("#phone_"+id).val();
upload_resume = $("#upload_resume_"+id).val();
$.ajax({
type:"POST",
data:{"id":id,"name":name,"email":email,"phone":phone,"upload_resume":upload_resume},
url:"<?php echo base_url(); ?>send",
success:function(data){
$("#send_hr").html(data);
}
});
$("#upload_resume_"+id).change(function(){
var file_data = $("#upload_resume_"+id).prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$('#imgsss').html("<img src='<?php echo base_url(); ?>resource/loading.gif' />");
$.ajax({
url: '<?php echo base_url(); ?>upload_resume',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
$("#imgsss").html(php_script_response);
}
});
});
});
});
</script>
In this code, I trigger two events i.e. click and change where I want to run $("#upload_resume_"+id).change(function(){}); inside $(".submit_modal1").click(function(e){}). Is it possible to do it or is there any other way to trigger both event simulteniously. How can I do this ?Please help me.
Thank You
$("#upload_resume_"+id).change(function(){ does not trigger the event
If you cannot just chain the PHP from the other PHP, then you likely mean
$(function() {
$(".submit_modal1").click(function(e) {
e.preventDefault();
id = this.id;
name = $("#fname_" + id).val();
email = $("#email_" + id).val();
phone = $("#phone_" + id).val();
upload_resume = $("#upload_resume_" + id).val();
$.ajax({
type: "POST",
data: {
"id": id,
"name": name,
"email": email,
"phone": phone,
"upload_resume": upload_resume
},
url: "<?php echo base_url(); ?>send",
success: function(data) {
$("#send_hr").html(data);
$("#upload_resume_" + id).change() // HERE
}
});
$("#upload_resume_" + id).change(); // OR HERE
});
// any change to upload_resume*
$("[id^=upload_resume]").change(function() {
var file_data = $(this).prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$('#imgsss').html("<img src='<?php echo base_url(); ?>resource/loading.gif' />");
$.ajax({
url: '<?php echo base_url(); ?>upload_resume',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response) {
$("#imgsss").html(php_script_response);
}
});
});
});
Related
PHP variable:
<?php $course_details_url_back = site_url("home/lesson/".slugify($course_details['title'])."/".$course_id); ?>
script do action for form:
$(document).on('submit','#form_create_user',function(e){
e.preventDefault();
var fd = new FormData(this);
var obj = $(this);
fd.append('course_id', "<?php echo $this->uri->segment(4); ?>");
obj.find('input[type="submit"]').val("Tworzenie...")
$.ajax({
url: $(this).attr("action"),
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
// obj.find('input[type="submit"]').val("Confirm user")
}
});
$.ajax({
url: "<?php echo site_url('home/saveValues/'); ?>",
data: fd,
cache: false,
processData: false,
contentType: false,
type: 'POST',
success: function (dataofconfirm) {
// do something with the result
toastr.success("Success created user.");
obj.find('input[type="submit"]').val("Potwierdź")
}
});
})
After submit form I need do above actions and also I need to implement to above code refresh page on submit form and back to url.
For this I've separate code:
document.getElementById("form_create_user").onsubmit = function(){
window.location.replace("<?php echo $course_details_url_back; ?>");
}
But can anyone help me implement this to current one code?
How to echo value input type text when use ajax upload ?
This is my code for upload file to dir attachments_files and it's work good.
But i have some issue. I want to know how to echo value from id="username_uploader" in upload.php using php ?
i tried to use like this
echo $_POST['username_uploader'];
but not work. Please help me .
index.php
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<input id="username_uploader" type="text" name="username_uploader" value="test_user"/>
<input id="attachment_file_input_id" type="file" name="sortpic" onchange="test_fn()"/>
<div id="demoajax"></div>
<script>
function test_fn () {
var file_data = $('#attachment_file_input_id').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: 'upload.php',
dataType: 'text',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(php_script_response){
alert("upload success");
$('#demoajax').append(php_script_response);
}
});
};
</script>
upload.php
<?php
if ( 0 < $_FILES['file']['error'] ) {
echo 'Error: ' . $_FILES['file']['error'] . '<br>';
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "attachments_files/" .$_FILES["file"]["name"]);
echo $_POST['username_uploader'];
}
?>
You need to include the username_uploader value in the FormData you send, as you currently omit it. Try this:
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('username_uploader', $('#username_uploader').val());
It would also be better practice for your PHP code to return JSON, that way you don't need to worry about the formatting or whitespace in the returned value. Here's a complete example:
function test_fn () {
var form_data = new FormData();
form_data.append('file', $('#attachment_file_input_id').prop('files')[0]);
form_data.append('username_uploader', $('#username_uploader').val());
$.ajax({
url: 'upload.php',
type: 'POST',
dataType: 'json',
cache: false,
processData: false,
data: form_data,
success: function(response){
alert("upload success");
$('#demoajax').append(response.uploader);
}
});
};
<?php
if (0 < $_FILES['file']['error']) {
echo json_encode(array('error' => 'Error: ' . $_FILES['file']['error'] . '<br>'));
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"], "attachments_files/" .$_FILES["file"]["name"]);
echo json_encode(array('uploader' => $_POST['username_uploader']));
}
?>
This is my ajax function
$(function(){
$("#myform").submit(function(){ //i want to get data from my form after submittingit
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
success: function(data){
alert(data);
}
});
return false;
});
});
this is my controller class function
function viewCustomerData(){
if($_POST){
$name = $_POST['name'];
return 'name';
}
else {
return false;
}
}
other thing is i tried to alert data string taken from form serialize, but it also empty. I want to return data set from database after sending key word from javascript file. i tried if the javascript file connect correctly with my controller function. so i tried to return some value and display it using alert box. but it gives empty result.
This is better way to submit a form with ajax
$(document).on("submit", "#myform", function(event)
{
event.preventDefault();
$.ajax({
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData"
type: "POST",
data: new FormData(this),
processData: false,
contentType: false,
success: function (data, status)
{
alert(data);
},
error: function (xhr, desc, err)
{
}
});
});
try this
$(function(){
$("#myform").submit(function(){
dataString = $("#myform").serialize();
alert(dataString);
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
cache: false,
datatype: 'json',
success: function(data){
alert(data.result);
}
});
});
});
in controller
function viewCustomerData(){
if($this->input->post('name'){
$result = $this->input->post('name');
} else {
$result = false;
}
header('Content-Type: application/json');
echo json_encode(array('result' => $result));
}
you cant alert $("#myform").serialize(); because this is an object instead of alert it try console.log($("#myform").serialize();)
then open browser console and see what is printed
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>index.php/customer/viewCustomerData",
data: dataString,
})
.done(function( data ) {
if ( console && console.log ) {
console.log( "Sample of data:", data);
}
});
var postID = $post->ID;
$.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri();?>/b.php",
data:{postID:postID},
dataType: 'json',
success: function(result){
if(result!=''){
r = $.parseJSON(result);
final_rating = get_final_rating(r);
set_stars(final_rating);
}
}
});
var arr = [a,b,c,d,e,f];
$.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri();?>/b.php",
data:{star:arr, postID:postID},
async :false,
cache: false,
success: function(result){
if(result === '1')
{
final_rating = result;
set_stars(final_rating);
}
}
});
You can do something like this with jQuery:
var postID = <?php echo $post->ID; ?>,
arr = [a,b,c,d,e,f],
req1, req2;
req1 = $.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri();?>/b.php",
data: {postID:postID},
dataType: 'json'
});
req2 = $.ajax({
type: "POST",
url: "<?php echo get_template_directory_uri();?>/b.php",
data: {star:arr, postID:postID},
async: false,
cache: false
});
$.when(req1, req2).then(function (data1, data2) {
// data1[0] = result
if(data1[0] !== '') {
r = $.parseJSON(result);
final_rating = get_final_rating(r);
set_stars(final_rating);
}
// data2[0] = result
if(data2[0] === '1') {
final_rating = result;
set_stars(final_rating);
}
});
var postID = $post->ID; should be replaced by:
var postID = <?php echo $post->ID; ?>;
You're also doing Ajax wrong. You should make all requests on admin-ajax.php - http://codex.wordpress.org/AJAX_in_Plugins
You then use different action parameters to differentiate between different Ajax calls.
Hello guys I have a problem in getting the response from my ajax. If I display it in the console. I can view it. But How do I assign it in a variable?
Here's what I have.
In my PHP code I have this
public function checkPassword($password){
$username = $this->session->userdata('username');
$validate = $this->members_model->checkPassword($password,$username);
echo $validate;
}
In my jquery I have this
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var g = response;
if(g == 1){
$('#existing_info').html('Password is VALID'); //Doesn't display the VALID if the response is 1. Why?
}else{
$('#existing_info').html('Password is INVALID!');
}
}
});
});
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
var k=response;
if(k.indexOf("1") != -1)
$('#existing_info').html('Password is VALID');
else
$('#existing_info').html('Password is INVALID!');
}
});
response is in response variable of success function.
indexof returns the index within the calling String object of the first occurrence of the specified value, starting the search at fromIndex,
returns -1 if the value is not found.
try something like this
<script>
var k = null;
$(function(){
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
if(response == 1){
k = response;
}
}
});
});
})
</script>
In your success response you will get what you are set to output in php.
If you want to get an array or data set you can encode it in json in your php script like
echo json_encode($validate);
Then in your jquery you can use this response like this
var responseData = jQuery.parseJSON(response);
console.log(responseData);
console.log will print json object in browser console.
You can use this json object like this
responseData.some_data
Ajax is asynch so you will have access to it after the ajax method returns:
$('#existing').on('keyup',function(){
var id = '<?php echo $this->session->userdata("user_id"); ?>';
var password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json'
}).then(function(response){
var k;
if(response == 1){
k = response;
//call another function that needs k here
}
});
});
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
success: function(response){
k=response;
}
});
var k = null;
$('#existing').on('keyup', function() {
var id = '<?php echo $this->session->userdata("user_id"); ?>',
password_url = '<?php echo site_url("member/checkPassword/' +id+ '"); ?>';
$.ajax({
type : 'POST',
url : password_url,
success : function(data) {
if(data === '1') {
k = data;
}
}
});
});
response parameter itself contain data so just assign that to variable and use it.
$.ajax({
type: 'POST',
url: password_url,
success: function(response){
if(parseInt(response) == 1){
var k = response;
}
}
});
Your response data is in response variable of success function. Since the response type is json you can assign it directly to javaScript variable.
Also you comparison is wrong try if(g == '1') instead if(g == 1). You are getting a string as response and your checking equality with a numeric type which won't be equal at any point.
ie:-
$.ajax({
type: 'POST',
url: password_url,
data: '',
dataType: 'json',
contentType:"application/json",// Add Content type too
success: function(response){
k=response;
}
});
if your json response is as shown below
{"menu": {
"id": "file",
"value": "File",
"popup": {
"menuitem": [
{"value": "New", "onclick": "CreateNewDoc()"},
{"value": "Open", "onclick": "OpenDoc()"},
{"value": "Close", "onclick": "CloseDoc()"}
]
}
}}
you can access menuitem array as
success: function(response){
k=response.menu.popup.menuitem;
}
File Name votepost.php
<?php
include("domain.php");
$csid=$_POST['CSID'];
$voteid=$_POST['VOTEID'];
$myid=$_POST['MYID'];
$usertype=$_POST['USERTYPE'];
$myurl =URL."putvote.php?csid=".$csid."&voterid=".$myid."&voteid=".$voteid."&usertype=".$usertype;
$myurl=str_replace(" ","%20",$myurl);
$jsondata = file_get_contents($myurl);
$data = json_decode($jsondata);
if($data->response=="true")
{
echo 'true';
}
else
{
echo 'false';
}
?>
ajax reponse use $.trim for IF ELSE
$.post("votepost.php", {CSID:csid,VOTEID:voteid,MYID:myid,USERTYPE:usertype}, function (data) {
if($.trim(data)=='true')
{
alert('ok');
}
else
{
alert('error');
}
});
I hope you will solve your problem
You can create the js blank array and assign it to the same array.
var resp = [];
jQuery.ajax({
dataType: "json",
method: 'post',
url: 'ajax.php',
async: false,
data: {postData: 'postData'},
success: function(data){
resp.push(data);
}
});