This is the method in which i manage the data send with jquery.ajax. By default is send an empty string and on each change i watch the change on the input and resend it. Through console things are good but in php $this->searchField always has the value of an empty string
function checkInfo(){
if(isset($_POST['searchField'])){
$this->searchField = json_decode($_POST['searchField']);
if ($this->searchField != ""){
$this->query = "SELECT * FROM myguests WHERE firstName like '%".$searchField."%'";
}
else if ($this->searchField == "") {
$this->query = "SELECT * FROM myguests ORDER BY id";
}
$this->tableDisplay();
exit();
}
else{
return "error";
}
}
This is my jquery ajax function :
function searchGuests(users){
var data = {
"searchField": users
};
console.log(data);
$.ajax({
type: "POST",
dataType: "text",
url: "controllers/manageTable.php",
data: data
})
.done(function(tr) {
$("#tableBody").empty();
$("#tableBody").append(tr);
})
.fail(function(error){
console.log(error);
});
};
Any idea what I am missing?
Try encoding the users to a string before sending it over.
function searchGuests(users){
var data = {
"searchField": JSON.stringify(users);
};
console.log(data);
$.ajax({
type: "POST",
dataType: "text",
url: "controllers/manageTable.php",
data: data
})
.done(function(tr) {
$("#tableBody").empty();
$("#tableBody").append(tr);
})
.fail(function(error){
console.log(error);
});
};
Related
I need help with my ajax function. I have a form that submits data with the same input name
When I run my code without javascript, I can insert multiple input data with the same name,
Submitted structure
{"_token":"CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu","id":"7","service_name":["asfd","safd"]}
When I implement javascript, a concatenated string is sent to the controller and this makes the service_name inaccessible.
formdata:"_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=7&service_name%5B%5D=sdfg&service_name%5B%5D=gfds&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=8&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=9&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=10&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=11&_token=CepbQkKwKziSRwDJKuqlEa5i4E21Y5jvSbmDNvqu&id=18"
My javascript function
jQuery("form.ajax").on("submit", function (e) {
e.preventDefault();
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: $(".ajax#servicesForm").serialize()
},
dataType: "JSON",
success: function (response) {
console.log(response);
},
error: function (jqXHR, exception) {
var msg = "";
if (jqXHR.status === 0) {
msg = "Not connect.\n Verify Network.";
} else if (jqXHR.status === 404) {
msg = "Requested page not found. [404]";
} else if (jqXHR.status === 500) {
msg = "Internal Server Error [500].";
} else if (exception === "parsererror") {
msg = "function Requested JSON parse failed.";
} else if (exception === "timeout") {
msg = "Time out error.";
} else if (exception === "abort") {
msg = "Ajax request aborted.";
} else {
msg = "Uncaught Error.\n" + jqXHR.responseText;
}
}
});
});
My PHP Controller Function
public function insert(Request $request)
{
return response()->json($request);
}
use FormData Object, to send fromdata
fd = new FormData();
fd.append("input-name", value1);
fd.append("input-name2", value2 OR arry of value);
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: "post",
data: {
formdata: fd
}
I found a workaround:
First, I created an array, and pushed all instances of input[name='service_name[]'] into the array.
Then I passed the data with ajax and was able to insert the data.
var serviceArray = new Array(), id;
jQuery.map($("input[name='service_name[]']"), function(obj, index) {
serviceArray.push($(obj).val());
});
My ajax script then:
jQuery.ajax({
url: "/admin/adminpanel/insertService/",
type: 'post',
data: {
'service_name': serviceArray,
'id': id
},
dataType: 'JSON',
success: function(response) {
console.log(response);
}
});
I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name
This my code for send realtime message.
After send message, it is not display unless i refresh the page.
I want this chat box message to show the new message entered.
This is to show the user List In the left side of the page:
$(".user-w").click(function() {
var user_id = $(this).attr("id");
// alert(user_id);
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/getMessageByLists/')?>",
data: {
'user_id': user_id
},
datatype: 'html',
success: function(data) {
$("#loadMessages").html(data);
}
}); });
This is Send function:
$("#sendMessage").click(function(e)
{e.preventDefault();// alert("test");
var msg = $("#message_text").val();
var touser = $("#touser").val();
//var reservation_id = $("#reservation_id").val();
if (!msg || msg.length == 0) {
alert("enter a message");
} else {
$.ajax({
type: "POST",
url: "<?php echo base_url('Message/addMessage')?>",
// data:{'msg' : msg, 'touser' : touser, 'reservation_id' : reservation_id},
data: {
'msg': msg,
'touser': touser
},
datatype: 'text',
// Page.Server.ScriptTimeout = 300;
success: function(data) {
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
} else {
alert("noo eroor chat message");
}
},
});
//return false;
} }); // End Send Function
if I am not wrong then, their might be an element with class as "user-w", also that element have "id" attribute too. So you can just execute following line, after sending the message to user.
$(".user-w[id='"+ touser +"']").trigger("click");
above line needs to placed in "success" method, like as below:
if (data == 1) {
//$("#loadMessages").load();
$("#message_text").val("");
$(".user-w[id='"+ touser +"']").trigger("click");
} else {
alert("noo eroor chat message");
}
this is how the javascript looks like
<script type="text/javascript">
$(document).ready(function () {
$('#loginButton').click(function () {
//this.disabled = true;
debugger;
var data = {
"userid": $("#username").val(),
"password": $("#password").val()
};
$.ajax({
url: "/Account/LoginPost",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
contentType: "application/json",
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
},
error: function () {
alert('Login Fail!!!');
}
});
});
});
I am getting the alert('Login fail') also debugger not getting hit.
I am using jquery 1.9.1 and have included unobstrusive
my controller is this as you can i am passing string values not object values
to the controller so stringify is justified here
[HttpPost]
public JsonResult LoginPost(string userid, string password)
{
using (someentities wk = new someentities())
{
var LoginUser = wk.tblUsers.Where(a => a.Username.Equals(userid)&&a.Password.Equals(password)).FirstOrDefault();
if (LoginUser != null)
{
FormsAuthentication.SetAuthCookie(userid,false);
Session["Username"] = LoginUser.Username;
Session["Password"] = LoginUser.Password;
Session["Name"] = LoginUser.Name;
return Json(new { Success = true }, JsonRequestBehavior.AllowGet);
}
else
{
TempData["Login"] = "Please Enter Correct Login Details";
return Json(new { Success = false }, JsonRequestBehavior.AllowGet);
}
}
// If we got this far, something failed, redisplay form
}
when page is loading these error are shown
$(..) live is not a valid function in
(anonymous function) # jquery.unobtrusive-ajax.js:115
(anonymous function) # jquery.unobtrusive-ajax.js:163
take a look to the success function
success: function (response) {
if (response.Success) {
$.get("#Url.Action("Search", "Home")", function (data) {
$('.container').html(data);
});
}
else
window.location.href = "#Url.Action("Index", "Home")";
}
you are using multiple ", combine it with the single one ', this is a syntax error, try to check the code on an editor such as Atom, to avoid this kind of errors
Stringify converts an object to a string. Have you tried passing data an object instead of a string? Try replacing JSON.stringify(data), with data?
I have a question about javascript and cakephp, I need to send data via Post and recive it in the other side (the controller) and make the normal process that I already have. But I don't know how can I catch the data. I'm working with Ajax
function editFun(clicked_id){
var id = clicked_id;
$("#Content").empty();
$('#Content').html("<b>Loading response...</b>");
$.ajax({
type: 'POST',
url: '/Posts/edit',
data: (id)
})
.done(function(data){
console.log(data);
$('#Content').html(data);
})
.fail(function(data){
$('#Content').html(data);
});
}
public function edit($id = null) {
if (!$id) {
throw new NotFoundException(__('Invalid post'));
}
$post = $this->Post->findById($id);
if (!$post) {
throw new NotFoundException(__('Invalid post'));
}
if ($this->request->is(array('post', 'put'))) {
$this->Post->id = $id;
if ($this->Post->save($this->request->data)) {
$this->Session->setFlash(__('Your post has been updated.'));
return $this->redirect(array('action' => 'index'));
}
$this->Session->setFlash(__('Unable to update your post.'));
}
if (!$this->request->data) {
$this->request->data = $post;
}
}
In that case you should send your id in URL. So even GET method is enough, because you controller receive $id param from URL.
So all what you need to change are post arguments:
$.ajax({
type: 'POST',
url: '/Posts/edit/' + id
})