Use one ajax call for different page and div? - javascript

I use this code to make ajax call to change the content of div in main page without reloading the page :
function ajaxcall()
{
$.ajax({
type: "POST",
url: "/create.php",
success: function( returnedData ) {
$( '#container' ).html( returnedData );
}
});
}
and I call it like that :
<p><a onclick="ajaxcall()" >Create</a></p>
The issue is very complicated because I have to call 4 pages in the same div :
create.hmtl ; update.html; delete.html ; read.html
Also I have 2 different forms in the same page that required the same thing, I mean I should do the same thing for the second form with another div "container-1",then I have 2 div for exmaple in create.html :
create.html :
<div id="container">
....
</div>
<div id="container-1">
....
</div>
So I call create.html everytime but different div for different form, the question is to use a minimum clean code to do all what I explained above?
Edit
To explain more my problem, I have 4 options (create/update/delete/read) with 4 pages, and in every page they are 2 div and 2 contents for 2 forms, I should change div content of every option(CRUD) for every form in webpage!
form -> ajax call content -> create.html -> div:container
form-1 -> ajax call content -> create.html -> div:container-1
form-1 -> ajax call content -> update.html -> div:container-1

You can add those as parameters to the function and make it like below
function ajaxcall(url, data, targetDivId)
{
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
$("#"+targetDivId).html( returnedData );
}
});
}
For your scenario:
I assume that even the AJAX url may change as currently it's pointing to create.php. In case it's same then you can avoid tht parameter.
<p><a onclick="ajaxcall('/create.php', {} , 'container-1')" >Create</a></p>
<p><a onclick="ajaxcall('/update.php', object2 , 'container-2')" >update</a></p>
<p><a onclick="ajaxcall('/delete.php', object3, 'container-3')" >Delete</a></p>

Following mohamedrias' answer, if you also needed to process each alternate path in the CRUD use case differently, you can use global event handlers.
Don't handle when making the request:
$.ajax({
type: "POST",
url: url,
data : data,
success: function( returnedData ) {
}
});
Do handle seperatley for each alternate path in CRUD
$(document).ajaxSuccess(function(event, xhr, settings) {
var query = settings.data;
var url = settings.url;
if (url.match(/create.php/) && query.match(/container1/)){
$("#container1").find(".form-1").html( xhr.responseText );
}
});
You should also notice that the selector in my example implies that "form-1" is a Class and not an ID.
IDs must be unique but Classes can occur many times.
Following this rule, if you wanted to reuse the same form for each alternate path you can do so by addressing discrete elements in the form using unique class names for each element. The container Div must have a unique ID (as you have already done). But you must give that element context by chaining the selectors to first select the div using ID and then select the element using class.

If I understood it correcyly you want to provide an argument to the ajax calling function to apply the return content from "/create.php" to a different div.
function ajaxcall(id, path)
{
$.ajax({
type: "POST",
url: path,
success: function( returnedData ) {
$("#"+id).html( returnedData );
}
});
}
And in html you can set the id like
<p><a onclick="ajaxcall(this.id, "/create.php")" >Create</a></p>

var xhr = new XMLHttpRequest();
xhr.onload = function(){
var document = xhr.response;
var container = document.getElementById('container');
var container-1 = document.getElementById('container-1');
console.log(container, container-1);
// or
// var containers = document.querySelectorAll("#container, #container-1" );
//console.log(containers);
}
xhr.open('POST','/create.php');
xhr.setRequestHeader(
'Content-Type',
'application/x-www-form-urlencoded'
);
xhr.responseType = 'document';
xhr.send();

Related

Pass Ajax Variable value to html element in different page

How can I pass data from a query in php and set it's result using an ajax method.
Here is what I have so far in a file called file1.php:
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
I wanna put the contents in this html element in the php file file2.php:
<p id ="resultFromFile1" name = "results">No Results</p>
Many stack overflow posts haven't been any help. Could someone point me in the right direction?
It's wrong approach.
You should rather create php script which will save your ajax request data in let's say database and then in file2.php load this data from DB, not directly update file
First of all what kind of content is query.php returning? Is it a JSON Object or are you just "echoing" the output as a string?
Next Question: Are you using jQuery, AngularJS or something in that direction?
Usually what you want to do is get the information from the "query.php" and pass it as a JSON formatted ajax result...
Now to your actual Problem: You want to get the element called "resultFromFile1" that's inside file2.php but you aren't adding anything to the "visible scope" yet since Load only loads the content but it doesn't add the content to any element you have to define an element holding your "file2.php". If i were you to avoid all these Problems i would use AngularJS for displaying your data in to a view and just include your "result" template via ng-include and let the ajax fill the document..
To solve your Problem:
<script type = "text/javascript">
// Your Solution
function myAjax () {
$.ajax( { type : 'POST',
data : { },
url : 'query.php',
success: function ( data ) {
$doc = new DomDocument();
$doc->Load('file2.php');
$element = $doc->getElementById('resultFromFile1');
},
error: function ( xhr ) {
alert( "error" );
}
});
}
// My Solution for this problem using native js
// Load the "file2" contents in to the file2Holder element
LoadUrlToElement('file2.php','file2Holder',function(data){
/* When the first loading of file2.php is done, load the results from the query.php and put it in to the element called "resultFromFile1" which we just loaded and placed in to the dom before. But i would recommend you to use AngularJS to avoid this Callback hell and get many cool features that webdevelopers don't want to miss these days.... */
LoadUrlToElement('query.php','resultFromFile1',function(){
alert('Content of resultFromFile1 is => '+document.getElementById('resultFromFile1'));
});
});
function LoadUrlToElement(url,elementID,done) {
$.ajax( { type : 'POST',
data : { },
url : url,
success: function ( data ) {
if(document.getElementById(elementID) === undefined){
alert("Can't proceed cause the content holder"+elementID+" is not found");
return; // Abort here cause there is no container with this id...
}
document.getElementById(elementID).html = data;
if(done !== undefined && typeof done === 'function') done(data);
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
<div id="file2Holder"></div>

laravel: view not shown after ajax post

I want to show a view after ajax post. but view shown only in browser console.not in main browser.what i am doing wrong?? please help. i am stucking here for one week.i am using laravel 5.3
javascript:
$('#btn-save').click(function () {
var doctor_id=$('#doctors_id').val();
var doctor_name=$('#autocomplete-custom-append').val();
var patient=$('#p_name').val();
var mobile=$('#p_mobile_no').val();
$.ajax({
url: '{{URL::to('confirmation')}}',
type: "POST",
data: {
'doctor_id':doctor_id,
'doctor_name': doctor_name,
'patient_name': patient,
'mobile_no':mobile
},
dataType: 'json',
success: function (data) {
//window.location.href=data.url;
}
});
return false;
});
controller:
public function serialConfirmation(Request $request)
{
$doctor_id=$request->input('doctor_id');
$doctor_name=$request->input('doctor_name');
$patient_name=$request->input('patient_name');
$mobile_no=$request->input('mobile_no');
return view('serial.confirmation',compact('doctor_id','doctor_name','patient_name', 'mobile_no' );
}
You will need to assing the html to your page you will do this in your javascript like so:
$("#wrapper").html(data);
If so that you want to put the html to a element with the id of wrapper.
Note this will exchange the current html in the element with the html returned from php if you want to preserve current html and just append the new html you will have to use either prepend or append jquery function depending on if you want to prepend or append.
if you want to redirect, there is no need to use ajax, just change the method you call serialConfirmation to call your url /confirmation then keep the function as you have it.
(You can have a form with action="{{ url('/confirmation') }} )
And you can access the data in your view like this {{$doctor_id}}
Just change your success like below:
success: function (data) {
// Insert your html code into the page using ".html(html)" method
// or other similar method.
}
Something like this way.

How to change specific element on ajax ?

I have ajax call that change the user info. And I want to get the value from the response and change value of specific element
Example: the element that need to chage:
<div id="changeMe"><!-- New Value --> </div>
Ajax call:
$.ajax({
url: "?rr=profile",
}).success(function(response) {
});
How to change the value of the "changeMe" element ONLY ?
Try it with
$.ajax({
url: "?rr=profile",
}).success(function(response) {
var r = $( response ).find( "#changeMe" );
$( "#changeMe" ).html( r.html() );
});
You could do this:
$.ajax({
url: "?rr=profile",
}).success(function(response) {
$('#changeMe').html('Your new content');
});
This will change the element with the ID "changeMe". See also JQuery API
To get a value you can use the same method.
Example:
var res = $('#someOtherElement').html();
The variable res has now the content of the element.
You can do it by following line.
$('#changeMe').html(response);
You can use the .html() or .text() jQuery methods depending on your requirements (whether the response content is HTML or plain text):
$.ajax({
url: "?rr=profile",
}).success(function(response) {
$('#changeMe').html(response);
});
switch .html(response) with .text(response) if that's better for you.
In your success function your can do like below
.success(function(response) {
$("#changeMe").append("Your value");
});
If you want to change the text then :
$('#changeMe').text('new data from response');
If you want to change CSS as well :
$('#changeMe').css('property', 'attribute');

Issue populating ajax response into a div

What am I missing? I've added the get element by Id and I'm definitely getting a response back, I checked using firebug and the response is correct. But I can't figure out why it won't populate my div area.
<script>
$(document).ready(function () {
$("#cmdSend").click(function () {
// Get he content from the input box
var mydata = document.getElementById("cmdInput").value;
$.ajax({
type: "POST",
url: "/Terminal/processCommand",
data: { cmd: mydata }, // pass the data to the method in the Terminal Contoller
success: function (data) {
//alert(data);
// we need to update the elements on the page
document.getElementById("terminal").value = document.getElementById("terminal").value + mydata;
document.getElementById("terminal").value = document.getElementById("terminal").value + data;
},
error: function (e) { alert(e); }
})
});
});
</script>
And the Div I want the response to be put in:
<div class="terminal" style="overflow:scroll">
<br>
</div>
First, you are calling document.getElementById(), but your div does not have an ID of terminal, it has a class called terminal.
Second, you are using jQuery but then switch back to classic JavaScript. You could update your code to the following:
success: function (data) {
//alert(data);
// we need to update the elements on the page
var existingHtml = $(".terminal").html();
$(".terminal").html(existingHtml + mydata + data);
}
Note that the $(".SomeName") selector is for selecting by class and $("#SomeName") is to select by id.
Edit and Note
If this terminal div could start to get a lot of data inside of it, you may look at using the .append() function in jQuery to prevent having to make a copy of the HTML and overwrite the HTML each time a request is made. The update would be something similar to the following (its a little shorter and should be more efficient as well)
success: function (data) {
//alert(data);
// we need to update the elements on the pag
$(".terminal").append(mydata + data);
}
If you want to get your element by id, add an id to the div:
<div id=terminal class="terminal" style="overflow:scroll">
<br>
</div>
If you want to change the contend of div not using jquery, you should use innerHTML instead of value.
document.getElementById("divID").innerHTML = document.getElementById("divID").innerHTML + data

Making a function affect a element in another page

I made a function that is invoked for the lack of better words from a page, lets call it Page1, the function is called when a button is clicked, at the end of said function it calls another one that creates (or should seeing I haven't been able to test it) a html and appends it to a div with a #lista id.
The problem is that this div is another page (Page2), so I don't know if there is some syntax like in ajax where you specify where you want those values to go, so basically page 1 calls a function (on another file just in case) that function calls another and the result of that function goes on Page1 (another file, again just in case)
Here is my jQuery/JS code to further illustrate:
$("#btnAceptar").click(function() {
var idlab = $('#txtNumLab').val(),
capacidad = $('#txtCapacidad').val(),
carrera = $('#txtCarrera').val(),
ubicacion = $('#txtUbicacion').val();
var request = $.ajax({
url: "includes/functionsLabs.php",
type: "post",
data: {
'call': 'addLab',
'pIdLab':idlab,
'pCapacidad':capacidad,
'pCarrera':carrera,
'pUbicacion':ubicacion},
dataType: 'json',
success: function(response){
alert('exito')
agregar();
}
});
});
This function should affect a element with id #Lista on Page2.
function agregar(){
var div = $( "#lista" ).append( "<div class='box'>
<p>Lab #'numero'</p>
<p class='info'><a href='#' id='lnkInfo'>Info</p></a>
<p class='info'><a href='reservarLab.html'>Reservar</p></a>
</div>" );
div.id = querySelectorAll('#lista > div').length +1;
var numero = div.id;
$('#numero').append(div);
}
Thanks a lot in advance!
Yes you can get content from another page using jQuery:
Ajax request gets the entire file, but you can filter the content once it's retrieved:
$.ajax({
url:href,
type:'GET',
success: function(data){
$('#content').html( $(data).find('#IDofDivToFind') );
}
});
Second Approach (Untested)
You can use JQuery .load() method:
$( "#content" ).load( "ajax/test.html div#content" );
Reference:
http://api.jquery.com/load/

Categories

Resources