I get two variable in my jquery function and how i pass it in my data inside ajax call and get it in laravel controller
This is my function
$('#updateProduct').on('submit', function(e){
e.preventDefault(e);
var redirect_url = $(this).find("[name='redirect_url']").val();
var url = $(this).attr('action');
var method = $(this).attr('method');
var videos = document.getElementById('videoToUpload').files[0];
var myData ={
'name': $(this).find("[name='name']").val(),
'description': $(this).find("[name='description']").val(),
'brand': $(this).find("[name='brand']").val(),
'category': $(this).find("[name='category']").val(),
'condition': $(this).find("[name='condition']").val(),
'shipper': $(this).find("[name='shipper']").val(),
'shipping_from': $(this).find("[name='shipping_from']").val(),
'shipping_paid_by': $(this).find("[name='shipping_paid_by']").val(),
'shipping_within' :$(this).find("[name='shipping_within']").val(),
'shipping_weight': $(this).find("[name='shipping_weight']").val(),
'shipping_fee': $(this).find("[name='shipping_fee']").val(),
'seller_get' : $(this).find("[name='seller_get']").val(),
'price_per_unit': $(this).find("[name='price_per_unit']").val(),
'selling_fee' : $(this).find("[name='selling_fee']").val(),
'is_active':$(this).find("[name='is_active']:checked").val(),
//'videos' :$("#videoToUpload").files[0],
//'videos' : document.getElementById('videoToUpload').files[0],
}
console.log(data);
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: {'myData':myData
'videos':new FormData("videos", document.getElementById('videoToUpload').files[0])
},
success: function(data){
alert("Products updated successfullly");
console.log(data);
//window.location.href = redirect_url;
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
Here i am having two variable one videos and other myData now my question is how to pass these two variable in data and request this variable in laravel controller
You have done everything well, but forget to write comma
$.ajax({
type: method,
url: url,
dataType: 'JSON',
data: {'myData': myData, 'videos': new FormData("videos", document.getElementById('videoToUpload').files[0]) },
success: function(data){
// .........
},
error: function(jqXHR, textStatus, errorThrown) {
// .........
}
});
By the way, don't spend time to define each input to variable, use jquery serialize and PHP unserialize, or you can use this code below to create Serialize Object
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name] !== undefined) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
Related
<script>
$(document).ready(function(){
var finishedCount = 0; //Count the amount of completed Ajax requests
var data; //Keep track of the first request's data
var data1; //Keep track of the second request's data
function finished(){
finishedCount++;
if (finishedCount >= 2){ //2 is the amount of requests
//Do what you need done using data and data1
$(document).on('mouseenter','.grid-item',function(){
var container = $(this);
container.find('.title-wrap').html('<p class="job-name">'+ data +'</p>');
container.find('.title-wrap').html('<p class="client-name">'+ data1 +'</p>');
console.log(data);
});
};
};
$(document).on('mouseenter','.grid-item',function(){
var container = $(this);
var jobId = container.children().find('.title-wrap-hidden').text();
$.ajax({
url: 'db_job_name_lookup.php',
type: 'POST',
data: {jobId: jobId},
success: function(data) {
// success
data = data;
finished();
// console.log(data);
},
error: function(jqXHR, textStatus, errorThrown){
// error
alert(errorThrown);
}
});
$.ajax({
url: 'db_client_name_lookup.php',
type: 'POST',
data: {jobId: jobId},
success: function(data1) {
// success
data1 = data1;
finished();
// console.log(data1);
},
error: function(jqXHR, textStatus, errorThrown){
// error
alert(errorThrown);
}
});
});
$(document).on('mouseleave', '.grid-item', function(){
var container = $(this);
container.find('.title-wrap').html('<p class="job-name"></p>');
container.find('.title-wrap').html('<p class="client-name"></p>');
});
});
</script>
Hi everyone, I want to use one event to make multiple AJAX request and I want to have both response result available to use at the same time. I tried using the above code, but it only gives back one response at a time and it even looks confused as to which result it should give, I tried using $.when and $.then but I pretty sure I'm not using it right. How would I accomplish this task?
PAGE 1
<?php
require_once("../includes/site_init.php");
if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
$job_id = $_POST['jobId'];
$portfolio_item_client = JobClient::find_by_sql('SELECT client_id FROM '.'job_client'." WHERE job_id = '" . $job_id . "' ");
$client_name = Client::find_by_sql('SELECT name FROM '.'client'." WHERE id = '" .$portfolio_item_client[0]->client_id."'");
echo $client_name[0]->name;
}else {
echo 'result failed';
}
?>
PAGE 2
<?php
require_once("../includes/site_init.php");
if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
$job_id = $_POST['jobId'];
$portfolio_item_name = Job::find_by_sql('SELECT name FROM '.'job'." WHERE id = '" . $job_id . "' LIMIT 1");
echo $portfolio_item_name[0]->name;
}else {
echo 'result failed';
}
?>
Try using $.when to resolve the promises
$(document).on('mouseenter', '.grid-item', function() {
var container = $(this);
var jobId = container.children().find('.title-wrap-hidden').text();
var ajax = $.ajax({
url: 'db_job_name_lookup.php',
type: 'POST',
data: {
jobId: jobId
},
success: function(data) {
// success
data = data;
},
error: function(jqXHR, textStatus, errorThrown) {
// error
alert(errorThrown);
}
});
var ajax1 = $.ajax({
url: 'db_client_name_lookup.php',
type: 'POST',
data: {
jobId: jobId
},
success: function(data1) {
// success
data1 = data1;
},
error: function(jqXHR, textStatus, errorThrown) {
// error
alert(errorThrown);
}
});
var container = $(this);
$.when(ajax, ajax1).done(function(data, data1) {
container.find('.title-wrap').html('<p class="job-name">'+ data +'</p>');
container.find('.title-wrap').html('<p class="client-name">'+ data1 +'</p>');
});
});
});
if you want to do a single ajax call you do the following: single_page.php
<?php
require_once("../includes/site_init.php");
header('Content-Type: application/json');
if(isset($_POST['jobId']) && $_POST['jobId'] !==NULL && $_POST['jobId'] !==0){
$job_id = $_POST['jobId'];
$portfolio_item_client = JobClient::find_by_sql('SELECT client_id FROM '.'job_client'." WHERE job_id = '" . $job_id . "' ");
$client_name = Client::find_by_sql('SELECT name FROM '.'client'." WHERE id = '" .$portfolio_item_client[0]->client_id."'");
$data['client_name']=$client_name[0]->name;
$portfolio_item_name = Job::find_by_sql('SELECT name FROM '.'job'." WHERE id = '" . $job_id . "' LIMIT 1");
$data['portfolio_item_name']=$portfolio_item_name[0]->name;
echo json_encode(array('result'=>$data))
}else {
echo json_encode(array('result'=>'result failed'))
}
?>
js:
$(document).on('mouseenter', '.grid-item', function() {
var container = $(this);
$.ajax({
url: 'single_page.php',
type: 'POST',
data: {
jobId: jobId
},
success: function(data) {
container.find('.title-wrap').html('<p class="job-name">'+ data.result.portfolio_item_name +'</p>');
container.find('.title-wrap').html('<p class="client-name">'+ data.result.client_name +'</p>');
},
error: function(jqXHR, textStatus, errorThrown) {
// error
alert(errorThrown);
}
});
});
Lets make an analogy. An Ajax request is like sending somebody to the store, and when they get back, they will do what you tell them. What you are trying to do is send two people to the store separately, and force them both to return at the same time. That won't work.
What you can do is keep track of which has returned, and whenever one comes back, check if they are both back. If they are, then you can tell them what to do at once (call a function). Or, you can have one go to the store, and when they return, they can tell the other one to go to the store, and when the second one returns, then tell them what to do (call a function).
Bottom line: you can't force them to finish at the same time, but you can wait until they are both done to run container.find('....
EDIT: Assuming all you need is to execute code once both requests are done, I would do this:
var finishedCount = 0; //Count the amount of completed Ajax requests
var data; //Keep track of the first request's data
var data1; //Keep track of the second request's data
function finished(){
finishedCount++;
if (finishedCount >= 2){ //2 is the amount of requests
//Do what you need done using data and data1
}
}
$.ajax({
url: 'db_job_name_lookup.php',
type: 'POST',
data: {jobId: jobId},
success: function(data) {
data = data;
finished();
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
$.ajax({
url: 'db_client_name_lookup.php',
type: 'POST',
data: {jobId: jobId},
success: function(data1) {
data1 = data1;
finished();
},
error: function(jqXHR, textStatus, errorThrown){
alert(errorThrown);
}
});
I have to get values from two different URLs and then to merge it. I know it would much better if i'll get all of the data in one URL, but that's how i've got and i need to work with it.
I want to print out the value of a_value, but it's been printed out while b hasn't returned his value. I've read some articles of how to make the functions synchronous but still don't know how to implement it into my code, and don't know what is the best solution for my case. I'm pretty new with JavaScript and still need some help and guiding.
function any_function() {
$.ajax(
{
url : '/url1',
type: "GET",
success:function(data, textStatus, jqXHR)
{
$("#print").html(a(data));
}
});
}
function a(data){
x = 'any value' //`do something with data and insert to this variable`
a_value = x + b(`some id that extracted from data`)
return a_value
}
function b(id){
$.ajax({
url: '/url2',
type: 'GET',
success: function (data, textStatus, jqXHR) {
b_value = c(data, id)
}
});
return b_value
}
function c(data, id){
//do something with `data` and return the value
return c_value
}
function f() {
var request1 = $.ajax({
url : '/url1',
type: 'GET'
});
var request2 = $.ajax({
url: '/url2',
type: 'GET'
});
$.when(request1, request2).done(function(result1, result2){
data1 = result1[0]
data2 = result2[0]
// r1 and r2 are arrays [ data, statusText, jqXHR ]
// Do stuff here with data1 and data2
// If you want to return use a callback or a promise
})
}
This can be done in a synchronous-looking fashion with promises:
$.get(url1)
.then(function(data1){
return $.get(url2)
})
.then(function(data2){
return $.get(url3);
})
.then(function(data3){
// All done
});
You just need to make the second call in the success handler of the first one:
function any_function() {
$.ajax({
url : '/url1',
type: "GET",
success:function(data, textStatus, jqXHR) {
$("#print").html(a(data));
b("someId");
}
});
}
function a(data){
x = 'any value' //`do something with data and insert to this variable`
a_value = x + b(`some id that extracted from data`)
return a_value;
}
function b(id){
$.ajax({
url: '/url2',
type: 'GET',
success: function (data, textStatus, jqXHR) {
b_value = c(data, id);
return b_value;
}
});
}
function c(data, id){
//do something with `data` and return the value
return c_value
}
I am attempting to do an AJAX call with the Select2 jquery plugin. The query seems to be working, but the issue occurs when .results() is called on the options object:
Uncaught TypeError: options.results is not a function
Here is my HTML:
<input class="form-control" type="number" value="2125" name="topic_relation[source_topic_id]" id="topic_relation_source_topic_id" />
Here is my JS:
$(document).ready(function() {
$('#topic_relation_source_topic_id').select2({
minimumInputLength: 3,
ajax: {
url: "<%= grab_topics_path %>",
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
q: term, //search term
page_limit: 30, // page size
page: page, // page number
};
},
processResults: function (data, page) {
var more = (page * 30) < data.total;
return {results: data.topics, more: more};
}
},
formatResult: topicFormatResult,
formatSelection: formatRepoSelection,
escapeMarkup: function (m) { return m; }
});
function topicFormatResult(topic) {
return topic.name
}
function formatRepoSelection(topic) {
return '<option value="'+ topic.id +'">' + topic.name + '</option>'
}
});
Here is the returned JSON:
{"total":2, "topics":[{"id":305,"name":"Educational Assessment, Testing, And Measurement"},{"id":3080,"name":"Inspectors, Testers, Sorters, Samplers, And Weighers"}]}
Here is the code which is failing:
function ajax(options) {
var timeout, // current scheduled but not yet executed request
handler = null,
quietMillis = options.quietMillis || 100,
ajaxUrl = options.url,
self = this;
return function (query) {
window.clearTimeout(timeout);
timeout = window.setTimeout(function () {
var data = options.data, // ajax data function
url = ajaxUrl, // ajax url string or function
transport = options.transport || $.fn.select2.ajaxDefaults.transport,
// deprecated - to be removed in 4.0 - use params instead
deprecated = {
type: options.type || 'GET', // set type of request (GET or POST)
cache: options.cache || false,
jsonpCallback: options.jsonpCallback||undefined,
dataType: options.dataType||"json"
},
params = $.extend({}, $.fn.select2.ajaxDefaults.params, deprecated);
data = data ? data.call(self, query.term, query.page, query.context) : null;
url = (typeof url === 'function') ? url.call(self, query.term, query.page, query.context) : url;
if (handler && typeof handler.abort === "function") { handler.abort(); }
if (options.params) {
if ($.isFunction(options.params)) {
$.extend(params, options.params.call(self));
} else {
$.extend(params, options.params);
}
}
$.extend(params, {
url: url,
dataType: options.dataType,
data: data,
success: function (data) {
========> var results = options.results(data, query.page, query); <==========
query.callback(results);
},
error: function(jqXHR, textStatus, errorThrown){
var results = {
hasError: true,
jqXHR: jqXHR,
textStatus: textStatus,
errorThrown: errorThrown
};
query.callback(results);
}
});
handler = transport.call(self, params);
}, quietMillis);
};
}
Since the plugin calls results(), you should also declare results: function (data, page) instead of processResults: function (data, page).
I'm trying to call Javascript function inside controller action method, Is there any right way to call setTimeout() to be invoked on certain condition inside controller action method ?
window.setTimeout(function() {
alert("test");
$.ajax({
type: "POST",
url: "'.$this->createUrl("/operator/createViopNode/").'",
data: {
id: '.$bc_id.',
callid:"'.$num.'",
taskid:'.$this->taskid.'
},
success: function(msg){
var ifrm = document.getElementById("frame");
ifrm = (ifrm.contentWindow) ? ifrm.contentWindow : (ifrm.contentDocument.document) ? ifrm.contentDocument.document : ifrm.contentDocument;
ifrm.document.open();
ifrm.document.write(msg);
ifrm.document.close();
},
error: function (jqXHR, textStatus, errorThrown){
alert("" + textStatus + ", " + errorThrown);
}
});
}, parseInt('.$tps_call.'));
I need to write above js function inside controller action method, how to write this ?
Index.csHtml
function abc()
{
alert("called")
}
now Ajax Call function
function ExecuteAjax(URL,Data,Success)
{
try {
$.ajax({
type: "post",
url: URL,
data: Data,
contentType: "json",
success: function (data) { if (typeof Success == "function") { Success(data); } }
})
} catch (e) {
alert(e.message)
}
}
Call ajax like this
ExecuteAjax("/Home/FillColorDropDown", "", function (data) {
eval(data.script);
});
return from controller
if(demo=="true")//put condition here whatever you want
{
string strscript="abc();";
}
protected JObject jobj = new JObject();
jobj.Add("Script", strscript);
return Json(jobj);
Execute js function when controller return success
You should register your javascript function like this:
function actionTest(){
$cs = Yii::app()->clientScript;
$cs->registerScript('my_script', 'alert("Hi there!");', CClientScript::POS_READY);
$this->render('any_view');
}
source
I am looking for advice to ensure that I am using callbacks and javascript coding using generally accepted js guidelines. What is listed below is two functions which are chained together. Basically its a list of checks which need to be completed prior to creating the entity. I don't expect the final version to use a ajax POST but it is a good way to test all of the error handling.
Advice or recommendations would be appreciated!! I will give credit to the best explained and critiqued answer.
function relationship_check(app_label, model, company_id, params, form, callback_function){
// This will check to see if a relationship exists. This works even on new objects.
kwargs = $.extend({}, params);
kwargs['app_label'] = app_label;
kwargs['model'] = model;
kwargs['relationship__company'] = company_id;
kwargs['error_on_objects_exists_and_no_relation'] = true;
ajax_req = $.ajax({
url: "{% url 'api_get_discover' api_name='v1' resource_name='relationship' %}",
type: "GET",
data: kwargs,
success: function(data, textStatus, jqXHR) {
callback_function(form, params)
},
error: function(data, textStatus, jqXHR) {
results = $.parseJSON(data.responseText)
if (results['object_exists'] && ! results['relationships_exists']){
django_message(results['create_string'], "info");
} else {
django_message(results['error'], "error");
}
return false
}
})
return false
};
function create_community(form, data){
var self = $(this),
ajax_req = $.ajax({
url: self.attr("action"),
type: "POST",
data: data,
success: function(data, textStatus, jqXHR) {
django_message("Saved successfully.", "success");
},
error: function(data, textStatus, jqXHR) {
var errors = $.parseJSON(data.responseText);
$.each(errors, function(index, value) {
if (index === "__all__") {
console.log(index + " : " + value )
django_message(value[0], "error");
} else {
console.log(index + " : " + value )
apply_form_field_error(index, value);
}
});
}
});
}
$(document).on("submit", "#community_form", function(e) {
e.preventDefault();
clear_form_field_errors("#community_form");
var data = {
name: $(this).find("#id_name").val(),
city: $(this).find("#id_city").val(),
cross_roads: $(this).find("#id_cross_roads").val(),
website: $(this).find("#id_website").val(),
latitude: $(this).find("#id_latitude").val(),
longitude: $(this).find("#id_longitude").val(),
confirmed_address: $(this).find("#id_confirmed_address").val()
};
console.log(data)
relationship_check(
'community', 'community', '{{ request.user.company.id }}',
data, "#community_form", create_community);
});