JSONP callback successful but javascript not updating .html when jQueryMobile included - ajax

I am building a PhoneGap app using jQuery Mobile. My JSONP cross domain communication works, but have an issue when jQuery Mobile is included. Without it everything works as expected, included, it stops working.
I've reduced code to simplest form - Serialize data, encode and call CrossDomain PHP file using JSONP. Execute success function. I thought it might be bad JS but "alert" works and no JS errors. But the $('#section1').html("SECTION 1 - " + data.message); doesn't update. Note: When I remove jQM it all works!
Below is the HTML and the PHP code it calls. It's as though the jQueryMobile AJAX call is interfering with the update of the .html code. Any ideas? I'm stumped.
Ajax4d.htm
<html><head><title>First jQueryMobile Example</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script>
$(document).ready(function() {
$("#foo").submit(function(event) {
event.preventDefault();
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
var postData = serializedData;
var urlStr = "http://www.fohost.co/testURLd.php?";
alert (urlStr + encodeURI(postData));
$.ajax({
url: urlStr,
data: encodeURI(postData),
dataType: "jsonp",
success: function(data){
alert("SUCCESS callback before HTML update: " + data.message);
$('#section1').html("SECTION 1 - " + data.message);
}
});
});
});
</script>
</head>
<body>
<section id="register_page" data-role="page" data-theme="b">
<div data-role="content">
<form id="foo" method="get" action="">
<fieldset data-role="fieldcontain">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="Chris" placeholder="Username"/>
</fieldset>
<fieldset class="ui-grid-a"><input type="submit" value="Send" /></fieldset>
</form>
</div>
<div id="section1">SECTION</div>
</section>
</body>
</html>
testURLd.php
<?php
header("content-type: application/json");
$user = $_GET['username'];
$rtnjsonobj->success = "true";
$rtnjsonobj->user = $user;
$rtnjsonobj->message = "Stored User: " . $user;
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';
?>

When you use the submit() method, but fire an ajax call, you aren't prohibiting the form from submitting.
Add a return false; to the end of the $("#foo").submit method. This will prohibit the page from reloading onclick.

Use pageinit instead of document ready..
check this link..
http://jquerymobile.com/test/docs/api/events.html
try this one..
$( document ).delegate("#register_page" ,"pageinit", function() {
$("#foo").submit(function(event) {
event.preventDefault();
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
var postData = serializedData;
var urlStr = "http://www.fohost.co/testURLd.php?";
alert (urlStr + encodeURI(postData));
$.ajax({
url: urlStr,
data: encodeURI(postData),
dataType: "jsonp",
success: function(data){
alert("SUCCESS callback before HTML update: " + data.message);
$('#section1').html("SECTION 1 - " + data.message);
}
});
});
});

Related

Ajax call in razor code refreshes the page

I'm populating a folder structure using TreeView in .cs file, rendering it in the view.cshtml. When an item is clicked, I call a js function which makes an ajax call to the web api, gets the file content and supposed to display the result in a TextArea or Div.
The result comes back from web api, and displays it in the textarea momentarily and disappears. I guess it's refreshing the page. But I'm not sure how to prevent it. I have done similar stuffs before, didn't behave so. I'm sure I'm missing something, but I can't tell what I'm missing.
#{
Layout = "~/Views/Shared/_Layout.cshtml";
}
<form>
<div style="width: 100%; overflow: hidden;">
<div style="width: 600px; float: left;">
<ul>
#foreach (var node in Model.Nodes[0].ChildNodes)
{
<li>#node.Text</li>
<ul>
#foreach (var f in node.ChildNodes)
{
<li>#f.Text</li>
}
</ul>
}
</ul>
</div>
<div id="divLog" style="margin-left: 620px;overflow:auto;"><textarea id="txtLog" rows="10" cols="50"></textarea></div>
</div>
</form>
<script>
function getLog(fileref) {
var baseURL = window.location.protocol + '//' + window.location.host + '#Url.Content("~")';
var apiUrl = baseURL + "/api/logapi?fileref=" + fileref;
document.getElementById("txtLog").innerText = "";
$(document).ready(function () {
$.ajax({
url: apiUrl,
type: "GET",
success: function (data, textStatus, jqXHR) {
document.getElementById("txtLog").innerText = data;
//document.getElementById("txtLog").innerHTML = data;
//$("#txtLog").val(data);
alert(data);
}
});
});
}
</script>
Maybe another solution for any people coming here. I had the same issue in my Razor pages project when trying to call an Ajax function from a form. The page would call the correct page handler and return the Json result, however the page would always refresh, and the success part in the ajax call would not be called. What worked FOR ME was to REMOVE the form element and replace it with a div. Now the Ajax call returns correctly for me.
<div id="first" class="section"> //WHEN THIS WAS FORM THE PAGE REFRESHED
<div class="section">
#Html.HiddenFor(m => m.PersonId)
#Html.HiddenFor(m => m.ProviderId)
#Html.AntiForgeryToken()
<div class="container2">
<input type="radio" name="group1" id="radio-1" checked="checked">
<label for="radio-1"><span style="font-size:16px;" class="radio">I want to recieve all Emails (personal and marketing)</span></label>
</div>
<button onclick="setPreferences()" class="btn btn-save">Save <i class="fa fa-save"></i></button>
</div>
</div>
And the ajax:
$.ajax({
url: '/UserPreferences?handler=SetPreferences',
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify(model),
headers: {
RequestVerificationToken: $('input:hidden[name="__RequestVerificationToken"]').val()
},
success: function (response) {
console.log(response);
}
});
I used button instead of anchor link, it works as expected, it doesn't refresh the screen.
<style>
.btn1 {
background-color: transparent;
border: hidden;
}
</style>
<li><input type="button" id="a" value="#f.Text" onclick="getLog('#f.Value')" class="button btn1"></li>
First, remove the Ajax call from the document ready function:
function getLog(fileref) {
var baseURL = window.location.protocol + '//' + window.location.host + '#Url.Content("~")';
var apiUrl = baseURL + "/api/logapi?fileref=" + fileref;
document.getElementById("txtLog").innerText = "";
$.ajax({
url: apiUrl,
type: "GET",
success: function (data, textStatus, jqXHR) {
document.getElementById("txtLog").innerText = data;
//document.getElementById("txtLog").innerHTML = data;
//$("#txtLog").val(data);
alert(data);
}
});
}
Secondly, replace the empty href attribute of the anchor link by href="javascript:;" or href="#".

How to call ajax function on buttonclick in laravel?

View Code:
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Here ,When I click on the button it should be replaced by the other text. But nothings appears on clicking.
Controller code:
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
In pure js that code work fine
function getMessage(){
alert('Its working!');
}
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Looks OK.
Put a breakpoint in your success and see what data is.
Or do a console.log
Mick
in your ajax code you didn't define dataType, add dataType:"json", to retrive the json data, change your ajax code as
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
dataType:'json',
data:{
_token = '<?php echo csrf_token() ?>'
},
success:function(data){
$("#msg").html(data.msg);
}
});
Update your code with below mentioned code, and let's try.. i will working for me..
<script type="text/javascript" charset="utf-8">
$(document).on('click', '#btnSelector', function(event) {
event.preventDefault();
/* Act on the event */
getMessage();
});
var getMessage = function(){
$.ajax({
type:'POST',
url:'/getmsg', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" id='btnSelector'>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<body>
<div id='msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" id="ajax_call" value="Replace Message">
</body>
<script>
$(function () {
$('#ajax_call').on('click', function () {
$.ajax({
type:'POST',
url:'<?php echo url("/getms"); ?>',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
},
complete: function(){
alert('complete');
},
error: function(result) {
alert('error');
}
});
});
});
</script>
Jquery onclick function: jquery onclick function not defined
Also check: Function not calling within an onclick event

Post request on Mootools

I'm new to MooTools and trying to send Ajax request with form content to the url.
<form method="post" enctype="multipart/form-data" action="<?= $PHP_SELF; ?>" name="fn" id="fn">
<input name="user_name" id="user_name">
<input name="user_mail" id="user_name">
<input name="user_text" id="user_name">
<input type="file" name="attach">
<input id="button" type="button" value="Submit">
</form>
<script type="text/javascript">
$('button').addEvent('click', function(event) {
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
});
});
</script>
When I click on button, nothing happens. How right transferring data from form?
Your code looks good, you had a } missing but aside from that you just forgot to add a .send();
Like req.send();, and you can actually pass the data as a argument to that method.
Test that and check here about the .send() method.
Suggention to how your code could look like:
<script type="text/javascript">
var req = new Request({
method: 'post',
url: 'url.php',
onSuccess: function(response) {
alert(response);
} // < --- You actually missed this one
});
$('button').addEvent('click', function(event) {
req.send();
});
</script>

How get the value from a link and send the form using mootools?

I have a such form with many links:
<form name="myform" action="" method="get" id="form">
<p>
My link
</p>
<p>
My link 2
</p>
<p>
My link 3
</p>
<input type="hidden" name="division" value="" />
</form>
I would like to send the form's value from the link that was clicked to php script and get the response (not reloading the page).
I'm trying to write a function that gets the value from a link:
<script type="text/javascript">
window.addEvent('domready', function() {
getValue = function(division)
{
var division;
division=$('form').getElements('a');
}
</script>
but I don't know how to write it in a right way. Next I would like to send the form:
$$('a.del').each(function(el) {
el.addEvent('click', function(e) {
new Event(e).stop();
$('form').submit();
});
});
How I should send it to get the response from a php file not reloading the page?
Instead of putting in javascript inline in the HTML, I would suggest using a delegated event instead. I would also send the form using an ajax call instead of a form submit.
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var formEl = document.id('form');
formEl.addEvent('click:relay(.del)', function() {
var value = this.getProperty('data-value');
new Request.JSON({
url: '/path/to/your/listener',
onSuccess: function(data) {
// ...
}
}).get({
value: value
});
});
</script>
This works for me:
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var links = document.id('form').getElements('a');
links.each(function(link) {
link.addEvent('click', function(e) {
e.stop();
var value = link.getProperty('data-value');
var req = new Request.HTML({
url: "/path/to/your/listener",
data: value,
onRequest: function(){
$('display').set('text', 'Search...');
},
onComplete: function() {
},
update : $('display')
}).get(
{data: value}
);
});
})
</script>

jquery form submission

Can someone show me a tutorial of using jquery to display successful form submission without refreshing the page. Something like that happens on gmail when a message is delivered and the yellow overlay that shows that you message was delivered and then fade outs.
Use jQuery+JSON combination something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'></div>
_test.php:
<?php
// Code here to deal with your form submitted data.
$arr = array( 'testDiv' => 'Form is successfully submitted.' );
echo json_encode( $arr );
?>
jsFile.js:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
OR:
You can use jQuery Form Plugin

Resources