I have a trouble in using ajax() function. I have an html file with a form and have a segment of JavaScript code:
<script>
$(document).ready(function(){
$("form").submit(function(){
var url = "xxx.php/";
var param = $("#streetInput").serialize() + "&";
param += $("#cityInput").serialize() + "&";
param += $("#stateInput").serialize();
htmlobj = $.ajax({
url: url,
data: param,
type: 'GET',
dataType: 'JSON',
success: function(output) {
// parse the data here
},
error: function() {
}
});
});
});
</script>
I want construct an URL pointing to a specified php file by GET method. However, I don't know how to retrieve the parameters sent through URL in xxx.php file. I don't know how to debug. I just type
<?php
echo $_GET("streetInput");
echo $_GET("cityInput");
......
$xml = simplexml_load_file($url);
?>
but it didn't work. Can someone help me out? I want to give three parameters through URL to xxx.php, then print those elements
In xxx.php file, I construct a URL for an API request and get an XML file back. And I want to convert the $xml file to JSON format and return to my html file.
Change your JS code to:
<script>
$(document).ready(function(){
$("form").submit(function(){
var url = "xxx.php";
var param = $("#streetInput").serialize() + "&";
param += $("#cityInput").serialize() + "&";
param += $("#stateInput").serialize();
$.ajax({url: url, data: param, type: 'GET'});
});
});
</script>
Or, if you have only these fields in form, use this:
<script>
$(document).ready(function(){
$("form").submit(function(){
var url = "xxx.php";
var param = $(this).serializeArray(); //<- Or, .serialize() can also be used
$.ajax({url: url, data: param, type: 'GET'});
});
});
</script>
Related
I need to pass a ajax variable as route parameter, but it is showing an error.
This is the error:
Too few arguments to function App\Http\Controllers\PermissaoController::status(), 0 passed and exactly 1 expected
This is the script:
<script type="text/javascript">
$(document).ready(function() {
$('#status_id').change(function(){
var usuario = (location.pathname).split('/');
var status = this.value;
$.ajax({
type: 'get',
url: "{{route('permissao.status', "+status+")}}",
data: {status: status, usuario: usuario[2]},
dataType:"json",
success:function(html){
$('#projeto_id').find('option').remove();
$('#projeto_id').append('<option value="">Selecione...</option>');
for(var i = 0; i< html.length;i++){
$('#projeto_id').append('<option value="'+html[i]['id']+'">'+html[i]['titulo']+ '-' + html[i]['codigo']+ '</option>');
}
}
})
})
})
This is my function in controller:
public function status($sd) {
$usuario = Usuario::where('id', $sd)->get();
return $usuario;
}
How can I do it?
You cant pass JavaScript to laravel route method.
It should be
url: "permissao/status/"+status,
if you face base url issue then you can do the following
var url="{{url('/')}}/";
then in ajax
url: url+"permissao/status/"+status,
If you want to use route.
var status = this.value;
var url ="{{route('permissao.status', ":status")}}";
url = url.replace(":status", status);
Use variable url with ajax call.
<script>
$(document).ready(function(){
$(document).on('change','#compId',function () {
var username = $(this).val();
/*var token = $("input[name=_token]").val();
var dataString = 'username='+username+'&token='+token;
*/
var data1={username}
$.ajax({
type: "get",
url : 'depttBranch',
data : data1,
success : function(data){
$('#branchId').html(data);
alert(data);
},error : function(){
alert('out');
}
});
});
});//end of document ready function
</script>
It's because you are using a relative URL, depttBranch.
This means that on http://example.com/abc the relative URL depttBranch will make an absolute URL http://example.com/abc/depttBranch while on http://example.com/abc/2 it will make http://example.com/abc/2/depttBranch.
Therefore you have to use some kind of more exact specification in the URL, for example relative to the root, e.g. /abc/depttBranch. This way it will always be http://example.com/abc/depttBranch.
i have this jquery code:
var idd = $(this).attr("id");
var page = $(this).attr("page");
var data = "lastmsg="+idd+"&page="+page;
$.ajax({
type: "POST",
url: "ajax_more.php",
data: data,
success: function(html){
$("ol#live_updates").append(html);
$("#more"+idd).remove(); // removing old more button
}
});
and this is the "ajax_more.php" code:
if(isset($_POST['lastmsg']))
{
$lastmsg = mysql_real_escape_string($_POST['lastmsg']);
$page = mysql_real_escape_string($_POST['page']);
echo $lastmsg . " " . $page;
}
Only ($lastmsg) passed, but any other parameter like ($page) is not passed. Where is the problem ??
i tried ($.post) and ($.ajax) with "POST" type, both not working...
data should be an object.
var data = {lastmsg: idd, page: page};
You need to properly encode all of your ajaxed parameters using encodeURI.
See my answer here for more information. Also, use your browser's console to debug.
I am fiddling with jQuery.ajax() and php, and I need some pointers in order to make everything work:
Here is the php code:
if(!empty($_POST["fname"])){
$firstName = $_POST["fname"];
echo $firstName."<br />";
}
if(!empty($_POST["id"])){
$age = $_POST["id"];
echo $age;
}
Here is the jQuery code:
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
});
var result;
console.log(result);
});
The values from jQuery exist, I get the alert, telling me the data has been submitted, firebug shows the Ajax post as working.
Why doesn't php gets my data and echo it?
You need to get the returned data by the php and do something with it. See the added line of code below.
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
alert("This is the data returned by the php script: " + result)
});
});
You have to use the success callback function to process the response from the POST to your Php page.
As stated in this thread
Your code could look similar to the following:
/* Send the data using post and put the results in a div */
$.ajax({
url: "test.php",
type: "post",
data: values,
success: function(returnval){
alert("success");
$("#result").html('submitted successfully:' + returnval);
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
So, you have to somehow append the response from your Php to an HTML element like a DIV using jQuery
Hope this helps you
The correct way:
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script:
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>
Is it possibe to simply load a php script with a url with js?
$(function() {
$('form').submit(function(e) {
e.preventDefault();
var title = $('#title:input').val();
var urlsStr = $("#links").val();
var urls = urlsStr.match(/\bhttps?:\/\/[^\s]+/gi);
var formData = {
"title": title,
"urls": urls
}
var jsonForm = JSON.stringify(formData);
$.ajax({
type: 'GET',
cache: false,
data: { jsonForm : jsonForm },
url: 'publishlinks/publish'
})
//load php script
});
});
Edit:
function index() {
$this->load->model('NewsFeed_model');
$data['queryMovies'] = $this->NewsFeed_model->getPublications();
$this->load->view('news_feed_view', $data);
}
simple
jQuery and:
<script>
$.get('myPHP.php', function(data) {});
</script>
Later edit:
for form use serialize:
<script>
$.post("myPHP.php", $("#myFormID").serialize());
</script>
like this ?
$.get('myPHP.php', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
There are various ways to execute a server side page using jQuery. Every method has its own configuration and at the minimum you have to specify the url which you want to request.
$.ajax
$.ajax({
type: "Get",//Since you just have to request the page
url:"test.php",
data: {},//In case you want to provide the data along with the request
success: function(data){},//If you want to do something after the request is successfull
failure: function(){}, //If you want to do something if the request fails
});
$.get
$.get("test.php");//Simplest one if you just dont care whether the call went through or not
$.post
var data = {};
$.post("test.php", data, function(data){});
You can get the form data as a json object as below
var data = $("formSelector").searialize();//This you can pass along with your request