I was wondering what was the correct way to do this ajax function using javascript. Here is the code:
$.ajax({
'url' : '',
'type' : 'POST',
'data' : last_time,
'data' : "last_time=yes",
'beforeSend' : function () {
},
How can I set 2 data values?
PHP:
if(isset($_POST['last_time'])){
jQuery's $.ajax method expects either
a querystring last_time=yes
or a JSON object {last_time: "yes"}
Not both. Like so...
Query string:
var dataString = "last_time=yes&date=4162014&action=last_time";
$.ajax({
'url' : 'localhost/actions/last_time.php',
'type' : 'POST',
'data' : dataString,
'beforeSend' : function () {
},
or
JSON:
var data = {
action: "last_time",
last_time: "yes",
date: "4162014"
};
$.ajax({
'url' : 'localhost/actions/last_time.php',
'type' : 'POST',
'data' : data,
'beforeSend' : function () {
},
With a simple php backend
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
switch ($_POST['action']}) {
case 'last_value':
$return_array = array(
"status" => "great!",
"message" => "Hey there!"
);
die(json_encode($return_array));
break;
default:
$return_array = array(
"status" => "default"
);
die(json_encode($return_array));
break;
}
} else {
die("access denied");
}
You could only have one property with name data (object keys must be unique, you could think javascript object as a hash map struct).
It should be a query string like 'foo=yes&bar=no' or an object {foo: 'yes', bar: 'no'}.
Related
i have tried to call variable $hetest but it always return with true however i add false as a parameter when i am calling the function
//function which i call in javascript file
create_new_user_send_sms(user_Mobile_Number,false)
.fail(error => console.error(error))
.done(response => {})
//the ajax call of the function i created
function create_new_user_send_sms(mobile_number,hestatus){
return jQuery.ajax({
type : "POST",
url: ajax_object.ajax_url,
data: {
action : 'create_user_send_sms',
mobile_number : mobile_number,
auto_Login_status : "true",
he : hestatus,
},
success: function (data) {
},
error : function(error){
console.log("error:" + error);
}
});
}
//the code in the php function create_user_send_sms
$mobile_number = $_POST['mobile_number'];
$auto_Login_status = $_POST['auto_Login_status'];
$hetest = $_POST['he'];
$password = wp_generate_password( 4, false, false );
Try using the filter_validation function to treat boolean post vars:
$hetest = filter_var ($_POST['he'], FILTER_VALIDATE_BOOLEAN);
I am trying to update my database using ajax in laravel. When i click the button (toggle button) it should update the database enable column from 1 to 0.
Here is the script written in the view
$(".toggle-btn").change(function() {
var id = $(this).attr('name'); // $(this) refers to button that was clicked
$.ajax({
url: '/adminpanel/dviulaan/stt',
method: "post",
data: {'id' : id} ,
dataType: "json",
});
});
Here is my route
Route::post('adminpanel/dviulaan/stt', 'AdminDvAnnouncement#status');
And here is the controller function
public function status()
{
$id = Input::all();
if (Request::ajax()) {
DvAnnouncement::where('announcement_id', $id)->update(
[
'enable' => '0',
'user_updated' => Auth::user()->id,
'updated_at' => new DateTime,
]);
}
$response = array(
'status' => 'success',
'msg' => 'Option created successfully',
);
return Response::json( $response );
}
When i click the button it shows the following error in the consol
POST http://localhost/adminpanel/dviulaan/stt 500 (Internal Server Error)
Please help me to find the error.
I have even changed the controller method as below
public function status(Request $request)
{
$id = Input::get('id');
if (Request::ajax()) {
DvAnnouncement::where('announcement_id', $id)->update(
[
'enable' => '0',
'user_updated' => Auth::user()->id,
'updated_at' => new DateTime,
]);
}
$response = array(
'status' => 'success',
'msg' => 'Option created successfully',
);
return Response::json( $response );
}
$id = Input::all(); => $id = Input::get('id');
UPD after logs
include in head
<meta name="csrf-token" content="{!! csrf_token() !!}" />
then change in function
$(".toggle-btn").change(function() {
var id = $(this).attr('name'); // $(this) refers to button that was clicked
$.ajax({
url: '/adminpanel/dviulaan/stt',
method: "post",
data: {'id' : id, '_token': $('meta[name="csrf-token"]').attr('content')} ,
dataType: "json",
});
});
I have created this jQuery AJAX script for submitting a form:
$(document).ready(function() {
// process the form
$('#reviewForm').submit(function(e) {
$("#reviewError").hide();
$("#reviewSuccess").hide();
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'description' : $('input[name=description]').val(),
'one' : $('input[name=price]').val(),
'two' : $('input[name=location]').val(),
'three' : $('input[name=staff]').val(),
'four' : $('input[name=service]').val(),
'five' : $('input[name=products]').val(),
'shopID' : $('input[name=shopID]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'post/review.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
if ( ! data.success) {
$("#reviewError").show();
} else {
// ALL GOOD! just show the success message!
$("#reviewSuccess").show();
}
})
// stop the form from submitting the normal way and refreshing the page
e.preventDefault();
});
});
Sadly the form submits though the normal way and not though the AJAX. Im at a loss to what the issue can be. I have tried the return false and such but that didn't work at all.
I think you are missing e.preventDefault(); at the begining of the submit(); and to use e.
$(document).ready(function(e) {
// process the form
$('#reviewForm').submit(function(e) {
e.preventDefault();
$("#reviewError").hide();
$("#reviewSuccess").hide();
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'description' : $('input[name=description]').val(),
'one' : $('input[name=price]').val(),
'two' : $('input[name=location]').val(),
'three' : $('input[name=staff]').val(),
'four' : $('input[name=service]').val(),
'five' : $('input[name=products]').val(),
'shopID' : $('input[name=shopID]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'post/review.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
if ( ! data.success) {
$("#reviewError").show();
} else {
// ALL GOOD! just show the success message!
$("#reviewSuccess").show();
}
})
});
});
Hope this Helps.
$(document).ready(function() {
// process the form
$('#reviewForm').click(function(e) {
$("#reviewError").hide();
$("#reviewSuccess").hide();
var formData = {
'name' : $('input[name=name]').val(),
'email' : $('input[name=email]').val(),
'description' : $('input[name=description]').val(),
'one' : $('input[name=price]').val(),
'two' : $('input[name=location]').val(),
'three' : $('input[name=staff]').val(),
'four' : $('input[name=service]').val(),
'five' : $('input[name=products]').val(),
'shopID' : $('input[name=shopID]').val()
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'post/review.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
if ( ! data.success) {
$("#reviewError").show();
} else {
// ALL GOOD! just show the success message!
$("#reviewSuccess").show();
}
})
// stop the form from submitting the normal way and refreshing the page
e.preventDefault();
});
});
Use 'Click' event instead of 'Submit' will work definatly
-- Ajax Code
var User = function(){
return {
init : function(){
document.getElementById('login').addEventListener('click', this.login);
},
login : function(){
var username = $("#username").val(),
password = $("#password").val();
$.ajax({
url : 'http://localhost/oc2/user_info/login',
method : 'post',
dataType : 'json',
data : {
username : username,
password : password
},
success : function(response){
alert('h'); <-- add the php return value id here.
window.location.href = "main.html";
},
error : function(response){
alert(response.responseText);
}
});
}
};
}();
-- PHP CodeIgniter
public function login()
{
$post = $this->input->post();
$where = array(
'email_address' => $post['username'], //"turbobpo.johnrey#gmail.com",
'password' => md5($post['password']) //"e10adc3949ba59abbe56e057f20f883e"
);
$user_info = $this->get_by($where);
if(isset($user_info['id']))
{
$this->session->set_userdata('user_info', $user_info);
$response = array(
'id' => $user_info['id'], <-- this i want to pass to my ajax
'success' => TRUE
);
}
else
{
$response = array(
'success' => FALSE
);
}
print json_encode($response);
}
Hello can you help me for this part i already management to went far on this php ajax i'm not used in creating this application please i need help i place a comment on the codes to see where i wanna retrieve the value from php to my ajax code so i can use it on my next retrieving of file where i use the id of a login user to get his available access in a grid form. it would be a plus if you can also show me how can i use that data to pass it back in php again the id after retrieving it on the success ajax return array value.
var User = function(){
return {
init : function(){
document.getElementById('login').addEventListener('click', this.login);
},
login : function(){
var username = $("#username").val(),
password = $("#password").val();
$.ajax({
url : 'http://localhost/oc2/user_info/login',
method : 'post',
dataType : 'json',
data : {
username : username,
password : password
},
success : function(response){
response.id; // Here is the id JQuery parses JSON for you
window.location.href = "main.html";
},
error : function(response){
alert(response.responseText);
}
});
}
};
}();
I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type : 'post',
cache : false,
url : 'test/result.php',
data : {result : stuff},
success: function(resp) {
alert(resp);
}
});
});
In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php from $_POST array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)
Then you can send actual key value pairs, using JSON format like...
{"ques_5" : "19", "ques_4": "19"}
Try this
var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));
above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.
And then in php explode that string.
Other possible solutions.
First
var obj = { 'item1': 'value1', 'item2': 'value2' };
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : JSON.stringify(obj) },
success: function(resp)
{
alert(resp);
}
});
Second
var a = $.JSON.encode(obj);
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : a },
success: function(resp)
{
alert(resp);
}
});
In PHP File
<?php
$json = $_POST["data"]
var_dump(json_decode($json));
?>
You can send the array in json format to the php and then use json_decode function to get back the array like
In ajax call you have to send json for that you need to first make array of the values so that you get it in right form
so that you json look like {"ques_5":"9","ques_4":19}
and use in ajax call
data: JSON.stringify(`your created json`),
contentType: "application/json; charset=utf-8",
dataType: "json",
IN PHP it look like
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function
// on the HTML side a simple JavaScript call from a link
<a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>
// on JavaScript side
function CargaZona(fc, div, params) {
var destino = "#" + div;
var request = $.ajax({
url : "inc/phpfunc.php",
type : "POST",
data : {
fc : fc,
params : JSON.stringify(params)
},
dataType : "html"
});
request.done(function (msg) {
$(destino).html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
// on phpfunc.php page
<?php
$params = "{'key1':'value1','key2':'value2'}";
$fc = 'def';
if (isset($_POST['fc'])) { $fc = $_POST['fc']; }
if (isset($_POST['params'])) { $params = $_POST['params']; }
switch ($fc) {
default:
call_user_func($fc,$params);
}
function democonllamada($params) {
$params = json_decode("$params", true);
echo "ok llegaron".$params['key1'];
}
?>