How to change page in blade for JavaScript (Laravel) - javascript

This api is api.php.
My web and api are in the one project.
I want to change page in jquery request success result.
But I don't know what to do.
Could you do me a really big favour?
Code in the here :
<pre>
<script type="text/javascript">
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(".btn-primary").click(function(e){
e.preventDefault();
var account = $("input[name=account]").val();
var password = $("input[name=password]").val();
$.ajax({
type:'POST',
headers:{
Key: "xxx",
Version:"1.0.0",
},
url:'http://127.0.0.1:8000/api/Login',
data:{account:account, password:password},
success:function(data){
//I want to change page.
}
});
});
</script>
<code>

you can try to do like this
success:function(data){
$("html").html(data);
}
or
success:function(data){
$("body").html(data);
}
but i'm sure that javascript from those pages will not work so you will fetch only html
edit: also this will actually not change your page it will fetch html from ajax request and replace your current content with it
to make actual rederict you should use window.location.replace("https://faksesite.com/xxx.blade.php");

Related

How to use javascript to append the header of request before loading that page

I have 2 html files belong to two different controllers
This is belong to Index action of SignupController
Index.html
<div class="signup-small-font pull-right">Forgot password?</div>
When click at this link , it will go to that url and make a request to get the view of the ResetPassword Action of AccountController and get the resetPAssword.html
Now what i want is before making that request , i need to append a custom header in the request for the server side .
I was using ajax javascript :
function appendHeader(urlCulture){
$.ajax({
type: 'GET',
url: urlCulture,
headers: {
"Culture": 'zh'
},
})
}
What should i do in the index.html anchor link to call this function before requesting for the resetPassword.html
Like what I want is when I click at it , it will navigate to Account/Resetpassword and use the response getting from javascript file to render instead of a normal response
In your html file
<div class="signup-small-font pull-right"><a onclick="appendHeader(urlCulture)" href="#">Forgot password?</a></div>
In your js
function appendHeader(urlCulture){
$.ajax({
type: 'GET',
url: urlCulture,
headers: {
"Culture": 'zh'
},
success: function(res) {
window.location = 'Account/ResetPassword';
}
})
}
Give it a try. Im not quite sure if this is what you want to do.
you are using routes, you need to get the url from the javascript function
there is an example of that here:
Get local href value from anchor (a) tag
you could make something similar:
<div class="signup-small-font pull-right"><a onclick="return appendCustomHeader(this);" href="/Account/ResetPassword">Forgot password?</a></div>
in your js function like the previous reply you could make something like this:
function appendCustomHeader(element){
var url = element.href; // to get full url
$.ajax({
type: 'GET',
url: url,
headers: {
"CustomHeader": 'YourCustomHeader'
},
success: function(res) {
// here you make anything else with your response
}
})
return false;
}
I've not tested it, I hope it works for you.
it seems you can disable href redirecttion returning false,
see this:
How can I disable HREF if onclick is executed?

PHP & JS - append html and scripts on page

I'm using an ajax call to append a MVC partial view with some styles sheets and script files to my php page.
However it is not appending de <script> tags. I already checked my HTTP request on the network and it really brings those tags.
My code:
$.ajax({
type: 'POST',
url: 'http://localhost:63322/MyController/MyAction', //external url project
data: JSON.stringify(parameters),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: true,
crossDomain: true,
processdata: true,
headers: {
"Access-Control-Allow-Origin" : "*",
"Access-Control-Allow-Headers": "*"
},
success: function(result){
$(".pageContainer").html(result);
},
error: function(er){ alert('Error'); }
});
On ajax success function I already tried:
to use $(".pageContainer").empty().append(result)
to separate the script tags and add to <head> like this:
var elems = $(result);
var scripts = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() == "script";
}catch(er){ return false; }
});
var remainElems = $.grep(elems, function(e){
try{
return e.tagName.toLowerCase() != "script";
}catch(er){ return false; }
});
$.each(scripts, function(){ $('head')[0].appendChild(this); });
$(".pageContainer").append(remainElems);
to give some time before appending with setTimeout(function(){ $(".pageContainer").html(result); }, 1000);
to change <script> tags to <link type="text/javascript" src="http://someurl.com" rel="tag"/> and it was appended but the code wasn't executed
But nothing works.
What is wrong? What I'm missing?
My PHP page uses jquery-1.8.3 and jquery-ui-1.9.2.custom. This is the problem?
NOTE:
My question is very different from that on: Executing inside retrieved by AJAX
If you read both you will see they are very different. I already readed what and noticed that.
Solved. I don't know why but seems jquery-1.8.3 don't performs the insertion of the <script> tags to the html code dynamically.
I changed
<script type="text/javascript" src="js/jquery-1.8.3.js"></script>
to
<script type="text/javascript" src="js/jquery-1.10.2.js"></script>
and now it works.

AJAX post to php not getting caught

Posting from javascript ajax (which according to alerts it hits correctly and succeeds at) I cannot get the post from my PHP code.
<script>
function SavePlot() {
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
success:function() {
alert("gets here");
}
});
}
</script>
So above it reaches the gets here alert, so it should be posting, however it isnt caught by the below php:
if(isset($_POST['action']) && $_POST['action'] == 'SavePlot') {
echo '<script>alert("Doesnt get here")</script>';
}
I've tried many other answers but couldn't seem to succeed.
First of all, whatever you echo in your php script won't show up automatically in your current HTML DOM.
However, you can retrieve what you've echo-ed in the PHP in your AJAX call:
success: function(response){
console.log(response);
alert("gets here");
}
In your console, you should see:
<script>alert("Doesnt get here")</script>
Try specifying dataType as HTML in your ajax request.
$.ajax({
method: "POST",
url: 'PhpToR.php',
data:{action:'SavePlot'},
dataType : 'HTML',
success:function() {
alert("gets here");
}
});

How to redirect response from ajax request

I need to redirect to a page from response. I made a ajax call and can handle success. There is html page in response, but how to redirect it to that page.
Here's my code.
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = response;
}
});
});
Not using ajax would make this easier:
<form type="POST" action="xyz.json">
<label for="id">Enter ID:</label><input id="id" name="id">
<button type="submit" id="launchId">Send</button>
</form>
If you really want to use ajax, you should generate a distinct server response, containing only the HTML parts you want to update in your page or actual JSON.
If you insist on using the response which you currently get, the appropriate way of dealing with it would be document.write:
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'html', // it's no JSON response!
success: function(response) {
document.write(response); // overwrite current document
},
error: function(err) {
alert(err+" did happen, please retry");
}
});
Please try this.
var newDoc = document.open("text/html", "replace");
newDoc.write(response.responseText);
newDoc.close();
Your response is an object containing the full HTML for a page in the responseText property.
You can probably do $(body).html(response.responseText); instead of window.location.href = ...; to overwrite the current page content with what you got a response.
...
complete : function(response) {
$(body).html(response.responseText);
}
But i suggest you don't and there could be style and other conflicts with whats already there on the page.
In your HTML add a div with id as 'content', something like this
<div id='content'/>
Since your response is html in your complete function append the content into the div like this -
complete : function(response) {
$('#content').append(response.responseText);
}
Let me know if you still face issues.
try this
$("#launchId").live('click',function(){
var id= $("#id").val();
var data = 'id='+id;
$.ajax({
url: "xyz.json",
type: "post",
data: data,
dataType: 'json',
complete : function(response) {
window.location.href = '/yourlocation?'+response;
}
});
});

How to send large data using jquery post without redirect page?

I'd like to know how to send large data using jquery POST without redirect page?
I have a project to create a mobile chat, and to connect between user app and server, i use JSON.
this is jquery get json script looks like, as we know jsonGet can't deal with large data.
note: bigNumber has 8000 characters.
$.getJSON('process.php?input='+bigNumber, function(data) {
$.each(data.Chats, function(i,output)
{
$("#data").append(output.chat);
});
});
this is what i get when using getJSON for sending big number: 414 (Request-URI Too Large)
So, after i send bigNumber, i'll get a response from process.php as json data and adding to the body of html.
//---
now this is my code.
html file
<script src="jquery.min.js"></script>
<script>
$(function(){
$("#senddata").click(function() {
$.ajax({
dataType: "json",
url: "process.php",
data: { input:$("#bigNumber").val() },
success: function(data) {
$.each(data.Chats, function(i,output)
{
$("#data").append(output.key);
});
},
method: "POST"
});
});
});
</script>
<div id="data"></div>
<input type="text" id="bigNumber"/>
<button id="senddata">Send</button>
and this is process.php
header('Content-type: application/json');
$key = $_POST["input"];
$simpan_array = array();
$chat = array();
$chat["key"] = $key;
array_push($simpan_array, $chat);
echo json_encode(array("Chats" => $simpan_array));
and when i fill the textbox and press the "Send" button, nothing happens.
what's wrong?
Just found out what the problem is, it was an error in json format, which is displayed on process.php
You need to use a POST request instead. And since getJSON() is just a facade for ajax(), it is pretty easy to convert:
$.ajax({
dataType: "json",
url: "process.php",
data: { input:bigNumber },
success: function(data) {
$.each(data.Chats, function(i,output)
{
$("#data").append(output.chat);
});
},
method: "post"
});
use $.post
$.post('process.php',{input: bigNumber}, function(data) {
$.each(data.Chats, function(i,output)
{
$("#data").append(output.chat);
});
},'JSON');
Why cant you try to use websockets for chat application refer this page
Web Socket Server or Introduction to HTML5 WebSocket

Categories