Can't send post data from ajax - ajax

I have game.php file have this text input which sending three values to javascript:
<script src="js/jq.js"></script>
<script src="js/main.js"></script>
<input type="text" name="textfield2" id="textfield2" onkeyup="home(this.value,<?php echo $uid ?>,<?php echo $row_g['id'] ?>)" />
the javascript is :
function home(homeex,uid,mid){
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "inuphome.php",
data: { homeex: homeex, uid: uid, mid: mid },
success: function (result) {
}
});
}
inuphome.php file try to insert or update received data :
<?php
require_once('connections/connect.php');
$homeex=$_POST['homeex'];
$uid=$_POST['uid'];
$mid=$_POST['mid'];
$exp="SELECT * FROM expects Where uid='$uid' and mid='$mid'";
$result_ex=mysqli_query($berikane,$exp);
$row_ex=mysqli_fetch_assoc($result_ex);
$count = mysqli_num_rows($result_ex);
if ($count==0){
$query = "INSERT INTO expects VALUES ('','$uid','$mid','$homeex','','')";
mysqli_query($berikane,$query);
}
else{
$query = "UPDATE expects SET homeex='$homeex' where uid='$uid' and mid='$mid'";
}
?>
but nothing happens ,how can i solve this , best regards.

Related

How to show array result in ajax success using codeigniter?

I am fetching values from data using where in() mysql query and I got the correct result, but I don't know how to display the result in ajax success.
How do I display company name and email id from result data set?
my ajax code
<script type="text/javascript">
$('#ok').on('click', function() {
var vals = $('#show').val();
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: { vals:vals },
datatype: 'json',
success: function (data) {
alert(data);
$("#result").html(data);
var result = JSON.parse(data);
}
});
});
</script>
my controller code:
function get_company()
{
$vals = $this->input->post('vals');
$query = $this->db->query("SELECT * FROM customer` where company_id IN ($vals) ")->result();
echo json_encode($query);
}
my result:
[{"company_name":"xyz Ltd","company_email":"123#gmail.com"},{"company_name":"wer Jit","company_email":"2222#gmail.com"}]
assuming you get this json in your ajax success:
const json = '[ {
"company_name": "xyz Ltd",
"company_email": "123#gmail.com"
},
{
"company_name": "wer Jit",
"company_email": "2222#gmail.com"
}]
';
const obj = JSON.parse(json);
// you don't need this line, if you have set ajax datatype:'json'
you can get results for a single data set:
console.log(obj[0].company_name);
// this is how to get the first company name of the data set
// expected output: "xyz Ltd"
or you can loop through the whole data set
obj.forEach(element => $("#result").append(element.company_name + '<br>'));
see a working example
conclusion: your ajax function could look just simply like this:
$.ajax({
type: "POST",
url: "<?php echo base_url();?>email/get_company",
data: {
vals: vals
},
datatype: 'json',
success: function(data) {
obj.forEach(data => $("#result").append(data.company_name + '<br>'));
}
})

parameter not send in ajax request

I want to call the action method(AddCompare) using an Ajax request at the View,
My problem is that the parameter sent to AddCompare Action always has zero value,
While the parameter value in the function AddToCompare is correct
this is my code
View:
#model IEnumerable<Products>
#foreach (var item in Model)
{
<li>
<div class="left-block">
<div class="quick-view">
<a title="Add To Compare" class="heart" href="#" onclick="AddToCompare(15)"></a>
</div>
</div>
</li>
}
<script>
function AddToCompare(param) {
alert(param); //display correct value 15
$.ajax({
type: "GET",
url: "#Url.Action("AddCompare")",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({
id: param
}),
success: function (response) {
var myObject = eval('(' + response.d + ')');
if (myObject > 0) {
$(".errMsg").append("<ul><li>Data saved successfully</li></ul>");
}
else {
$(".errMsg").append("<ul><li>Opppps something went wrong.</li></ul>");
}
$(".errMsg").show("slow");
},
error: function (response) {
alert(response.status + ' ' + response.statusText);
}
});
}
</script>
Controller
public JsonResult AddCompare(int id)
{
//id is zero !!!
int param=id;
}
Where is the problem?
try to use
$.get
this is the syntax
$.get(URL,data,function(data,status,xhr),dataType)
In your AJAX call you don't need to stringify
$.ajax({
// your code
data: {id: param},
Decorate your action method with HttpGet even if it is GET by default. Just a better practice.
[HttpGet]
public JsonResult AddCompare(int id)
{
}
Since you are using a Get verb you can do this:
$.ajax({
type: "GET",
url: "/Controller/Action?ID=" + id,
dataType: "json"
}).done(function (response) {
//response code here
});
Change the controller and the action to your needs and you can add other settings to the ajax if needed.

Yii ajax file upload

I need to upload image with ajax call. But POST field with image always is empty. Part of my form:
<div class="col-lg-6">
<?php echo CHtml::activeFileField($model, 'logo'); ?>
<?php echo CHtml::textField('test', 'test'); ?>
<?php echo CHtml::submitButton('Upload'); ?>
<?php echo CHtml::ajaxSubmitButton('Upload ajax', '#');?>
</div>
If i click submitButton, then i have both test and logo fields - image uploaded.
And if i click ajaxSubmitButton, then i have only test field, logo is empty. What is the solution?
PS: i need non-extension solution.
You cannot upload files with ajaxSubmitButton by default. Use simple submit or some uploader.
If you want to upload image via ajax, here's example:
<?php echo CHtml::link('Upload ajax', '#', array("onclick"=>"js:upload_file(this)"));?>
In your js:
function upload_file(){
var fd = new FormData();
var e = document.getElementById("Model_logo");
fd.append( "Model[logo]", $(e)[0].files[0]);
$.ajax({
url: 'upload',
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function (data) {
},
error: function () {
alert("ERROR in upload");
}
});
}
Change Model to your model name and this will work. Also now you can append any data to FormData and it will be passed in $_POST and your file in $_FILES.
Be carefull, this way doesn't work on ie7 and ie8 as i remember.
Based on ineersa's answer, I made some improvements:
<?php echo CHtml::link('Upload ajax', '#', array("onclick"=>"upload_file()")); ?>
In your js:
function upload_file(){
var fd = new FormData($('#model-form')[0]);
$.ajax({
url: 'upload',
type: 'POST',
cache: false,
data: fd,
processData: false,
contentType: false,
success: function (data) {
},
error: function () {
alert("ERROR in upload");
}
});
}
This way you don't have to append each form field manually. All form data will be read automatically (including files). Just make sure that #model-form is changed according to your form id.
A way you don't need to call $.ajax(...) by yourself.
$(document).on('ajaxBeforeSend', 'form.my-form', function (event, jqXHR, settings) {
if ((settings.url.indexOf("js_skip") == -1) && $("form.my-form input[type=file]")[0].files.length) {
jqXHR.abort();
settings.cache = false;
settings.contentType = false;
settings.processData = false;
settings.data = new FormData(this);
settings.url = settings.url + "&js_skip=1";
jqXHR = $.ajax(settings);
}
});

Ajax form not submitting

I followed the Submit Ajax Form tutorial on tutsplus.com ,
but cannot figure out for the life of me why my data won't have addreply.php applied to it. When I look in my mysql table, the data does not get inserted. Any help would be greatly appreciated. I searched the web and have troubleshooted for many hours.
$(document).ready(function() {
$(".replyLink").one("click", function(){
$(this).parent().after("<div id='contact_form'></div>");
$("#contact_form").append("<form id='replyForm'></form>");
$("#replyForm").append("<input class='enterName' id='enterName' type='text'
name='name' placeholder='name' rows='1' cols='20' />");
$("#replyForm").append("<textarea class='enterReply' id='enterReply' name='comment'
placeholder='reply'></textarea>");
$("#replyForm").append("<input type='hidden' name='id' value=''>");
commentID= $(this).parent().attr('id');
$("#replyForm").append("<input class='replyButton' id='replyButton' type='submit' `value='reply'/>");`
$(".enterReply").slideDown();
$(".replyButton").slideDown();
});
$(".replyButton").click(function() {
var name = $("input#enterName").val();
var reply = $("textarea#enterReply").val();
var dataString = 'name='+ name.val() + '&comment=' + reply.val();
$.ajax({
type: "POST",
url: "addreply.php",
data: dataString,
success: function() {
}
});
return false;
});
**addreply.php**
<?php
session_start();
$replyID= $_POST['id'];
$name= $_POST['name'];
$comment= $_POST['comment'];
$type= $_POST['type'];
$song= $_POST['song'];
if($song == ''){
$song= 'not';
}
include 'connection.php';
if($_SESSION['signed_in'] == 'yes') {
$query1= "INSERT INTO ApprovedComments(name, comment, Authorized, type, reply_ID, song, date)
VALUES('$name', '$comment', 'YES', '$type', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query1);
// echo "hi";
}
if( !isset($_SESSION['signed_in']) ) {
$query2= "INSERT INTO PreApprovedComments(name, comment, reply_ID, song, date)
VALUES('$name', '$comment', '$replyID', '$song', NOW());";
$insertComment= mysql_query($query2);
}
mysql_close();
?>
Try
$.ajax({
type: "POST",
url: "addreply.php",
data: $("#replyForm").serialize()+'name='+ encodeURIComponent(name) +
'&comment=' + encodeURIComponent(reply),
success: function() {
}
});
this will post all the fields in the #replyForm form and the name and comment fields.

Jquery and ajax

I am quite new to JS and JQ so I am ask this basic question. I have code like this:
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('1500', function() {$(this).remove();
$('#messages').fadeOut('1000');
});
}
});
return false;
});
For now it is working like it should. But I want to add something more. Div with id #messages contains all messages, and I wish that upon deleting message it fadeout(it is working) and then load new data and present all messages again without the deleted one.
Also, there is a counter that counts unread messages, and I created separate page for ajax purpose, but I don't know how to go on from fadeOut.
This is the code from the seperate page:
<?php if(isset ($messages)) { ?>
<?php foreach ($messages as $msg){ ?>
<div class="col_3">
<?php
if($msg['read'] == 0){ echo 'Status of message: Unreaded';}
elseif($msg['read'] == 1){echo 'Status of message: Readed';}
echo "<p>Message from: $msg[name]</p>";
echo "<p>Sender email: $msg[email]</p>";
echo "<p>Message: <br />$msg[message]</p>"; ?>
Delete message
</div>
I edited code a bit, but still nothing.
$(".delete").click(function() {
var commentContainer = $(this).parent();
var id = $(this).attr("id");
var string = 'id='+ id ;
$.ajax({
url: "<?php echo site_url('messages/delete') ?>",
type: "POST",
data: string,
cache: false,
success: function(){
commentContainer.slideUp('600', function() {$(this).remove();
$('.messages').fadeOut('2000', function(){$(this).remove();
$('#messages').load("<?php echo site_url('messages/show') ?>").show().fadeIn('1000');
});
});
}
});
return false;
});
When I look page source I can see that the content has been changed, but it is not displayed.
I didn't quite understand what you are trying to do but if this is what you mean by saying but I don't know how to go on from fadeOut you can put a callback function to fadeOut
$('#messages').fadeOut('1000', function () {
// Do something here
);

Resources