Safari again?? Form submits bypassing AJAX - javascript

My brain is exploding - can't figure out what the issue is with Safari. All browsers work just fine, but Safari simply doesn't read my JavaScript. Not even a simple ol' 'alert()'. Any clues?
============HTML===============
</div>
<div class="container top">
<h1 class="text">Weather Dashboard</h1>
<h3 class="text">Enter the city to get a 3-day forecast</h3>
<form id="cityForm" class="form-group">
<div class="container-fixed">
<div class="form-horizontal">
<div class="input-group inpWid">
<div class="input-group-addon">
<span class="glyphicon glyphicon-home"></span>
</div>
<input type="text" class="form-control" id="city"
name="city" placeholder="Enter the City">
</div>
<button type="submit" class="btn btn-primary btn-success">Weather Me!</button>
</div>
</div>
</form>
<div class="container-fixed" id="weatherBox">
</div>
</div>
============JQuery/JavaScript===============
$("#cityForm").submit(function(e) {
e.preventDefault();
alert("safari");
var url = "scraper.php"; // the script where you handle the form input.
var city1 = $("#city").val();
var city = city1.replace(/\s+/g, '');
$.ajax({
type: "POST",
url: url,
cache:false,
data: {city, city1},
success: function(data){
$("#weatherBox").html(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
============PHP===============
$city = $_POST["city"];
$city1 = $_POST["city1"];
$url="http://www.weather-forecast.com/locations/$city/forecasts/latest";
$content = file_get_contents($url);
preg_match('/3 Day Weather Forecast Summary:<\/b>(.*?).<\/span>/s', $content, $day1);
preg_match('/7 Day Weather Forecast Summary:<\/b>(.*?).<\/span>/s', $content, $day2);
preg_match('/10 Day Weather Forecast Summary:<\/b>(.*?).<\/span>/s', $content, $day3);
for ($i=1; $i<=3; $i++) {
${d.$i} = '<img src="sun.gif" alt="sun" height="42" width="42">';
$wCon = ${day.$i}[1];
preg_match("/dry/i", $wCon, ${weather.$i});
if (${weather.$i}[0]!="dry"){
${d.$i} = '<img src="rain.png" alt="rain" height="42" width="42">';
};
unset(${weather.$i}[0]);
};
============Website===============
http://alexanderii.net/cover/

you have syntax error:-
change data: {city, city1}, to data:{'city':city,'city1':city1}
try this code:-
$.ajax({
type: "POST",
url: url,
cache:false,
data:{'city':city,'city1':city1},
success: function(data){
$("#weatherBox").html(data); // show response from the php script.
}
});

Related

Javascript - After creating a div, Ajax is not working

I have a button for a form. When I click the button, the form is created. After being created, the form is not working with Ajax. My script codes are in here. My #testform is not wrong because it's working without creating form. Do you have any ideas?
function addDiv() {
var panel = document.querySelector(".add_new");
var div = document.createElement("div");
div.innerHTML = '<br> <form id="testform" method="POST"> <div class="row" style="padding-left:10rem;"> <div class="col-md-4"> <input type="text" class="form-control" value="" placeholder="Başlık" name="yeniBaslik" required></div> <div class="col-md-4"> <input type="text" placeholder="Açıklama" name="yeniAciklama" class="form-control" value="" name="" required> </div> <div class="col-md-2 text-left"> <button type="submit" class="btn btn-success btn-animated btn-wide addToDatabase">Add to the Database</button> </div> </row> </form> <br>';
panel.appendChild(div);
}
$("#testform").submit(function(e) {
e.preventDefault();
var formData = new FormData($("#testform").get(0));
$.ajax({
url: 'config.php',
type: 'POST',
data: formData,
contentType: false,
processData: false,
success: function() {
setTimeout(
function() {
$(".addToDatabase").html("Successfully.");
}, 1000);
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="addDiv()"> Create a form </button>
<div class="add_new"></div>
Since second statement is executed before "div" is created, submit event is not being listened to on the new <form>
function addDiv() {
/*...*/
panel.appendChild(div);
$("#testform").submit(function(e) { /*...*/ });
}

How to send data from view to controller laravel with ajax?

I have problem to send data from view to controller laravel version 7
i send data from form and ul li
i have array data in javascript
my html code is :
I have problem to send data from view to controller laravel version 7
i send data from form and ul li
i have array data in javascript
<ul name="ali" id="singleFieldTags" class="tagit ui-widget ui-widget-content ui-corner-all">
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<span class="tagit-label">reza</span>
<a class="tagit-close">
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
</li>
<li class="tagit-choice ui-widget-content ui-state-default ui-corner-all tagit-choice-editable">
<span class="tagit-label">ali</span>
<a class="tagit-close">
<span class="text-icon">×</span>
<span class="ui-icon ui-icon-close"></span>
</a>
</li>
<li class="tagit-new">
<input type="text" class="ui-widget-content ui-autocomplete-input" autocomplete="off">
</li>
</ul>
<form id="form" method="post" action="/save_new" enctype="multipart/form-data">
#csrf
<div class="form-group">
<label for="title">title</label>
<input type="text" name="title" class="form-control">
</div>
<div class="form-group">
<label for="choose-file" class="custom-file-upload" id="choose-file-label">
Click Here to upload image
</label>
<br/>
<br/>
<label >no image selected !</label>
<input name="uploadDocument" type="file" id="choose-file"
accept=".jpg,.jpeg,.pdf,doc,docx,application/msword,.png" style="display: none;" />
</div>
<div class="form-group">
<label for="title">Description</label>
<textarea name="meta_description" class="form-control"></textarea>
</div>
<div class="form-group">
<label >keywords</label>
<input name="tags" id="mySingleField" value="reza,ali" type="hidden" disabled="true">
<ul name="ali" id="singleFieldTags"></ul>
</div>
<button type="submit" onclick="myF()" class="btn btn-success pull-left"> save</button>
</form>
in my javascript
<Script type="text/javascript">
function myF() {
var data2 = [];
var inputs = $(".tagit-choice");
for (var i = 0; i < inputs.length; i++) {
data2[i] = $(inputs[i]).text();
}
$.ajax({
url:'/save_new',
type: 'POST',
dataType:'json',
// data: JSON.stringify(data2),
data: JSON.stringify(data2),
contentType: 'application/json; charset=utf-8',
success: function( data ){
console.log('ok');
console.log(data);
},
error: function (xhr, b, c) {
console.log('error');
console.log("xhr=" + xhr + " b=" + b + " c=" + c);
}
});
}
when i send data from ajax i have error in console
error reza:263:37
xhr=[object Object] b=error c=
but in Request JSON
i see
0 "reza×"
1 "ali×"
Please help me Thanks
my controller is :
public function save_new(Request $request){
// dd($request->all());
dd($request->getContent());
}
my route is :
Route::POST('/save_new','Backend\AdminPostController#save_new')->name('save_new');
edit:
my problem is solved thans you all
var fd = new FormData();
var file = $("#form input[name=uploadDocument]")[0].files;
fd.append('file', file[0]);
fd.append('title', $("#form input[name=title]").val());
fd.append('description', $("#form textarea[name=meta_description]").val());
fd.append('tags', JSON.stringify(data2));
$.ajax({
type: 'post',
url: '/ok2',
contentType: false,
processData: false,
data: fd,
success: function(response) {
},
error: function (response) {},
});
I'm not sure about your work but this is one of the basic method to send data via jquery make sure to put ajaxSetup in document.ready function
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#form').on('submit',function(){
$.ajax({
type:'post',
url:$("#form").attr('action'),
data:$("#form").serializeArray(),
success:function(data){
//response
console.log(data);
}
});
});

Cannot POST / error when clicking Submit button

I am developing a login page for our mobile app using Phone gap. But whenever I clicked the Submit button, an error 'Cannot POST /' appears. Why is that so? Please see my code below.
index.html
<body>
<div class="main-info2">
<h3>Sign In</h3>
<div class="in-form">
<form id="login_form" method="post"">
<input type="text" placeholder="Username" required=" " id="email" />
<input type="password" placeholder="Password" required=" " id="password" />
<div class="check-sub">
<input type="submit" value="Login" id="login">
</div>
</form>
</div>
</div>
<div class="copy-right">
<p>Design by W3layouts</p>
</div>
</div>
<!-- //main -->
</body>
login.js
$(document).ready(function(){
do_login();
});
function do_login() {
$("#login").click(function () {
var email = $('#email').val();
var password = $('#password').val();
var dataString="email="+email+"&password="+password+"&login=";
if($.trim(email).length>0 & $.trim(password).length>0){
$.ajax({
type: 'POST',
url: "http://localhost:1234/cleverpro/login.php",
dataType: 'json',
data: dataString,
crossDomain: true,
cache: false,
beforeSend: function(){ $("#login").html('Connecting...');},
success: function(data){
if(data == "success"){
console.log("hay nako!");
alert("hala");
}else if(data == "failed"){
$("#login").html('Login');
console.log("hastang sayupa");
alert("halajud");
}
}
});
}else{
return false;
console.log("walay sulod uy");
}
});
}
login.php
<?php
include "db.php";
if(isset($_POST['login'])){
$email=mysql_real_escape_string(htmlspecialchars(trim($_POST['email'])));
$password=mysql_real_escape_string(htmlspecialchars(trim($_POST['password'])));
$login=mysql_num_rows(mysql_query("select * from `user` where `email`='$email' and `password`='$password'"));
if($login!=0){
echo "success";
}else{
echo "failed";
}
}
?>
I didn't know where did I gone wrong with this. Please help me.
First of all it would be better to use on('submit', handler) instead on click. (see Whats the difference between onclick and onsubmit?)
When you clicks "Login", default form send action happens after your javascript code finishes. It means that form POST happens to 'action' of your form that is not set in your form and is '/' by default.
You need to preventDefault action, somethink like this
$('#login_form').on('submit', function(e) {
e.preventDefault();
//Your code
});

How to reload a PHP Query with Jquery (Included Page)

I have a small snippet which is a comment system. I am trying to make it so when I press submit, the form itself will refresh and so will the comments.
I have tried using AJAX but I can't see anything actually initiating when I press "Submit".
My frontpage.php includes each element of the player.
and here is the core for the player_comments.php:
<script>
$(document).ready(function() {
var options = {
url: '',
target: '#comment-text', // target element(s) to be updated with server response
type: 'post' // 'get' or 'post', override for form's 'method' attribute
};
// bind form using 'ajaxForm'
$('#song-comment-form').ajaxForm(options);
});
</script>
<?
}
if(isset($userId)) {
/* logged in only */
}
$iComments = 0;
$qComments = $db->query("
SELECT songs_comments.*, user.id AS uId, user.username AS uName, user.avatar AS uAvatar
FROM songs_comments LEFT JOIN user ON songs_comments.userid_from = user.id
WHERE songs_comments.songid = '".$rSong->id."' ORDER BY songs_comments.id DESC");
while ($rComments = $qComments->fetch_object()) {
$showComments .= '
<img src="../'.makeAvatar($rComments->uId,$rComments->uAvatar,50).'" class="avatar float-left" alt>
<div class="comment">
<div class="comment-text">'.$rComments->text.'</div>
<div class="comment-footer">
'.$rComments->uName.' on '.dateStamp($rComments->time).'
</div>
<br style="clear:both;">
</div>
';
$iComments++;
} ?>
<div id="player-song-comments-wrap">
<div id="player-song-comments-heading"><img src="template/images/icons/comments.png" alt> Comments</div>
<div id="player-song-comments-sub-heading">
<?=isset($userId)?'Add comment':'Add comment'?>
<span id="song-comments-num"><?=$iComments?></span> comments for "<span id="song-comments-title"><?=$rSong->title?></span>"
by <span id="song-comments-artist"><?=$rSong->artist?></span>
</div>
<hr>
<form id="song-comment-form">
<input type="hidden" value="<?=$rSong->id?>" class="song-id">
<textarea class="editor" id="song-comment-textarea"></textarea><br>
<input type="submit" value="Submit"><input type="button" value="Cancel" id="hide-song-comment-form">
<hr>
</form>
<div id="player-song-comments">
<?=$showComments?>
</div>
</div>
How do I make it so that when I click submit, everything inside this include is reloaded?
here your ajax call code
<script>
$(document).ready(function(){
$("#submit_data").on('click',function(e){
$.ajax({
type:'POST',
url:"player_comments.php",
success:function(data){
console.log(data);
$("#player-song-comments-wrap").html(data)
}
});
});
});
</script>
<form id="song-comment-form">
<input type="hidden" value="<?php echo $rSong->id ?>" class="song-id">
<textarea class="editor" id="song-comment-textarea"></textarea><br>
<input type="submit" value="Submit" id="submit_data"><input type="button" value="Cancel" id="hide-song-comment-form">
<hr>
</form>
<div id="player-song-comments-wrap">
</div>
here your player_comments.php code which call in ajax url
<?php
if(isset($userId)) {
/* logged in only */
}
$iComments = 0;
$qComments = $db->query("
SELECT songs_comments.*, user.id AS uId, user.username AS uName, user.avatar AS uAvatar
FROM songs_comments LEFT JOIN user ON songs_comments.userid_from = user.id
WHERE songs_comments.songid = '".$rSong->id."' ORDER BY songs_comments.id DESC");
while ($rComments = $qComments->fetch_object()) {
$showComments .= '
<img src="../'.makeAvatar($rComments->uId,$rComments->uAvatar,50).'" class="avatar float-left" alt>
<div class="comment">
<div class="comment-text">'.$rComments->text.'</div>
<div class="comment-footer">
'.$rComments->uName.' on '.dateStamp($rComments->time).'
</div>
<br style="clear:both;">
</div>
';
$iComments++;
}
?>

Pass an image through AJAX [duplicate]

This question already has answers here:
How can I upload files asynchronously with jQuery?
(34 answers)
Closed 8 years ago.
Basically I want to pass a image file with ajax on submitting a form and retrieve the image and send it by email as an attachment file:
Here's the form :
<form role="form" action="" name="devis" id="devis" method="post" enctype="multipart/form-data" class="form-horizontal">
<fieldset>
<div class="form-group">
<label class="control-label col-md-4" for="societe">Company</label>
<div class="col-md-8">
<input type="text" class="form-control input-md col-md-8" name="societe" value="" maxlength="" id="societe">
</div>
</div>
<div class="form-group">
<label class="control-label col-md-4" for="message"><span class="required">* </span>Message</label>
<div class="col-md-8">
<textarea rows="5" name="message" class="form-control input-md col-md-8" maxlength="" required="" style="resize:none;" id="message"></textarea>
</div>
</div>
<div class="form-group" id="input_file">
<label class="control-label col-md-4" for="image_input_field">Logo</label>
<div class="col-md-8">
<div class="input-group uploaddiv">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Parcourir <input type="file" id="image_input_field" name="file">
</span>
</span>
<input type="text" class="form-control" readonly="">
</div>
</div>
</div>
<div class="form-group">
<div class="form-actions col-md-9 col-md-offset-3 text-right">
<input type="submit" value="Envoyer" name="" class="btn btn-primary" id="submit">
<input type="reset" value="Annuler" name="" class="btn btn-default" id="reset">
</div>
</div>
</fieldset>
</form>
I can't seem to find what's the error in my code ! Here's the AJAX call :
jQuery(document).on("click", "#submit", function(e) {
e.preventDefault();
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
jQuery.ajax({
url: "ajax.php",
type: "post",
data: {
'file': file,
'module' : 'ajax_data_form',
'societe': societe,
'message': message
},
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// jQuery('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
});
And here's the ajax.php:
<?php
if( isset($_POST['module']) && $_POST['module'] == "ajax_data_form" )
{
var_dump($_FILES);
}
$.ajax({
type: "POST",
url: pathname,
data: new FormData($('#devis')[0]),
processData: false,
contentType: false,
success: function (data) {
$("#divider").html(data);
}
});
and get the file data normally in $_FILES[];. Because FormData is automatically handles the multipart header in an ajax request.
can you try it
<script type="text/javascript">
$(document).ready(function() {
$("#submit").click(function() {
var fileInput = document.getElementById('image_input_field');
var file = fileInput.files[0];
var formData = new FormData();
formData.append('file', file);
// console.log(file);
var societe = $("input#societe").val();
var message = $("textarea#message").val();
$.ajax({
url: "ajax.php",
type: "POST",
data: "file="+file,
cache: false,
success: function(reponse) {
if(reponse) {
alert(reponse);
// console.log(reponse);
// $('#devis').trigger("reset");
} else {
alert('Erreur');
}
}
});
}); });
</script>
In ajax.php
just write
echo 'something';
As you may know already, it is not possible to process file uploads via ajax calls, it will be possible once HTML5 FILE I/O Api is ready and implemented by major browsers.
You can use jQuery iframe post form plugin to post data in iframe so user experience will be similar to ajax call (partial update of page).
Here is the link:
https://github.com/dogzworld/iframe-post-form
Description: "This jQuery ajax upload plugin creates a hidden iframe and sets the form's target attribute to post to that iframe. When the form is submitted, it is posted (including the file uploads) to the hidden iframe. Finally, the plugin collects the server's response from the iframe."
As mentioned you can send response from the server and display updates on your webpage accordingly.
There has to be a demo page but it is not working as of now.
You can also use it for file uploads.
Calling Example:
jQuery('#frmId').iframePostForm({
json : true,
post : function () {
//return true or false
return true;
},
complete : function (response) {
//complete event
console.log(response);
}
});
Using a Jquery Plugin Called Jquery Form plugin Link
I would suggest to simply submit the form using jquery and what ever data you want you can keep them in hidden fields.
$("#devis").ajaxSubmit(options);
return false;
The you can easily get the file in the php page like this
$ImageTempname = $_FILES['ImageFile']['tmp_name'];
$ImageFilename = $_FILES['ImageFile']['name'];
$ImageType = $_FILES['ImageFile']['type'];
and so on.....

Categories